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