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