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