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