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