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