Merged revisions 38903-38904 via svnmerge from
[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_HOLD:
706                 ast_moh_start(c, data, NULL);
707                 if (token)
708                         free(token);
709                 return 0;
710         case AST_CONTROL_UNHOLD:
711                 ast_moh_stop(c);
712                 if (token)
713                         free(token);
714                 return 0;
715         case AST_CONTROL_PROCEEDING:
716         case -1:
717                 if (token)
718                         free(token);
719                 return -1;
720         default:
721                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d on %s\n", condition, token);
722                 if (token)
723                         free(token);
724                 return -1;
725         }
726
727         if (h323debug)
728                 ast_log(LOG_DEBUG, "OH323: Indicated %d on %s\n", condition, token);
729         if (token)
730                 free(token);
731         oh323_update_info(c);
732
733         return -1;
734 }
735
736 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
737 {
738         struct oh323_pvt *pvt = (struct oh323_pvt *) newchan->tech_pvt;
739
740         ast_mutex_lock(&pvt->lock);
741         if (pvt->owner != oldchan) {
742                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, pvt->owner);
743                 return -1;
744         }
745         pvt->owner = newchan;
746         ast_mutex_unlock(&pvt->lock);
747         return 0;
748 }
749
750 /* Private structure should be locked on a call */
751 static struct ast_channel *__oh323_new(struct oh323_pvt *pvt, int state, const char *host)
752 {
753         struct ast_channel *ch;
754         int fmt;
755         
756         /* Don't hold a oh323_pvt lock while we allocate a chanel */
757         ast_mutex_unlock(&pvt->lock);
758         ch = ast_channel_alloc(1);
759         /* Update usage counter */
760         ast_atomic_fetchadd_int(&__mod_desc->usecnt, +1);
761         ast_update_use_count();
762         ast_mutex_lock(&pvt->lock);
763         if (ch) {
764                 ch->tech = &oh323_tech;
765                 ast_string_field_build(ch, name, "H323/%s", host);
766                 ch->nativeformats = pvt->options.capability;
767                 if (!ch->nativeformats) {
768                         ch->nativeformats = global_options.capability;
769                 }
770                 pvt->nativeformats = ch->nativeformats;
771                 fmt = ast_best_codec(ch->nativeformats);
772                 ch->fds[0] = ast_rtp_fd(pvt->rtp);
773                 if (state == AST_STATE_RING) {
774                         ch->rings = 1;
775                 }
776                 ch->writeformat = fmt;
777                 ch->rawwriteformat = fmt;
778                 ch->readformat = fmt;
779                 ch->rawreadformat = fmt;
780                 /* Allocate dsp for in-band DTMF support */
781                 if (pvt->options.dtmfmode & H323_DTMF_INBAND) {
782                         pvt->vad = ast_dsp_new();
783                         ast_dsp_set_features(pvt->vad, DSP_FEATURE_DTMF_DETECT);
784                 }
785                 /* Register channel functions. */
786                 ch->tech_pvt = pvt;
787                 /*  Set the owner of this channel */
788                 pvt->owner = ch;
789                 
790                 strncpy(ch->context, pvt->context, sizeof(ch->context) - 1);
791                 strncpy(ch->exten, pvt->exten, sizeof(ch->exten) - 1);          
792                 ch->priority = 1;
793                 if (!ast_strlen_zero(pvt->accountcode)) {
794                         ast_string_field_set(ch, accountcode, pvt->accountcode);
795                 }
796                 if (pvt->amaflags) {
797                         ch->amaflags = pvt->amaflags;
798                 }
799                 
800                 /* Don't use ast_set_callerid() here because it will
801                  * generate a NewCallerID event before the NewChannel event */
802                 if (!ast_strlen_zero(pvt->cid_num)) {
803                         ch->cid.cid_num = ast_strdup(pvt->cid_num);
804                         ch->cid.cid_ani = ast_strdup(pvt->cid_num);
805                 } else {
806                         ch->cid.cid_num = ast_strdup(pvt->cd.call_source_e164);
807                         ch->cid.cid_ani = ast_strdup(pvt->cd.call_source_e164);
808                 }
809                 ch->cid.cid_name = ast_strdup(pvt->cid_name);
810                 ch->cid.cid_rdnis = ast_strdup(pvt->rdnis);
811                 
812                 if (!ast_strlen_zero(pvt->exten) && strcmp(pvt->exten, "s")) {
813                         ch->cid.cid_dnid = strdup(pvt->exten);
814                 }
815                 ast_setstate(ch, state);
816                 if (state != AST_STATE_DOWN) {
817                         if (ast_pbx_start(ch)) {
818                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ch->name);
819                                 ast_hangup(ch);
820                                 ch = NULL;
821                         }
822                 }
823
824                 /* Configure the new channel jb */
825                 if (ch && pvt && pvt->rtp)
826                         ast_jb_configure(ch, &global_jbconf);
827         } else  {
828                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
829         }
830         return ch;
831 }
832
833 static struct oh323_pvt *oh323_alloc(int callid)
834 {
835         struct oh323_pvt *pvt;
836
837         pvt = (struct oh323_pvt *) malloc(sizeof(struct oh323_pvt));
838         if (!pvt) {
839                 ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
840                 return NULL;
841         }
842         memset(pvt, 0, sizeof(struct oh323_pvt));
843         pvt->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0,bindaddr.sin_addr);
844         if (!pvt->rtp) {
845                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
846                 free(pvt);
847                 return NULL;
848         }
849         ast_rtp_settos(pvt->rtp, tos);
850         ast_mutex_init(&pvt->lock);
851         /* Ensure the call token is allocated */
852         if ((pvt->cd).call_token == NULL) {
853                 (pvt->cd).call_token = (char *)malloc(128);
854         }
855         if (!pvt->cd.call_token) {
856                 ast_log(LOG_ERROR, "Not enough memory to alocate call token\n");
857                 return NULL;
858         }
859         memset((char *)(pvt->cd).call_token, 0, 128);
860         pvt->cd.call_reference = callid;
861         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
862         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
863                 pvt->nonCodecCapability |= AST_RTP_DTMF;
864         } else {
865                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
866         }
867         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
868         pvt->newstate = pvt->newcontrol = -1;
869         /* Add to interface list */
870         ast_mutex_lock(&iflock);
871         pvt->next = iflist;
872         iflist = pvt;
873         ast_mutex_unlock(&iflock);
874         return pvt;
875 }
876
877 static struct oh323_pvt *find_call_locked(int call_reference, const char *token)
878 {  
879         struct oh323_pvt *pvt;
880
881         ast_mutex_lock(&iflock);
882         pvt = iflist; 
883         while(pvt) {
884                 if (!pvt->needdestroy && ((signed int)pvt->cd.call_reference == call_reference)) {
885                         /* Found the call */             
886                         if ((token != NULL) && (!strcmp(pvt->cd.call_token, token))) {
887                                 ast_mutex_lock(&pvt->lock);
888                                 ast_mutex_unlock(&iflock);
889                                 return pvt;
890                         } else if (token == NULL) {
891                                 ast_log(LOG_WARNING, "Call Token is NULL\n");
892                                 ast_mutex_lock(&pvt->lock);
893                                 ast_mutex_unlock(&iflock);
894                                 return pvt;
895                         }
896                 }
897                 pvt = pvt->next; 
898         }
899         ast_mutex_unlock(&iflock);
900         return NULL;
901 }
902
903 static int update_state(struct oh323_pvt *pvt, int state, int signal)
904 {
905         if (!pvt)
906                 return 0;
907         if (pvt->owner && !ast_mutex_trylock(&pvt->owner->lock)) {
908                 if (state >= 0)
909                         ast_setstate(pvt->owner, state);
910                 if (signal >= 0)
911                         ast_queue_control(pvt->owner, signal);
912                 return 1;
913         }
914         else {
915                 if (state >= 0)
916                         pvt->newstate = state;
917                 if (signal >= 0)
918                         pvt->newcontrol = signal;
919                 return 0;
920         }
921 }
922
923 struct oh323_user *find_user(const call_details_t *cd)
924 {
925         struct oh323_user *u;
926         char iabuf[INET_ADDRSTRLEN];
927         u = userl.users;
928         if (userbyalias) {
929                 while(u) {
930                         if (!strcasecmp(u->name, cd->call_source_aliases)) {
931                                 break;
932                         }
933                         u = u->next;
934                 }
935         } else {
936                 while(u) {
937                         if (!strcasecmp(cd->sourceIp, ast_inet_ntoa(iabuf, sizeof(iabuf), u->addr.sin_addr))) {
938                                 break;
939                         }
940                         u = u->next;
941                 }
942         }
943         return u;
944 }
945
946 struct oh323_peer *find_peer(const char *peer, struct sockaddr_in *sin)
947 {
948         struct oh323_peer *p = NULL;
949         static char iabuf[INET_ADDRSTRLEN];
950
951         p = peerl.peers;
952         if (peer) {
953                 while(p) {
954                         if (!strcasecmp(p->name, peer)) {
955                                 ast_log(LOG_DEBUG, "Found peer %s by name\n", peer);
956                                 break;
957                         }
958                         p = p->next;
959                 }
960         } else {
961                 /* find by sin */
962                 if (sin) {
963                         while (p) {
964                                 if ((!inaddrcmp(&p->addr, sin)) || 
965                                         (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
966                                         ast_log(LOG_DEBUG, "Found peer %s/%s by addr\n", peer, ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr));
967                                         break;
968                                 }
969                                 p = p->next;
970                         }
971                 }       
972         }
973         if (!p) {
974                 ast_log(LOG_DEBUG, "Could not find peer %s by name or address\n", peer);
975         }
976         return p;
977 }
978
979 static int create_addr(struct oh323_pvt *pvt, char *opeer)
980 {
981         struct hostent *hp;
982         struct ast_hostent ahp;
983         struct oh323_peer *p;
984         int portno;
985         int found = 0;
986         char *port;
987         char *hostn;
988         char peer[256] = "";
989
990         strncpy(peer, opeer, sizeof(peer) - 1);
991         port = strchr(peer, ':');
992         if (port) {
993                 *port = '\0';
994                 port++;
995         }
996         pvt->sa.sin_family = AF_INET;
997         ast_mutex_lock(&peerl.lock);
998         p = find_peer(peer, NULL);
999         if (p) {
1000                 found++;
1001                 memcpy(&pvt->options, &p->options, sizeof(pvt->options));
1002                 if (pvt->rtp) {
1003                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", pvt->options.nat);
1004                         ast_rtp_setnat(pvt->rtp, pvt->options.nat);
1005                 }
1006                 if (pvt->options.dtmfmode) {
1007                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1008                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1009                         } else {
1010                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1011                         }
1012                 }
1013                 if (p->addr.sin_addr.s_addr) {
1014                         pvt->sa.sin_addr = p->addr.sin_addr;    
1015                         pvt->sa.sin_port = p->addr.sin_port;    
1016                 } 
1017         }
1018         ast_mutex_unlock(&peerl.lock);
1019         if (!p && !found) {
1020                 hostn = peer;
1021                 if (port) {
1022                         portno = atoi(port);
1023                 } else {
1024                         portno = h323_signalling_port;
1025                 }               
1026                 hp = ast_gethostbyname(hostn, &ahp);
1027                 if (hp) {
1028                         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1029                         memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
1030                         pvt->sa.sin_port = htons(portno);
1031                         return 0;       
1032                 } else {
1033                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1034                         return -1;
1035                 }
1036         } else if (!p) {
1037                 return -1;
1038         } else {        
1039                 return 0;
1040         }
1041 }
1042 static struct ast_channel *oh323_request(const char *type, int format, void *data, int *cause)
1043 {
1044         int oldformat;
1045         struct oh323_pvt *pvt;
1046         struct ast_channel *tmpc = NULL;
1047         char *dest = (char *)data;
1048         char *ext, *host;
1049         char *h323id = NULL;
1050         char tmp[256], tmp1[256];
1051         
1052         ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
1053         pvt = oh323_alloc(0);
1054         if (!pvt) {
1055                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
1056                 return NULL;
1057         }       
1058         oldformat = format;
1059         format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
1060         if (!format) {
1061                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
1062                 return NULL;
1063         }
1064         strncpy(tmp, dest, sizeof(tmp) - 1);    
1065         host = strchr(tmp, '@');
1066         if (host) {
1067                 *host = '\0';
1068                 host++;
1069                 ext = tmp;
1070         } else {
1071                 host = tmp;
1072                 ext = NULL;
1073         }
1074         strtok_r(host, "/", &(h323id));         
1075         if (!ast_strlen_zero(h323id)) {
1076                 h323_set_id(h323id);
1077         }
1078         if (ext) {
1079                 strncpy(pvt->exten, ext, sizeof(pvt->exten) - 1);
1080         }
1081         ast_log(LOG_DEBUG, "Extension: %s Host: %s\n",  pvt->exten, host);
1082         if (!usingGk) {
1083                 if (create_addr(pvt, host)) {
1084                         oh323_destroy(pvt);
1085                         return NULL;
1086                 }
1087         }
1088         else {
1089                 memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1090                 if (pvt->rtp) {
1091                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", pvt->options.nat);
1092                         ast_rtp_setnat(pvt->rtp, pvt->options.nat);
1093                 }
1094                 if (pvt->options.dtmfmode) {
1095                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1096                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1097                         } else {
1098                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1099                         }
1100                 }
1101         }
1102
1103         ast_mutex_lock(&caplock);
1104         /* Generate unique channel identifier */
1105         snprintf(tmp1, sizeof(tmp1)-1, "%s-%u", host, ++unique);
1106         tmp1[sizeof(tmp1)-1] = '\0';
1107         ast_mutex_unlock(&caplock);
1108
1109         ast_mutex_lock(&pvt->lock);
1110         tmpc = __oh323_new(pvt, AST_STATE_DOWN, tmp1);
1111         ast_mutex_unlock(&pvt->lock);
1112         if (!tmpc) {
1113                 oh323_destroy(pvt);
1114         }
1115         ast_update_use_count();
1116         restart_monitor();
1117         return tmpc;
1118 }
1119
1120 /** Find a call by alias */
1121 struct oh323_alias *find_alias(const char *source_aliases)
1122 {
1123         struct oh323_alias *a;
1124
1125         a = aliasl.aliases;
1126         while(a) {
1127                 if (!strcasecmp(a->name, source_aliases)) {
1128                         break;
1129                 }
1130                 a = a->next;
1131         }
1132         return a;
1133 }
1134
1135 /**
1136   * Callback for sending digits from H.323 up to asterisk
1137   *
1138   */
1139 int send_digit(unsigned call_reference, char digit, const char *token)
1140 {
1141         struct oh323_pvt *pvt;
1142         struct ast_frame f;
1143         int res;
1144
1145         ast_log(LOG_DEBUG, "Received Digit: %c\n", digit);
1146         pvt = find_call_locked(call_reference, token); 
1147         if (!pvt) {
1148                 ast_log(LOG_ERROR, "Private structure not found in send_digit.\n");
1149                 return -1;
1150         }
1151         memset(&f, 0, sizeof(f));
1152         f.frametype = AST_FRAME_DTMF;
1153         f.subclass = digit;
1154         f.datalen = 0;
1155         f.samples = 800;
1156         f.offset = 0;
1157         f.data = NULL;
1158         f.mallocd = 0;
1159         f.src = "SEND_DIGIT";   
1160         res = ast_queue_frame(pvt->owner, &f);
1161         ast_mutex_unlock(&pvt->lock);
1162         return res;
1163 }
1164
1165 /**
1166   * Callback function used to inform the H.323 stack of the local rtp ip/port details
1167   *
1168   * Returns the local RTP information
1169   */
1170 struct rtp_info *external_rtp_create(unsigned call_reference, const char * token)
1171 {       
1172         struct oh323_pvt *pvt;
1173         struct sockaddr_in us;
1174         struct rtp_info *info;
1175
1176         info = (struct rtp_info *)malloc(sizeof(struct rtp_info));
1177         if (!info) {
1178                 ast_log(LOG_ERROR, "Unable to allocated info structure, this is very bad\n");
1179                 return NULL;
1180         }
1181         pvt = find_call_locked(call_reference, token); 
1182         if (!pvt) {
1183                 free(info);
1184                 ast_log(LOG_ERROR, "Unable to find call %s(%d)\n", token, call_reference);
1185                 return NULL;
1186         }
1187         /* figure out our local RTP port and tell the H.323 stack about it */
1188         ast_rtp_get_us(pvt->rtp, &us);
1189         ast_mutex_unlock(&pvt->lock);
1190
1191         ast_inet_ntoa(info->addr, sizeof(info->addr), us.sin_addr);
1192         info->port = ntohs(us.sin_port);
1193         if (h323debug)
1194                 ast_log(LOG_DEBUG, "Sending RTP 'US' %s:%d\n", info->addr, info->port);
1195         return info;
1196 }
1197
1198 /**
1199  * Definition taken from rtp.c for rtpPayloadType because we need it here.
1200  */
1201 struct rtpPayloadType {
1202         int isAstFormat;        /* whether the following code is an AST_FORMAT */
1203         int code;
1204 };
1205
1206 /**
1207   * Call-back function passing remote ip/port information from H.323 to asterisk 
1208   *
1209   * Returns nothing 
1210   */
1211 void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort, const char *token, int pt)
1212 {
1213         struct oh323_pvt *pvt;
1214         struct sockaddr_in them;
1215         struct rtpPayloadType rtptype;
1216
1217         if (h323debug)
1218                 ast_log(LOG_DEBUG, "Setting up RTP connection for %s\n", token);
1219
1220         /* Find the call or allocate a private structure if call not found */
1221         pvt = find_call_locked(call_reference, token); 
1222         if (!pvt) {
1223                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1224                 return;
1225         }
1226         if (pvt->alreadygone) {
1227                 ast_mutex_unlock(&pvt->lock);
1228                 return;
1229         }
1230         rtptype = ast_rtp_lookup_pt(pvt->rtp, pt);
1231         pvt->nativeformats = rtptype.code;
1232         if (pvt->owner && !ast_mutex_trylock(&pvt->owner->lock)) {
1233                 pvt->owner->nativeformats = pvt->nativeformats;
1234                 ast_set_read_format(pvt->owner, pvt->owner->readformat);
1235                 ast_set_write_format(pvt->owner, pvt->owner->writeformat);
1236                 if (pvt->options.progress_audio)
1237                         ast_queue_control(pvt->owner, AST_CONTROL_PROGRESS);
1238                 ast_mutex_unlock(&pvt->owner->lock);
1239         }
1240         else {
1241                 if (pvt->options.progress_audio)
1242                         pvt->newcontrol = AST_CONTROL_PROGRESS;
1243                 if (h323debug)
1244                         ast_log(LOG_DEBUG, "RTP connection preparation for %s is pending...\n", token);
1245         }
1246
1247         them.sin_family = AF_INET;
1248         /* only works for IPv4 */
1249         them.sin_addr.s_addr = inet_addr(remoteIp); 
1250         them.sin_port = htons(remotePort);
1251         ast_rtp_set_peer(pvt->rtp, &them);
1252
1253         ast_mutex_unlock(&pvt->lock);
1254
1255         if (h323debug)
1256                 ast_log(LOG_DEBUG, "RTP connection prepared for %s\n", token);
1257
1258         return;
1259 }
1260
1261 /**  
1262   *     Call-back function to signal asterisk that the channel has been answered 
1263   * Returns nothing
1264   */
1265 void connection_made(unsigned call_reference, const char *token)
1266 {
1267         struct oh323_pvt *pvt;
1268
1269         if (h323debug)
1270                 ast_log(LOG_DEBUG, "Call %s answered\n", token);
1271
1272         pvt = find_call_locked(call_reference, token); 
1273         if (!pvt) {
1274                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1275                 return;
1276         }
1277
1278         /* Inform asterisk about remote party connected only on outgoing calls */
1279         if (!pvt->outgoing) {
1280                 ast_mutex_unlock(&pvt->lock);
1281                 return;
1282         }
1283         if (update_state(pvt, AST_STATE_UP, AST_CONTROL_ANSWER))
1284                 ast_mutex_unlock(&pvt->owner->lock);
1285         ast_mutex_unlock(&pvt->lock);
1286         return;
1287 }
1288
1289 int progress(unsigned call_reference, const char *token, int inband)
1290 {
1291         struct oh323_pvt *pvt;
1292
1293         ast_log(LOG_DEBUG, "Received ALERT/PROGRESS message for %s tones\n", (inband ? "inband" : "self-generated"));
1294
1295         pvt = find_call_locked(call_reference, token);
1296         if (!pvt) {
1297                 ast_log(LOG_ERROR, "Private structure not found in progress.\n");
1298                 return -1;
1299         }
1300         if (!pvt->owner) {
1301                 ast_mutex_unlock(&pvt->lock);
1302                 ast_log(LOG_ERROR, "No Asterisk channel associated with private structure.\n");
1303                 return -1;
1304         }
1305         if (update_state(pvt, -1, (inband ? AST_CONTROL_PROGRESS : AST_CONTROL_RINGING)))
1306                 ast_mutex_unlock(&pvt->owner->lock);
1307         ast_mutex_unlock(&pvt->lock);
1308
1309         return 0;
1310 }
1311
1312 /**
1313  *  Call-back function for incoming calls
1314  *
1315  *  Returns 1 on success
1316  */
1317 call_options_t *setup_incoming_call(call_details_t *cd)
1318 {
1319         struct oh323_pvt *pvt;
1320         struct oh323_user *user = NULL;
1321         struct oh323_alias *alias = NULL;
1322         char iabuf[INET_ADDRSTRLEN];
1323
1324         if (h323debug)
1325                 ast_log(LOG_DEBUG, "Setting up incoming call for %s\n", cd->call_token);
1326
1327         /* allocate the call*/
1328         pvt = oh323_alloc(cd->call_reference);
1329
1330         if (!pvt) {
1331                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
1332                 return NULL;
1333         }
1334
1335         /* Populate the call details in the private structure */
1336         memcpy(&pvt->cd, cd, sizeof(pvt->cd));
1337         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1338
1339         if (h323debug) {
1340                 ast_verbose(VERBOSE_PREFIX_3 "Setting up Call\n");
1341                 ast_verbose(VERBOSE_PREFIX_3 "\tCall token:  [%s]\n", pvt->cd.call_token);
1342                 ast_verbose(VERBOSE_PREFIX_3 "\tCalling party name:  [%s]\n", pvt->cd.call_source_name);
1343                 ast_verbose(VERBOSE_PREFIX_3 "\tCalling party number:  [%s]\n", pvt->cd.call_source_e164);
1344                 ast_verbose(VERBOSE_PREFIX_3 "\tCalled party name:  [%s]\n", pvt->cd.call_dest_alias);
1345                 ast_verbose(VERBOSE_PREFIX_3 "\tCalled party number:  [%s]\n", pvt->cd.call_dest_e164);
1346         }
1347
1348         /* Decide if we are allowing Gatekeeper routed calls*/
1349         if ((!strcasecmp(cd->sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk)) {
1350                 if (!ast_strlen_zero(cd->call_dest_e164)) {
1351                         strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
1352                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1); 
1353                 } else {
1354                         alias = find_alias(cd->call_dest_alias);
1355                         if (!alias) {
1356                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd->call_dest_alias);
1357                                 return NULL;
1358                         }
1359                         strncpy(pvt->exten, alias->name, sizeof(pvt->exten) - 1);
1360                         strncpy(pvt->context, alias->context, sizeof(pvt->context) - 1);
1361                 }
1362         } else {
1363                 /* Either this call is not from the Gatekeeper 
1364                    or we are not allowing gk routed calls */
1365                 user  = find_user(cd);
1366                 if (!user) {
1367                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
1368                                 strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
1369                         } else {
1370                                 strncpy(pvt->exten, cd->call_dest_alias, sizeof(pvt->exten) - 1);
1371                         }
1372                         if (ast_strlen_zero(default_context)) {
1373                                 ast_log(LOG_ERROR, "Call from '%s' rejected due to no default context\n", pvt->cd.call_source_aliases);
1374                                 return NULL;
1375                         }
1376                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
1377                         ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd->call_source_aliases, pvt->context);
1378                         /* XXX: Is it really required??? */
1379 #if 0
1380                         memset(&pvt->options, 0, sizeof(pvt->options));
1381 #endif
1382                 } else {
1383                         if (user->host) {
1384                                 if (strcasecmp(cd->sourceIp, ast_inet_ntoa(iabuf, sizeof(iabuf), user->addr.sin_addr))) {
1385                                         if (ast_strlen_zero(user->context)) {
1386                                                 if (ast_strlen_zero(default_context)) {
1387                                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s) and no default context\n", user->name, cd->sourceIp);
1388                                                         return NULL;
1389                                                 }
1390                                                 strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
1391                                         } else {
1392                                                 strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
1393                                         }
1394                                         pvt->exten[0] = 'i';
1395                                         pvt->exten[1] = '\0';
1396                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s)s\n", user->name, cd->sourceIp);
1397                                         return NULL;    /* XXX: Hmmm... Why to setup context if we drop connection immediately??? */
1398                                 }
1399                         }
1400                         strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
1401                         memcpy(&pvt->options, &user->options, sizeof(pvt->options));
1402                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
1403                                 strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
1404                         } else {
1405                                 strncpy(pvt->exten, cd->call_dest_alias, sizeof(pvt->exten) - 1);
1406                         }
1407                         if (!ast_strlen_zero(user->accountcode)) {
1408                                 strncpy(pvt->accountcode, user->accountcode, sizeof(pvt->accountcode) - 1);
1409                         } 
1410                         if (user->amaflags) {
1411                                 pvt->amaflags = user->amaflags;
1412                         } 
1413                 } 
1414         }
1415         return &pvt->options;
1416 }
1417
1418 /**
1419  * Call-back function to start PBX when OpenH323 ready to serve incoming call
1420  *
1421  * Returns 1 on success
1422  */
1423 static int answer_call(unsigned call_reference, const char *token)
1424 {
1425         struct oh323_pvt *pvt;
1426         struct ast_channel *c = NULL;
1427
1428         if (h323debug)
1429                 ast_log(LOG_DEBUG, "Preparing Asterisk to answer for %s\n", token);
1430
1431         /* Find the call or allocate a private structure if call not found */
1432         pvt = find_call_locked(call_reference, token); 
1433         if (!pvt) {
1434                 ast_log(LOG_ERROR, "Something is wrong: answer_call\n");
1435                 return 0;
1436         }
1437         /* allocate a channel and tell asterisk about it */
1438         c = __oh323_new(pvt, AST_STATE_RINGING, pvt->cd.call_token);
1439
1440         /* And release when done */
1441         ast_mutex_unlock(&pvt->lock);
1442         if (!c) {
1443                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1444                 return 0;
1445         }
1446         return 1;
1447 }
1448
1449 /**
1450  * Call-back function to establish an outgoing H.323 call
1451  * 
1452  * Returns 1 on success 
1453  */
1454 int setup_outgoing_call(call_details_t *cd)
1455 {
1456         /* Use argument here or free it immediately */
1457         cleanup_call_details(cd);
1458
1459         return 1;
1460 }
1461
1462 /**
1463   *  Call-back function to signal asterisk that the channel is ringing
1464   *  Returns nothing
1465   */
1466 void chan_ringing(unsigned call_reference, const char *token)
1467 {
1468         struct oh323_pvt *pvt;
1469
1470         if (h323debug)
1471                 ast_log(LOG_DEBUG, "Ringing on %s\n", token);
1472
1473         pvt = find_call_locked(call_reference, token); 
1474         if (!pvt) {
1475                 ast_log(LOG_ERROR, "Something is wrong: ringing\n");
1476                 return;
1477         }
1478         if (!pvt->owner) {
1479                 ast_mutex_unlock(&pvt->lock);
1480                 ast_log(LOG_ERROR, "Channel has no owner\n");
1481                 return;
1482         }
1483         if (update_state(pvt, AST_STATE_RINGING, AST_CONTROL_RINGING))
1484                 ast_mutex_unlock(&pvt->owner->lock);
1485         ast_mutex_unlock(&pvt->lock);
1486         return;
1487 }
1488
1489 /**
1490   * Call-back function to cleanup communication
1491   * Returns nothing,
1492   */
1493 static void cleanup_connection(unsigned call_reference, const char *call_token)
1494 {       
1495         struct oh323_pvt *pvt;
1496
1497         ast_log(LOG_DEBUG, "Cleaning connection to %s\n", call_token);
1498         
1499         while (1) {
1500                 pvt = find_call_locked(call_reference, call_token); 
1501                 if (!pvt) {
1502                         if (h323debug)
1503                                 ast_log(LOG_DEBUG, "No connection for %s\n", call_token);
1504                         return;
1505                 }
1506                 if (!pvt->owner || !ast_mutex_trylock(&pvt->owner->lock))
1507                         break;
1508 #if 1
1509 #ifdef DEBUG_THREADS
1510                 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]);
1511 #else
1512                 ast_log(LOG_NOTICE, "Avoiding H.323 destory deadlock on %s\n", call_token);
1513 #endif
1514 #endif
1515                 ast_mutex_unlock(&pvt->lock);
1516                 usleep(1);
1517         }
1518         if (pvt->rtp) {
1519                 /* Immediately stop RTP */
1520                 ast_rtp_destroy(pvt->rtp);
1521                 pvt->rtp = NULL;
1522         }
1523         /* Free dsp used for in-band DTMF detection */
1524         if (pvt->vad) {
1525                 ast_dsp_free(pvt->vad);
1526                 pvt->vad = NULL;
1527         }
1528         cleanup_call_details(&pvt->cd);
1529         pvt->alreadygone = 1;
1530         /* Send hangup */       
1531         if (pvt->owner) {
1532                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1533                 ast_queue_hangup(pvt->owner);
1534                 ast_mutex_unlock(&pvt->owner->lock);
1535         }
1536         ast_mutex_unlock(&pvt->lock);
1537         if (h323debug)
1538                 ast_log(LOG_DEBUG, "Connection to %s cleaned\n", call_token);
1539         return; 
1540 }
1541
1542 static void hangup_connection(unsigned int call_reference, const char *token, int cause)
1543 {
1544         struct oh323_pvt *pvt;
1545
1546         ast_log(LOG_DEBUG, "Hanging up connection to %s with cause %d\n", token, cause);
1547         
1548         pvt = find_call_locked(call_reference, token); 
1549         if (!pvt) {
1550                 return;
1551         }
1552         if (pvt->owner && !ast_mutex_trylock(&pvt->owner->lock)) {
1553                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1554                 pvt->owner->hangupcause = pvt->hangupcause = cause;
1555                 ast_queue_hangup(pvt->owner);
1556                 ast_mutex_unlock(&pvt->owner->lock);
1557         }
1558         else {
1559                 pvt->needhangup = 1;
1560                 pvt->hangupcause = cause;
1561                 ast_log(LOG_DEBUG, "Hangup for %s is pending\n", token);
1562         }
1563         ast_mutex_unlock(&pvt->lock);
1564 }
1565
1566 void set_dtmf_payload(unsigned call_reference, const char *token, int payload)
1567 {
1568         struct oh323_pvt *pvt;
1569
1570         if (h323debug)
1571                 ast_log(LOG_DEBUG, "Setting DTMF payload to %d on %s\n", payload, token);
1572
1573         pvt = find_call_locked(call_reference, token);
1574         if (!pvt) {
1575                 return;
1576         }
1577         if (pvt->rtp) {
1578                 ast_rtp_set_rtpmap_type(pvt->rtp, payload, "audio", "telephone-event");
1579         }
1580         ast_mutex_unlock(&pvt->lock);
1581         if (h323debug)
1582                 ast_log(LOG_DEBUG, "DTMF payload on %s set to %d\n", token, payload);
1583 }
1584
1585 static void set_local_capabilities(unsigned call_reference, const char *token)
1586 {
1587         struct oh323_pvt *pvt;
1588         int capability, dtmfmode;
1589
1590         if (h323debug)
1591                 ast_log(LOG_DEBUG, "Setting capabilities for connection %s\n", token);
1592
1593         pvt = find_call_locked(call_reference, token);
1594         if (!pvt)
1595                 return;
1596         capability = pvt->options.capability;
1597         dtmfmode = pvt->options.dtmfmode;
1598         ast_mutex_unlock(&pvt->lock);
1599         h323_set_capabilities(token, capability, dtmfmode);
1600
1601         if (h323debug)
1602                 ast_log(LOG_DEBUG, "Capabilities for connection %s is set\n", token);
1603 }
1604
1605 static void *do_monitor(void *data)
1606 {
1607         int res;
1608         int reloading;
1609         struct oh323_pvt *oh323 = NULL;
1610         
1611         for(;;) {
1612                 /* Check for a reload request */
1613                 ast_mutex_lock(&h323_reload_lock);
1614                 reloading = h323_reloading;
1615                 h323_reloading = 0;
1616                 ast_mutex_unlock(&h323_reload_lock);
1617                 if (reloading) {
1618                         if (option_verbose > 0) {
1619                                 ast_verbose(VERBOSE_PREFIX_1 "Reloading H.323\n");
1620                         }
1621                         h323_do_reload();
1622                 }
1623                 /* Check for interfaces needing to be killed */
1624                 ast_mutex_lock(&iflock);
1625 restartsearch:          
1626                 oh323 = iflist;
1627                 while(oh323) {
1628                         if (oh323->needdestroy) {
1629                                 __oh323_destroy(oh323);
1630                                 goto restartsearch;
1631                         }
1632                         oh323 = oh323->next;
1633                 }
1634                 ast_mutex_unlock(&iflock);
1635                 pthread_testcancel();
1636                 /* Wait for sched or io */
1637                 res = ast_sched_wait(sched);
1638                 if ((res < 0) || (res > 1000)) {
1639                         res = 1000;
1640                 }
1641                 res = ast_io_wait(io, res);
1642                 pthread_testcancel();
1643                 ast_mutex_lock(&monlock);
1644                 if (res >= 0) {
1645                         ast_sched_runq(sched);
1646                 }
1647                 ast_mutex_unlock(&monlock);
1648         }
1649         /* Never reached */
1650         return NULL;
1651 }
1652
1653 static int restart_monitor(void)
1654 {
1655         pthread_attr_t attr;
1656         /* If we're supposed to be stopped -- stay stopped */
1657         if (monitor_thread == AST_PTHREADT_STOP) {
1658                 return 0;
1659         }
1660         if (ast_mutex_lock(&monlock)) {
1661                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1662                 return -1;
1663         }
1664         if (monitor_thread == pthread_self()) {
1665                 ast_mutex_unlock(&monlock);
1666                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1667                 return -1;
1668         }
1669         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
1670                 /* Wake up the thread */
1671                 pthread_kill(monitor_thread, SIGURG);
1672         } else {        
1673                 pthread_attr_init(&attr);
1674                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1675                 /* Start a new monitor */
1676                 if (ast_pthread_create(&monitor_thread, &attr, do_monitor, NULL) < 0) {
1677                         ast_mutex_unlock(&monlock);
1678                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1679                         return -1;
1680                 }
1681
1682         }
1683         ast_mutex_unlock(&monlock);
1684         return 0;
1685 }
1686
1687 static int h323_do_trace(int fd, int argc, char *argv[])
1688 {
1689         if (argc != 3) {
1690                 return RESULT_SHOWUSAGE;
1691         }
1692         h323_debug(1, atoi(argv[2]));
1693         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1694         return RESULT_SUCCESS;
1695 }
1696
1697 static int h323_no_trace(int fd, int argc, char *argv[])
1698 {
1699         if (argc != 3) {
1700                 return RESULT_SHOWUSAGE;
1701         }
1702         h323_debug(0,0);
1703         ast_cli(fd, "H.323 trace disabled\n");
1704         return RESULT_SUCCESS;
1705 }
1706
1707 static int h323_do_debug(int fd, int argc, char *argv[])
1708 {
1709         if (argc != 2) {
1710                 return RESULT_SHOWUSAGE;
1711         }
1712         h323debug = 1;
1713         ast_cli(fd, "H323 debug enabled\n");
1714         return RESULT_SUCCESS;
1715 }
1716
1717 static int h323_no_debug(int fd, int argc, char *argv[])
1718 {
1719         if (argc != 3) {
1720                 return RESULT_SHOWUSAGE;
1721         }
1722         h323debug = 0;
1723         ast_cli(fd, "H323 Debug disabled\n");
1724         return RESULT_SUCCESS;
1725 }
1726
1727 static int h323_gk_cycle(int fd, int argc, char *argv[])
1728 {
1729 #if 0
1730         if (argc != 3) {
1731                 return RESULT_SHOWUSAGE;
1732         }       
1733         h323_gk_urq();
1734         
1735         /* Possibly register with a GK */
1736         if (!gatekeeper_disable) {
1737                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1738                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1739                 }
1740         }
1741 #endif
1742         return RESULT_SUCCESS;
1743 }
1744
1745 static int h323_ep_hangup(int fd, int argc, char *argv[])
1746 {
1747         if (argc != 3) {
1748                 return RESULT_SHOWUSAGE;
1749         }
1750         if (h323_soft_hangup(argv[2])) {
1751                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
1752         } else { 
1753                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
1754         }
1755         return RESULT_SUCCESS;
1756 }
1757
1758 static int h323_tokens_show(int fd, int argc, char *argv[])
1759 {
1760         if (argc != 3) {
1761                 return RESULT_SHOWUSAGE;
1762         }
1763         h323_show_tokens();
1764         return RESULT_SUCCESS;
1765 }
1766
1767 static char trace_usage[] = 
1768 "Usage: h.323 trace <level num>\n"
1769 "       Enables H.323 stack tracing for debugging purposes\n";
1770
1771 static char no_trace_usage[] = 
1772 "Usage: h.323 no trace\n"
1773 "       Disables H.323 stack tracing for debugging purposes\n";
1774
1775 static char debug_usage[] = 
1776 "Usage: h.323 debug\n"
1777 "       Enables H.323 debug output\n";
1778
1779 static char no_debug_usage[] = 
1780 "Usage: h.323 no debug\n"
1781 "       Disables H.323 debug output\n";
1782
1783 static char show_codec_usage[] = 
1784 "Usage: h.323 show codec\n"
1785 "       Shows all enabled codecs\n";
1786
1787 static char show_cycle_usage[] = 
1788 "Usage: h.323 gk cycle\n"
1789 "       Manually re-register with the Gatekeper (Currently Disabled)\n";
1790
1791 static char show_hangup_usage[] = 
1792 "Usage: h.323 hangup <token>\n"
1793 "       Manually try to hang up call identified by <token>\n";
1794
1795 static char show_tokens_usage[] = 
1796 "Usage: h.323 show tokens\n"
1797 "       Print out all active call tokens\n";
1798
1799 static char h323_reload_usage[] =
1800 "Usage: h323 reload\n"
1801 "       Reloads H.323 configuration from sip.conf\n";
1802
1803 static struct ast_cli_entry  cli_trace =
1804         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1805 static struct ast_cli_entry  cli_no_trace =
1806         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1807 static struct ast_cli_entry  cli_debug =
1808         { { "h.323", "debug", NULL }, h323_do_debug, "Enable H.323 debug", debug_usage };
1809 static struct ast_cli_entry  cli_no_debug =
1810         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable H.323 debug", no_debug_usage };
1811 static struct ast_cli_entry  cli_show_codecs =
1812         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1813 static struct ast_cli_entry  cli_gk_cycle =
1814         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1815 static struct ast_cli_entry  cli_hangup_call =
1816         { { "h.323", "hangup", NULL }, h323_ep_hangup, "Manually try to hang up a call", show_hangup_usage };
1817 static struct ast_cli_entry  cli_show_tokens =
1818         { { "h.323", "show", "tokens", NULL }, h323_tokens_show, "Show all active call tokens", show_tokens_usage };
1819
1820 static int update_common_options(struct ast_variable *v, struct call_options *options)
1821 {
1822         unsigned int format;
1823         int tmp;
1824
1825         if (!strcasecmp(v->name, "allow")) {
1826                 format = ast_getformatbyname(v->value);
1827                 if (format < 1) 
1828                         ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1829                 else
1830                         options->capability |= format;
1831         } else if (!strcasecmp(v->name, "disallow")) {
1832                 format = ast_getformatbyname(v->value);
1833                 if (format < 1) 
1834                         ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1835                 else
1836                         options->capability &= ~format;
1837         } else if (!strcasecmp(v->name, "dtmfmode")) {
1838                 if (!strcasecmp(v->value, "inband")) {
1839                         options->dtmfmode = H323_DTMF_INBAND;
1840                 } else if (!strcasecmp(v->value, "rfc2833")) {
1841                         options->dtmfmode = H323_DTMF_RFC2833;
1842                 } else {
1843                         ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1844                         options->dtmfmode = H323_DTMF_RFC2833;
1845                 }
1846         } else if (!strcasecmp(v->name, "dtmfcodec")) {
1847                 tmp = atoi(v->value);
1848                 if (tmp < 96)
1849                         ast_log(LOG_WARNING, "Invalid global dtmfcodec value %s\n", v->value);
1850                 else
1851                         options->dtmfcodec = tmp;
1852         } else if (!strcasecmp(v->name, "bridge")) {
1853                 options->bridge = ast_true(v->value);
1854         } else if (!strcasecmp(v->name, "nat")) {
1855                 options->nat = ast_true(v->value);
1856         } else if (!strcasecmp(v->name, "noFastStart")) {
1857                 options->noFastStart = ast_true(v->value);
1858         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
1859                 options->noH245Tunneling = ast_true(v->value);
1860         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
1861                 options->noSilenceSuppression = ast_true(v->value);
1862         } else if (!strcasecmp(v->name, "progress_setup")) {
1863                 tmp = atoi(v->value);
1864                 if ((tmp != 0) && (tmp != 1) && (tmp != 3) && (tmp != 8)) {
1865                         ast_log(LOG_WARNING, "Invalid value %d for progress_setup at line %d, assuming 0\n", tmp, v->lineno);
1866                         tmp = 0;
1867                 }
1868                 options->progress_setup = tmp;
1869         } else if (!strcasecmp(v->name, "progress_alert")) {
1870                 tmp = atoi(v->value);
1871                 if ((tmp != 0) && (tmp != 8)) {
1872                         ast_log(LOG_WARNING, "Invalud value %d for progress_alert at line %d, assuming 0\n", tmp, v->lineno);
1873                         tmp = 0;
1874                 }
1875                 options->progress_alert = tmp;
1876         } else if (!strcasecmp(v->name, "progress_audio")) {
1877                 options->progress_audio = ast_true(v->value);
1878         } else
1879                 return 1;
1880
1881         return 0;
1882 }
1883
1884 static struct oh323_alias *build_alias(char *name, struct ast_variable *v)
1885 {
1886         struct oh323_alias *alias;
1887
1888         alias = (struct oh323_alias *)malloc(sizeof(struct oh323_alias));
1889         if (alias) {
1890                 memset(alias, 0, sizeof(struct oh323_alias));
1891                 strncpy(alias->name, name, sizeof(alias->name) - 1);
1892                 while (v) {
1893                         if (!strcasecmp(v->name, "e164")) {
1894                                 strncpy(alias->e164,  v->value, sizeof(alias->e164) - 1);
1895                         } else if (!strcasecmp(v->name, "prefix")) {
1896                                 strncpy(alias->prefix,  v->value, sizeof(alias->prefix) - 1);
1897                         } else if (!strcasecmp(v->name, "context")) {
1898                                 strncpy(alias->context,  v->value, sizeof(alias->context) - 1);
1899                         } else if (!strcasecmp(v->name, "secret")) {
1900                                 strncpy(alias->secret,  v->value, sizeof(alias->secret) - 1);
1901                         } else {
1902                                 if (strcasecmp(v->value, "h323")) {     
1903                                         ast_log(LOG_WARNING, "Keyword %s does not make sense in type=h323\n", v->value);
1904                                 }
1905                         }
1906                         v = v->next;
1907                 }
1908         }
1909         return alias;
1910 }
1911
1912 static struct oh323_user *build_user(char *name, struct ast_variable *v)
1913 {
1914         struct oh323_user *user;
1915         int format;
1916
1917         user = (struct oh323_user *)malloc(sizeof(struct oh323_user));
1918         if (user) {
1919                 memset(user, 0, sizeof(struct oh323_user));
1920                 strncpy(user->name, name, sizeof(user->name) - 1);
1921                 memcpy(&user->options, &global_options, sizeof(user->options));
1922                 /* Set default context */
1923                 strncpy(user->context, default_context, sizeof(user->context) - 1);
1924                 while(v) {
1925                         if (!strcasecmp(v->name, "context")) {
1926                                 strncpy(user->context, v->value, sizeof(user->context) - 1);
1927                         } else if (!update_common_options(v, &user->options)) {
1928                                 /* dummy */
1929                         } else if (!strcasecmp(v->name, "secret")) {
1930                                 strncpy(user->secret, v->value, sizeof(user->secret) - 1);
1931                         } else if (!strcasecmp(v->name, "callerid")) {
1932                                 strncpy(user->callerid, v->value, sizeof(user->callerid) - 1);
1933                         } else if (!strcasecmp(v->name, "accountcode")) {
1934                                 strncpy(user->accountcode, v->value, sizeof(user->accountcode) - 1);
1935                         } else if (!strcasecmp(v->name, "host")) {
1936                                 if (!strcasecmp(v->value, "dynamic")) {
1937                                         ast_log(LOG_ERROR, "A dynamic host on a type=user does not make any sense\n");
1938                                         free(user);
1939                                         return NULL;
1940                                 } else if (ast_get_ip(&user->addr, v->value)) {
1941                                         free(user);
1942                                         return NULL;
1943                                 } 
1944                                 /* Let us know we need to use ip authentication */
1945                                 user->host = 1;
1946                         } else if (!strcasecmp(v->name, "amaflags")) {
1947                                 format = ast_cdr_amaflags2int(v->value);
1948                                 if (format < 0) {
1949                                         ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
1950                                 } else {
1951                                         user->amaflags = format;
1952                                 }
1953                         }
1954                         v = v->next;
1955                 }
1956         }
1957         return user;
1958 }
1959
1960 static struct oh323_peer *build_peer(char *name, struct ast_variable *v)
1961 {
1962         struct oh323_peer *peer;
1963         struct oh323_peer *prev;
1964         struct ast_ha *oldha = NULL;
1965         int found=0;
1966
1967         prev = NULL;
1968         ast_mutex_lock(&peerl.lock);
1969         peer = peerl.peers;
1970
1971         while(peer) {
1972                 if (!strcasecmp(peer->name, name)) {    
1973                         break;
1974                 }
1975                 prev = peer;
1976                 peer = peer->next;
1977         }
1978
1979         if (peer) {
1980                 found++;
1981                 /* Already in the list, remove it and it will be added back (or FREE'd) */
1982                 if (prev) {
1983                         prev->next = peer->next;
1984                 } else {
1985                         peerl.peers = peer->next;
1986                 }
1987                 ast_mutex_unlock(&peerl.lock);
1988         } else {
1989                 ast_mutex_unlock(&peerl.lock);
1990                 peer = (struct oh323_peer*)malloc(sizeof(struct oh323_peer));
1991                 if (peer)
1992                         memset(peer, 0, sizeof(struct oh323_peer));
1993         }
1994         if (peer) {
1995                 if (!found) {
1996                         strncpy(peer->name, name, sizeof(peer->name) - 1);
1997                         peer->addr.sin_port = htons(h323_signalling_port);
1998                         peer->addr.sin_family = AF_INET;
1999                 }
2000                 oldha = peer->ha;
2001                 peer->ha = NULL;
2002                 peer->addr.sin_family = AF_INET;
2003                 memcpy(&peer->options, &global_options, sizeof(peer->options));
2004
2005                 while(v) {
2006                         if (!update_common_options(v, &peer->options)) {
2007                                 /* dummy */
2008                         } else if (!strcasecmp(v->name, "host")) {
2009                                 if (!strcasecmp(v->value, "dynamic")) {
2010                                         ast_log(LOG_ERROR, "Dynamic host configuration not implemented.\n");
2011                                         free(peer);
2012                                         return NULL;
2013                                 }
2014                                 if (ast_get_ip(&peer->addr, v->value)) {
2015                                                 ast_log(LOG_ERROR, "Could not determine IP for %s\n", v->value);
2016                                                 free(peer);
2017                                                 return NULL;
2018                                 }
2019                         } else if (!strcasecmp(v->name, "port")) {
2020                                 peer->addr.sin_port = htons(atoi(v->value));
2021                         }
2022                         v=v->next;
2023                 }
2024         }
2025         return peer;
2026 }
2027
2028 int reload_config(void)
2029 {       
2030         int format;
2031         struct ast_config *cfg;
2032         struct ast_variable *v;
2033         struct oh323_peer *peer   = NULL;
2034         struct oh323_user *user   = NULL;
2035         struct oh323_alias *alias = NULL;
2036         struct ast_hostent ahp; struct hostent *hp;
2037         char *cat;
2038         char *utype;
2039         
2040         cfg = ast_config_load(config);
2041
2042         /* We *must* have a config file otherwise stop immediately */
2043         if (!cfg) {
2044                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
2045                 return 1;
2046         }
2047         
2048        /* fire up the H.323 Endpoint */       
2049         if (!h323_end_point_exist()) {
2050                h323_end_point_create();        
2051         }
2052         h323debug = 0;
2053         memset(&bindaddr, 0, sizeof(bindaddr));
2054         memset(&global_options, 0, sizeof(global_options));
2055         global_options.dtmfcodec = 101;
2056         global_options.dtmfmode = H323_DTMF_RFC2833;
2057         global_options.capability = GLOBAL_CAPABILITY;
2058         global_options.bridge = 1;              /* Do native bridging by default */
2059
2060         /* Copy the default jb config over global_jbconf */
2061         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
2062
2063         v = ast_variable_browse(cfg, "general");
2064         while (v) {
2065                 /* handle jb conf */
2066                 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
2067                         v = v->next;
2068                         continue;
2069                 }
2070
2071                 /* Create the interface list */
2072                 if (!strcasecmp(v->name, "port")) {
2073                         h323_signalling_port = (int)strtol(v->value, NULL, 10);
2074                 } else if (!strcasecmp(v->name, "bindaddr")) {
2075                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
2076                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
2077                         } else {
2078                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
2079                         }
2080                 } else if (!strcasecmp(v->name, "tos")) {
2081                         if (sscanf(v->value, "%d", &format)) {
2082                                 tos = format & 0xff;
2083                         } else if (!strcasecmp(v->value, "lowdelay")) {
2084                                 tos = IPTOS_LOWDELAY;
2085                         } else if (!strcasecmp(v->value, "throughput")) {
2086                                 tos = IPTOS_THROUGHPUT;
2087                         } else if (!strcasecmp(v->value, "reliability")) {
2088                                 tos = IPTOS_RELIABILITY;
2089                         } else if (!strcasecmp(v->value, "mincost")) {
2090                                 tos = IPTOS_MINCOST;
2091                         } else if (!strcasecmp(v->value, "none")) {
2092                                 tos = 0;
2093                         } else {
2094                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
2095                         }
2096                 } else if (!strcasecmp(v->name, "gatekeeper")) {
2097                         if (!strcasecmp(v->value, "DISABLE")) {
2098                                 gatekeeper_disable = 1;
2099                                 usingGk = 0;
2100                         } else if (!strcasecmp(v->value, "DISCOVER")) {
2101                                 gatekeeper_disable = 0;
2102                                 gatekeeper_discover = 1;
2103                                 usingGk = 1;
2104                         } else {
2105                                 gatekeeper_disable = 0;
2106                                 usingGk = 1;
2107                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper) - 1);
2108                         }
2109                 } else if (!strcasecmp(v->name, "secret")) {
2110                         strncpy(secret, v->value, sizeof(secret) - 1);
2111                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
2112                         gkroute = ast_true(v->value);
2113                 } else if (!strcasecmp(v->name, "context")) {
2114                         strncpy(default_context, v->value, sizeof(default_context) - 1);
2115                         ast_verbose(VERBOSE_PREFIX_2 "Setting default context to %s\n", default_context);       
2116                 } else if (!strcasecmp(v->name, "UserByAlias")) {
2117                         userbyalias = ast_true(v->value);
2118                 } else if (!update_common_options(v, &global_options)) {
2119                         /* dummy */
2120                 }
2121                 v = v->next;    
2122         }
2123         
2124         cat = ast_category_browse(cfg, NULL);
2125         while(cat) {
2126                 if (strcasecmp(cat, "general")) {
2127                         utype = ast_variable_retrieve(cfg, cat, "type");
2128                         if (utype) {
2129                                 if (!strcasecmp(utype, "user")) {
2130                                         user = build_user(cat, ast_variable_browse(cfg, cat));
2131                                         if (user) {
2132                                                 ast_mutex_lock(&userl.lock);
2133                                                 user->next = userl.users;
2134                                                 userl.users = user;
2135                                                 ast_mutex_unlock(&userl.lock);
2136                                         }
2137                                 }  else if (!strcasecmp(utype, "peer")) {
2138                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
2139                                         if (peer) {
2140                                                 ast_mutex_lock(&peerl.lock);
2141                                                 peer->next = peerl.peers;
2142                                                 peerl.peers = peer;
2143                                                 ast_mutex_unlock(&peerl.lock);
2144                                         }
2145                                 }  else if (!strcasecmp(utype, "friend")) {
2146                                         user = build_user(cat, ast_variable_browse(cfg, cat));
2147                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
2148                                         if (user) {
2149                                                 ast_mutex_lock(&userl.lock);
2150                                                 user->next = userl.users;
2151                                                 userl.users = user;
2152                                                 ast_mutex_unlock(&userl.lock);
2153                                         }
2154                                         if (peer) {
2155                                                 ast_mutex_lock(&peerl.lock);
2156                                                 peer->next = peerl.peers;
2157                                                 peerl.peers = peer;
2158                                                 ast_mutex_unlock(&peerl.lock);
2159                                         }
2160                                 }  else if (!strcasecmp(utype, "h323") || !strcasecmp(utype, "alias")) {
2161                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
2162                                         if (alias) {
2163                                                 ast_mutex_lock(&aliasl.lock);
2164                                                 alias->next = aliasl.aliases;
2165                                                 aliasl.aliases = alias;
2166                                                 ast_mutex_unlock(&aliasl.lock);
2167                                         }
2168                                 } else {
2169                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
2170                                 }
2171                         } else {
2172                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
2173                         }
2174                 }
2175                 cat = ast_category_browse(cfg, cat);
2176         }
2177         ast_config_destroy(cfg);
2178
2179         /* Register our H.323 aliases if any*/
2180         while (alias) {         
2181                 if (h323_set_alias(alias)) {
2182                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
2183                         return -1;
2184                 }       
2185                 alias = alias->next;
2186         }
2187
2188         return 0;
2189 }
2190
2191 void delete_users(void)
2192 {
2193         struct oh323_user *user, *userlast;
2194         struct oh323_peer *peer;
2195         
2196         /* Delete all users */
2197         ast_mutex_lock(&userl.lock);
2198         for (user=userl.users;user;) {
2199                 userlast = user;
2200                 user=user->next;
2201                 free(userlast);
2202         }
2203         userl.users=NULL;
2204         ast_mutex_unlock(&userl.lock);
2205         ast_mutex_lock(&peerl.lock);
2206         for (peer=peerl.peers;peer;) {
2207                 /* Assume all will be deleted, and we'll find out for sure later */
2208                 peer->delme = 1;
2209                 peer = peer->next;
2210         }
2211         ast_mutex_unlock(&peerl.lock);
2212 }
2213
2214 void delete_aliases(void)
2215 {
2216         struct oh323_alias *alias, *aliaslast;
2217                 
2218         /* Delete all users */
2219         ast_mutex_lock(&aliasl.lock);
2220         for (alias=aliasl.aliases;alias;) {
2221                 aliaslast = alias;
2222                 alias=alias->next;
2223                 free(aliaslast);
2224         }
2225         aliasl.aliases=NULL;
2226         ast_mutex_unlock(&aliasl.lock);
2227 }
2228
2229 void prune_peers(void)
2230 {
2231         /* Prune peers who still are supposed to be deleted */
2232         struct oh323_peer *peer, *peerlast, *peernext;
2233         ast_mutex_lock(&peerl.lock);
2234         peerlast = NULL;
2235         for (peer=peerl.peers;peer;) {
2236                 peernext = peer->next;
2237                 if (peer->delme) {
2238                         free(peer);
2239                         if (peerlast) {
2240                                 peerlast->next = peernext;
2241                         } else {
2242                                 peerl.peers = peernext;
2243                         }
2244                 } else {
2245                         peerlast = peer;
2246                 }
2247                 peer = peernext;
2248         }
2249         ast_mutex_unlock(&peerl.lock);
2250 }
2251
2252 static int h323_reload(int fd, int argc, char *argv[])
2253 {
2254         ast_mutex_lock(&h323_reload_lock);
2255         if (h323_reloading) {
2256                 ast_verbose("Previous H.323 reload not yet done\n");
2257         } else {
2258                 h323_reloading = 1;
2259         }
2260         ast_mutex_unlock(&h323_reload_lock);
2261         restart_monitor();
2262         return 0;
2263 }
2264
2265 static int h323_do_reload(void)
2266 {
2267         delete_users();
2268         delete_aliases();
2269         prune_peers();
2270         reload_config();
2271         restart_monitor();
2272         return 0;
2273 }
2274
2275 static int reload(void *mod)
2276 {
2277         return h323_reload(0, 0, NULL);
2278 }
2279
2280 static struct ast_cli_entry  cli_h323_reload =
2281         { { "h.323", "reload", NULL }, h323_reload, "Reload H.323 configuration", h323_reload_usage };
2282
2283 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
2284 {
2285         struct oh323_pvt *pvt;
2286         pvt = (struct oh323_pvt *) chan->tech_pvt;
2287         if (pvt && pvt->rtp && pvt->options.bridge) {
2288                 return pvt->rtp;
2289         }
2290         return NULL;
2291 }
2292
2293 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
2294 {
2295         return NULL;
2296 }
2297
2298 static char *convertcap(int cap)
2299 {
2300         switch (cap) {
2301         case AST_FORMAT_G723_1:
2302                 return "G.723";
2303         case AST_FORMAT_GSM:
2304                 return "GSM";
2305         case AST_FORMAT_ULAW:
2306                 return "ULAW";
2307         case AST_FORMAT_ALAW:
2308                 return "ALAW";
2309         case AST_FORMAT_ADPCM:
2310                 return "G.728";
2311         case AST_FORMAT_G729A:
2312                 return "G.729";
2313         case AST_FORMAT_SPEEX:
2314                 return "SPEEX";
2315         case AST_FORMAT_ILBC:
2316                 return "ILBC";
2317         default:
2318                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
2319                 return NULL;
2320         }
2321 }
2322
2323 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
2324 {
2325         /* XXX Deal with Video */
2326         struct oh323_pvt *pvt;
2327         struct sockaddr_in them;
2328         struct sockaddr_in us;
2329         char *mode;
2330         char iabuf[INET_ADDRSTRLEN];
2331
2332         if (!rtp) {
2333                 return 0;
2334         }
2335
2336         mode = convertcap(chan->writeformat); 
2337         pvt = (struct oh323_pvt *) chan->tech_pvt;
2338         if (!pvt) {
2339                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
2340                 return -1;
2341         }
2342         ast_rtp_get_peer(rtp, &them);   
2343         ast_rtp_get_us(rtp, &us);
2344         h323_native_bridge(pvt->cd.call_token, ast_inet_ntoa(iabuf, sizeof(iabuf), them.sin_addr), mode);
2345         return 0;
2346 }
2347
2348 static struct ast_rtp_protocol oh323_rtp = {
2349         .type = "H323",
2350         .get_rtp_info = oh323_get_rtp_peer,
2351         .get_vrtp_info = oh323_get_vrtp_peer,
2352         .set_rtp_peer=  oh323_set_rtp_peer,
2353 };
2354
2355 static int load_module(void *mod)
2356 {
2357         int res;
2358         ast_mutex_init(&userl.lock);
2359         ast_mutex_init(&peerl.lock);
2360         ast_mutex_init(&aliasl.lock);
2361         sched = sched_context_create();
2362         if (!sched) {
2363                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2364         }
2365         io = io_context_create();
2366         if (!io) {
2367                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2368         }
2369         res = reload_config();
2370         if (res) {
2371                 return 0;
2372         } else {
2373                 /* Make sure we can register our channel type */
2374                 if (ast_channel_register(&oh323_tech)) {
2375                         ast_log(LOG_ERROR, "Unable to register channel class 'H323'\n");
2376                         h323_end_process();
2377                         return -1;
2378                 }
2379                 ast_cli_register(&cli_debug);
2380                 ast_cli_register(&cli_no_debug);
2381                 ast_cli_register(&cli_trace);
2382                 ast_cli_register(&cli_no_trace);
2383                 ast_cli_register(&cli_show_codecs);
2384                 ast_cli_register(&cli_gk_cycle);
2385                 ast_cli_register(&cli_hangup_call);
2386                 ast_cli_register(&cli_show_tokens);
2387                 ast_cli_register(&cli_h323_reload);
2388
2389                 ast_rtp_proto_register(&oh323_rtp);
2390
2391                 /* Register our callback functions */
2392                 h323_callback_register(setup_incoming_call, 
2393                                                 setup_outgoing_call,                                                     
2394                                                 external_rtp_create, 
2395                                                 setup_rtp_connection, 
2396                                                 cleanup_connection, 
2397                                                 chan_ringing,
2398                                                 connection_made, 
2399                                                 send_digit,
2400                                                 answer_call,
2401                                                 progress,
2402                                                 set_dtmf_payload,
2403                                                 hangup_connection,
2404                                                 set_local_capabilities);
2405                 /* start the h.323 listener */
2406                 if (h323_start_listener(h323_signalling_port, bindaddr)) {
2407                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
2408                         return -1;
2409                 }
2410                 /* Possibly register with a GK */
2411                 if (!gatekeeper_disable) {
2412                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
2413                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
2414                                 return 0;
2415                         }
2416                 }
2417                 /* And start the monitor for the first time */
2418                 restart_monitor();
2419         }
2420         return res;
2421 }
2422
2423 static int unload_module(void *mod)
2424 {
2425         struct oh323_pvt *p, *pl;
2426
2427         /* unregister commands */
2428         ast_cli_unregister(&cli_debug);
2429         ast_cli_unregister(&cli_no_debug);
2430         ast_cli_unregister(&cli_trace);
2431         ast_cli_unregister(&cli_no_trace);   
2432         ast_cli_unregister(&cli_show_codecs);
2433         ast_cli_unregister(&cli_gk_cycle);
2434         ast_cli_unregister(&cli_hangup_call);
2435         ast_cli_unregister(&cli_show_tokens);
2436         ast_cli_unregister(&cli_h323_reload);
2437         ast_rtp_proto_unregister(&oh323_rtp);
2438         ast_channel_unregister(&oh323_tech);
2439                 
2440         if (!ast_mutex_lock(&iflock)) {
2441                 /* hangup all interfaces if they have an owner */
2442                 p = iflist;
2443                 while(p) {
2444                         if (p->owner) {
2445                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
2446                         }
2447                         p = p->next;
2448                 }
2449                 iflist = NULL;
2450                 ast_mutex_unlock(&iflock);
2451         } else {
2452                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
2453                 return -1;
2454         }
2455         if (!ast_mutex_lock(&monlock)) {
2456                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
2457                         /* this causes a seg, anyone know why? */
2458                         pthread_cancel(monitor_thread);
2459                         pthread_kill(monitor_thread, SIGURG);
2460                         pthread_join(monitor_thread, NULL);
2461                 }
2462                 monitor_thread = AST_PTHREADT_STOP;
2463                 ast_mutex_unlock(&monlock);
2464         } else {
2465                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2466                 return -1;
2467         }
2468         if (!ast_mutex_lock(&iflock)) {
2469                 /* destroy all the interfaces and free their memory */
2470                 p = iflist;
2471                 while(p) {
2472                         pl = p;
2473                         p = p->next;
2474                         /* free associated memory */
2475                         ast_mutex_destroy(&pl->lock);
2476                         free(pl);
2477                 }
2478                 iflist = NULL;
2479                 ast_mutex_unlock(&iflock);
2480         } else {
2481                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
2482                 return -1;
2483         }
2484         h323_gk_urq();
2485         h323_end_process();
2486         io_context_destroy(io);
2487         sched_context_destroy(sched);
2488         delete_users();
2489         delete_aliases();
2490         prune_peers();
2491         ast_mutex_destroy(&aliasl.lock);
2492         ast_mutex_destroy(&userl.lock);
2493         ast_mutex_destroy(&peerl.lock);
2494         return 0; 
2495
2496
2497 static const char *description(void)
2498 {
2499         return desc;
2500 }
2501
2502 static const char *key(void)
2503 {
2504         return ASTERISK_GPL_KEY;
2505 }
2506
2507 STD_MOD(MOD_1, reload, NULL, NULL);