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