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