Formatting fixes and sanity checks Bug #4263
[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         pvt->cd.call_token = strdup(cd.call_token);
1263         pvt->cd.call_source_aliases = strdup(cd.call_source_aliases);
1264         pvt->cd.call_dest_alias = strdup(cd.call_dest_alias);
1265         pvt->cd.call_source_name = strdup(cd.call_source_name);
1266         pvt->cd.call_source_e164 = strdup(cd.call_source_e164);
1267         pvt->cd.call_dest_e164 = strdup(cd.call_dest_e164);
1268
1269         if (h323debug) {
1270                 ast_verbose(VERBOSE_PREFIX_3 "Setting up Call\n");
1271                 ast_verbose(VERBOSE_PREFIX_3 "\tCall token:  [%s]\n", pvt->cd.call_token);
1272                 ast_verbose(VERBOSE_PREFIX_3 "\tCalling party name:  [%s]\n", pvt->cd.call_source_name);
1273                 ast_verbose(VERBOSE_PREFIX_3 "\tCalling party number:  [%s]\n", pvt->cd.call_source_e164);
1274                 ast_verbose(VERBOSE_PREFIX_3 "\tCalled party name:  [%s]\n", pvt->cd.call_dest_alias);
1275                 ast_verbose(VERBOSE_PREFIX_3 "\tCalled party number:  [%s]\n", pvt->cd.call_dest_e164);
1276         }
1277
1278         /* Decide if we are allowing Gatekeeper routed calls*/
1279         if ((!strcasecmp(cd.sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk)) {
1280                 if (!ast_strlen_zero(cd.call_dest_e164)) {
1281                         strncpy(pvt->exten, cd.call_dest_e164, sizeof(pvt->exten) - 1);
1282                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1); 
1283                 } else {
1284                         alias = find_alias(cd.call_dest_alias);
1285                         if (!alias) {
1286                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd.call_dest_alias);
1287                                 return NULL;
1288                         }
1289                         strncpy(pvt->exten, alias->name, sizeof(pvt->exten) - 1);
1290                         strncpy(pvt->context, alias->context, sizeof(pvt->context) - 1);
1291                 }
1292         } else {
1293                 /* Either this call is not from the Gatekeeper 
1294                    or we are not allowing gk routed calls */
1295                 user  = find_user(&cd);
1296                 if (!user) {
1297                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
1298                                 strncpy(pvt->exten, cd.call_dest_e164, sizeof(pvt->exten) - 1);
1299                         } else {
1300                                 strncpy(pvt->exten, cd.call_dest_alias, sizeof(pvt->exten) - 1);
1301                         }
1302                         if (ast_strlen_zero(default_context)) {
1303                                 ast_log(LOG_ERROR, "Call from '%s' rejected due to no default context\n", pvt->cd.call_source_aliases);
1304                                 return NULL;
1305                         }
1306                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
1307                         ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd.call_source_aliases, pvt->context);
1308                         memset(&pvt->options, 0, sizeof(pvt->options));
1309                 } else {                                        
1310                         if (user->host) {
1311                                 if (strcasecmp(cd.sourceIp, ast_inet_ntoa(iabuf, sizeof(iabuf), user->addr.sin_addr))) {
1312                                         if (ast_strlen_zero(user->context)) {
1313                                                 if (ast_strlen_zero(default_context)) {
1314                                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s) and no default context\n", user->name, cd.sourceIp);
1315                                                         return NULL;
1316                                                 }
1317                                                 strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
1318                                         } else {
1319                                                 strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
1320                                         }
1321                                         pvt->exten[0] = 'i';
1322                                         pvt->exten[1] = '\0';
1323                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s)s\n", user->name, cd.sourceIp);
1324                                         return NULL;
1325                                 }
1326                         }
1327                         strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
1328                         pvt->bridge = user->bridge;
1329                         pvt->nat = user->nat;
1330                         memcpy(&pvt->options, &user->options, sizeof(pvt->options));
1331                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
1332                                 strncpy(pvt->exten, cd.call_dest_e164, sizeof(pvt->exten) - 1);
1333                         } else {
1334                                 strncpy(pvt->exten, cd.call_dest_alias, sizeof(pvt->exten) - 1);
1335                         }
1336                         if (!ast_strlen_zero(user->accountcode)) {
1337                                 strncpy(pvt->accountcode, user->accountcode, sizeof(pvt->accountcode) - 1);
1338                         } 
1339                         if (user->amaflags) {
1340                                 pvt->amaflags = user->amaflags;
1341                         } 
1342                 } 
1343         }
1344         return &pvt->options;
1345 }
1346
1347 /**
1348  * Call-back function to start PBX when OpenH323 ready to serve incoming call
1349  *
1350  * Returns 1 on success
1351  */
1352 static int answer_call(unsigned call_reference, const char *token)
1353 {
1354         struct oh323_pvt *pvt;
1355         struct ast_channel *c = NULL;
1356
1357         if (h323debug)
1358                 ast_log(LOG_DEBUG, "Preparing Asterisk to answer for %s\n", token);
1359
1360         /* Find the call or allocate a private structure if call not found */
1361         pvt = find_call_locked(call_reference, token); 
1362         if (!pvt) {
1363                 ast_log(LOG_ERROR, "Something is wrong: answer_call\n");
1364                 return 0;
1365         }
1366         /* allocate a channel and tell asterisk about it */
1367         c = __oh323_new(pvt, AST_STATE_RINGING, pvt->cd.call_token);
1368
1369         /* And release when done */
1370         ast_mutex_unlock(&pvt->lock);
1371         if (!c) {
1372                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1373                 return 0;
1374         }
1375         return 1;
1376 }
1377
1378 /**
1379  * Call-back function to establish an outgoing H.323 call
1380  * 
1381  * Returns 1 on success 
1382  */
1383 int setup_outgoing_call(call_details_t 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(call_details_t cd)
1423 {       
1424         struct oh323_pvt *pvt;
1425         struct ast_rtp *rtp = NULL;
1426
1427         ast_log(LOG_DEBUG, "Cleaning connection to %s\n", cd.call_token);
1428         
1429         while (1) {
1430                 pvt = find_call_locked(cd.call_reference, cd.call_token); 
1431                 if (!pvt) {
1432                         if (h323debug)
1433                                 ast_log(LOG_DEBUG, "No connection for %s\n", cd.call_token);
1434                         return;
1435                 }
1436                 if (!pvt->owner || !ast_mutex_trylock(&pvt->owner->lock))
1437                         break;
1438 #if 1
1439 #ifdef DEBUG_THREADS
1440                 ast_log(LOG_NOTICE, "Avoiding H.323 destory deadlock on %s, locked at %ld/%d by %s (%s:%d)\n", cd.call_token, pvt->owner->lock.thread, pvt->owner->lock.reentrancy, pvt->owner->lock.func, pvt->owner->lock.file, pvt->owner->lock.lineno);
1441 #else
1442                 ast_log(LOG_NOTICE, "Avoiding H.323 destory deadlock on %s\n", cd.call_token);
1443 #endif
1444 #endif
1445                 ast_mutex_unlock(&pvt->lock);
1446                 usleep(1);
1447         }
1448         if (pvt->rtp) {
1449                 rtp = pvt->rtp;
1450                 pvt->rtp = NULL;
1451                 /* Immediately stop RTP */
1452                 ast_rtp_destroy(rtp);
1453         }
1454         /* Free dsp used for in-band DTMF detection */
1455         if (pvt->vad) {
1456                 ast_dsp_free(pvt->vad);
1457                 pvt->vad = NULL;
1458         }
1459         cleanup_call_details(&pvt->cd);
1460         pvt->alreadygone = 1;
1461         /* Send hangup */       
1462         if (pvt->owner) {
1463                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1464                 ast_queue_hangup(pvt->owner);
1465                 ast_mutex_unlock(&pvt->owner->lock);
1466         }
1467         ast_mutex_unlock(&pvt->lock);
1468         if (h323debug)
1469                 ast_log(LOG_DEBUG, "Connection to %s cleaned\n", cd.call_token);
1470         return; 
1471 }
1472
1473 static void hangup_connection(unsigned int call_reference, const char *token, int cause)
1474 {
1475         struct oh323_pvt *pvt;
1476
1477         ast_log(LOG_DEBUG, "Hanging up connection to %s with cause %d\n", token, cause);
1478         
1479         pvt = find_call_locked(call_reference, token); 
1480         if (!pvt) {
1481                 return;
1482         }
1483         if (pvt->owner && !ast_mutex_trylock(&pvt->owner->lock)) {
1484                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1485                 pvt->owner->hangupcause = pvt->hangupcause = cause;
1486                 ast_queue_hangup(pvt->owner);
1487                 ast_mutex_unlock(&pvt->owner->lock);
1488         }
1489         else {
1490                 pvt->needhangup = 1;
1491                 pvt->hangupcause = cause;
1492                 ast_log(LOG_DEBUG, "Hangup for %s is pending\n", token);
1493         }
1494         ast_mutex_unlock(&pvt->lock);
1495 }
1496
1497 void set_dtmf_payload(unsigned call_reference, const char *token, int payload)
1498 {
1499         struct oh323_pvt *pvt;
1500
1501         if (h323debug)
1502                 ast_log(LOG_DEBUG, "Setting DTMF payload to %d on %s\n", payload, token);
1503
1504         pvt = find_call_locked(call_reference, token);
1505         if (!pvt) {
1506                 return;
1507         }
1508         if (pvt->rtp) {
1509                 ast_rtp_set_rtpmap_type(pvt->rtp, payload, "audio", "telephone-event");
1510         }
1511         ast_mutex_unlock(&pvt->lock);
1512         if (h323debug)
1513                 ast_log(LOG_DEBUG, "DTMF payload on %s set to %d\n", token, payload);
1514 }
1515
1516 static void *do_monitor(void *data)
1517 {
1518         int res;
1519         int reloading;
1520         struct oh323_pvt *oh323 = NULL;
1521         
1522         for(;;) {
1523                  /* Check for a reload request */
1524                 ast_mutex_lock(&h323_reload_lock);
1525                 reloading = h323_reloading;
1526                 h323_reloading = 0;
1527                 ast_mutex_unlock(&h323_reload_lock);
1528                 if (reloading) {
1529                         if (option_verbose > 0) {
1530                                 ast_verbose(VERBOSE_PREFIX_1 "Reloading H.323\n");
1531                         }
1532                         h323_do_reload();
1533                 }
1534                 /* Check for interfaces needing to be killed */
1535                 ast_mutex_lock(&iflock);
1536 restartsearch:          
1537                 oh323 = iflist;
1538                 while(oh323) {
1539                         if (oh323->needdestroy) {
1540                                 __oh323_destroy(oh323);
1541                                 goto restartsearch;
1542                         }
1543                         oh323 = oh323->next;
1544                 }
1545                 ast_mutex_unlock(&iflock);
1546                 pthread_testcancel();
1547                 /* Wait for sched or io */
1548                 res = ast_sched_wait(sched);
1549                 if ((res < 0) || (res > 1000)) {
1550                         res = 1000;
1551                 }
1552                 res = ast_io_wait(io, res);
1553                 pthread_testcancel();
1554                 ast_mutex_lock(&monlock);
1555                 if (res >= 0) {
1556                         ast_sched_runq(sched);
1557                 }
1558                 ast_mutex_unlock(&monlock);
1559         }
1560         /* Never reached */
1561         return NULL;
1562 }
1563
1564 static int restart_monitor(void)
1565 {
1566         pthread_attr_t attr;
1567         /* If we're supposed to be stopped -- stay stopped */
1568         if (monitor_thread == AST_PTHREADT_STOP) {
1569                 return 0;
1570         }
1571         if (ast_mutex_lock(&monlock)) {
1572                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1573                 return -1;
1574         }
1575         if (monitor_thread == pthread_self()) {
1576                 ast_mutex_unlock(&monlock);
1577                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1578                 return -1;
1579         }
1580         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
1581                 /* Wake up the thread */
1582                 pthread_kill(monitor_thread, SIGURG);
1583         } else {        
1584                 pthread_attr_init(&attr);
1585                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1586                 /* Start a new monitor */
1587                 if (ast_pthread_create(&monitor_thread, &attr, do_monitor, NULL) < 0) {
1588                         ast_mutex_unlock(&monlock);
1589                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1590                         return -1;
1591                 }
1592
1593         }
1594         ast_mutex_unlock(&monlock);
1595         return 0;
1596 }
1597
1598 static int h323_do_trace(int fd, int argc, char *argv[])
1599 {
1600         if (argc != 3) {
1601                 return RESULT_SHOWUSAGE;
1602         }
1603         h323_debug(1, atoi(argv[2]));
1604         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1605         return RESULT_SUCCESS;
1606 }
1607
1608 static int h323_no_trace(int fd, int argc, char *argv[])
1609 {
1610         if (argc != 3) {
1611                 return RESULT_SHOWUSAGE;
1612         }
1613         h323_debug(0,0);
1614         ast_cli(fd, "H.323 trace disabled\n");
1615         return RESULT_SUCCESS;
1616 }
1617
1618 static int h323_do_debug(int fd, int argc, char *argv[])
1619 {
1620         if (argc != 2) {
1621                 return RESULT_SHOWUSAGE;
1622         }
1623         h323debug = 1;
1624         ast_cli(fd, "H323 debug enabled\n");
1625         return RESULT_SUCCESS;
1626 }
1627
1628 static int h323_no_debug(int fd, int argc, char *argv[])
1629 {
1630         if (argc != 3) {
1631                 return RESULT_SHOWUSAGE;
1632         }
1633         h323debug = 0;
1634         ast_cli(fd, "H323 Debug disabled\n");
1635         return RESULT_SUCCESS;
1636 }
1637
1638 static int h323_gk_cycle(int fd, int argc, char *argv[])
1639 {
1640 #if 0
1641         if (argc != 3) {
1642                 return RESULT_SHOWUSAGE;
1643         }       
1644         h323_gk_urq();
1645         
1646         /* Possibly register with a GK */
1647         if (!gatekeeper_disable) {
1648                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1649                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1650                 }
1651         }
1652 #endif
1653         return RESULT_SUCCESS;
1654 }
1655
1656 static int h323_ep_hangup(int fd, int argc, char *argv[])
1657 {
1658         if (argc != 3) {
1659                 return RESULT_SHOWUSAGE;
1660         }
1661         if (h323_soft_hangup(argv[2])) {
1662                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
1663         } else { 
1664                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
1665         }
1666         return RESULT_SUCCESS;
1667 }
1668
1669 static int h323_tokens_show(int fd, int argc, char *argv[])
1670 {
1671         if (argc != 3) {
1672                 return RESULT_SHOWUSAGE;
1673         }
1674         h323_show_tokens();
1675         return RESULT_SUCCESS;
1676 }
1677
1678 static char trace_usage[] = 
1679 "Usage: h.323 trace <level num>\n"
1680 "       Enables H.323 stack tracing for debugging purposes\n";
1681
1682 static char no_trace_usage[] = 
1683 "Usage: h.323 no trace\n"
1684 "       Disables H.323 stack tracing for debugging purposes\n";
1685
1686 static char debug_usage[] = 
1687 "Usage: h.323 debug\n"
1688 "       Enables H.323 debug output\n";
1689
1690 static char no_debug_usage[] = 
1691 "Usage: h.323 no debug\n"
1692 "       Disables H.323 debug output\n";
1693
1694 static char show_codec_usage[] = 
1695 "Usage: h.323 show codec\n"
1696 "       Shows all enabled codecs\n";
1697
1698 static char show_cycle_usage[] = 
1699 "Usage: h.323 gk cycle\n"
1700 "       Manually re-register with the Gatekeper (Currently Disabled)\n";
1701
1702 static char show_hangup_usage[] = 
1703 "Usage: h.323 hangup <token>\n"
1704 "       Manually try to hang up call identified by <token>\n";
1705
1706 static char show_tokens_usage[] = 
1707 "Usage: h.323 show tokens\n"
1708 "       Print out all active call tokens\n";
1709
1710 static char h323_reload_usage[] =
1711 "Usage: h323 reload\n"
1712 "       Reloads H.323 configuration from sip.conf\n";
1713
1714 static struct ast_cli_entry  cli_trace =
1715         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1716 static struct ast_cli_entry  cli_no_trace =
1717         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1718 static struct ast_cli_entry  cli_debug =
1719         { { "h.323", "debug", NULL }, h323_do_debug, "Enable H.323 debug", debug_usage };
1720 static struct ast_cli_entry  cli_no_debug =
1721         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable H.323 debug", no_debug_usage };
1722 static struct ast_cli_entry  cli_show_codecs =
1723         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1724 static struct ast_cli_entry  cli_gk_cycle =
1725         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1726 static struct ast_cli_entry  cli_hangup_call =
1727         { { "h.323", "hangup", NULL }, h323_ep_hangup, "Manually try to hang up a call", show_hangup_usage };
1728 static struct ast_cli_entry  cli_show_tokens =
1729         { { "h.323", "show", "tokens", NULL }, h323_tokens_show, "Show all active call tokens", show_tokens_usage };
1730
1731 static struct oh323_alias *build_alias(char *name, struct ast_variable *v)
1732 {
1733         struct oh323_alias *alias;
1734
1735         alias = (struct oh323_alias *)malloc(sizeof(struct oh323_alias));
1736         if (alias) {
1737                 memset(alias, 0, sizeof(struct oh323_alias));
1738                 strncpy(alias->name, name, sizeof(alias->name) - 1);
1739                 while (v) {
1740                         if (!strcasecmp(v->name, "e164")) {
1741                                 strncpy(alias->e164,  v->value, sizeof(alias->e164) - 1);
1742                         } else if (!strcasecmp(v->name, "prefix")) {
1743                                 strncpy(alias->prefix,  v->value, sizeof(alias->prefix) - 1);
1744                         } else if (!strcasecmp(v->name, "context")) {
1745                                 strncpy(alias->context,  v->value, sizeof(alias->context) - 1);
1746                         } else if (!strcasecmp(v->name, "secret")) {
1747                                 strncpy(alias->secret,  v->value, sizeof(alias->secret) - 1);
1748                         } else {
1749                                 if (strcasecmp(v->value, "h323")) {     
1750                                         ast_log(LOG_WARNING, "Keyword %s does not make sense in type=h323\n", v->value);
1751                                 }
1752                         }
1753                         v = v->next;
1754                 }
1755         }
1756         return alias;
1757 }
1758
1759 static struct oh323_user *build_user(char *name, struct ast_variable *v)
1760 {
1761         struct oh323_user *user;
1762         int format;
1763
1764         user = (struct oh323_user *)malloc(sizeof(struct oh323_user));
1765         if (user) {
1766                 memset(user, 0, sizeof(struct oh323_user));
1767                 strncpy(user->name, name, sizeof(user->name) - 1);
1768                 memcpy(&user->options, &global_options, sizeof(user->options));
1769                 user->capability = capability;
1770                 /* set a native brigding default value */
1771                 user->bridge = bridging;
1772                 /* and default context */
1773                 strncpy(user->context, default_context, sizeof(user->context) - 1);
1774                 while(v) {
1775                         if (!strcasecmp(v->name, "context")) {
1776                                 strncpy(user->context, v->value, sizeof(user->context) - 1);
1777                         } else if (!strcasecmp(v->name, "bridge")) {
1778                                 user->bridge = ast_true(v->value);
1779                         } else if (!strcasecmp(v->name, "nat")) {
1780                                 user->nat = ast_true(v->value);
1781                         } else if (!strcasecmp(v->name, "noFastStart")) {
1782                                 user->options.noFastStart = ast_true(v->value);
1783                         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
1784                                 user->options.noH245Tunneling = ast_true(v->value);
1785                         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
1786                                 user->options.noSilenceSuppression = ast_true(v->value);
1787                         } else if (!strcasecmp(v->name, "secret")) {
1788                                 strncpy(user->secret, v->value, sizeof(user->secret) - 1);
1789                         } else if (!strcasecmp(v->name, "callerid")) {
1790                                 strncpy(user->callerid, v->value, sizeof(user->callerid) - 1);
1791                         } else if (!strcasecmp(v->name, "accountcode")) {
1792                                 strncpy(user->accountcode, v->value, sizeof(user->accountcode) - 1);
1793                         } else if (!strcasecmp(v->name, "progress_setup")) {
1794                                 int progress_setup = atoi(v->value);
1795                                 if ((progress_setup != 0) &&
1796                                    (progress_setup != 1) &&
1797                                    (progress_setup != 3) &&
1798                                    (progress_setup != 8)) {
1799                                         ast_log(LOG_WARNING, "Invalid value %d for progress_setup at line %d, assuming 0\n", progress_setup, v->lineno);
1800                                         progress_setup = 0;
1801                                 }
1802                                 user->options.progress_setup = progress_setup;
1803                         } else if (!strcasecmp(v->name, "progress_alert")) {
1804                                 int progress_alert = atoi(v->value);
1805                                 if ((progress_alert != 0) &&
1806                                    (progress_alert != 8)) {
1807                                         ast_log(LOG_WARNING, "Invalud value %d for progress_alert at line %d, assuming 0\n", progress_alert, v->lineno);
1808                                         progress_alert = 0;
1809                                 }
1810                                 user->options.progress_alert = progress_alert;
1811                         } else if (!strcasecmp(v->name, "progress_audio")) {
1812                                 user->options.progress_audio = ast_true(v->value);
1813                         } else if (!strcasecmp(v->name, "dtmfcodec")) {
1814                                 user->options.dtmfcodec = atoi(v->value);
1815                         } else if (!strcasecmp(v->name, "dtmfmode")) {
1816                                 if (!strcasecmp(v->value, "inband")) {
1817                                         user->dtmfmode = H323_DTMF_INBAND;
1818                                 } else if (!strcasecmp(v->value, "rfc2833")) {
1819                                         user->dtmfmode = H323_DTMF_RFC2833;
1820                                 } else {
1821                                         ast_log(LOG_WARNING, "Unknown DTMF Mode %s, using RFC2833\n", v->value);
1822                                         user->dtmfmode = H323_DTMF_RFC2833;
1823                                 }       
1824                         } else if (!strcasecmp(v->name, "allow")) {
1825                                 format = ast_getformatbyname(v->value);
1826                                 if (format < 1) {
1827                                         ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1828                                 } else {
1829                                         user->capability |= format;
1830                                 }
1831                         } else if (!strcasecmp(v->name, "disallow")) {
1832                                 format = ast_getformatbyname(v->value);
1833                                 if (format < 1) {
1834                                         ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1835                                 } else {
1836                                         user->capability &= ~format;
1837                                 }
1838                         } else if (!strcasecmp(v->name, "host")) {
1839                                 if (!strcasecmp(v->value, "dynamic")) {
1840                                         ast_log(LOG_ERROR, "A dynamic host on a type=user does not make any sense\n");
1841                                         free(user);
1842                                         return NULL;
1843                                 } else if (ast_get_ip(&user->addr, v->value)) {
1844                                         free(user);
1845                                         return NULL;
1846                                 } 
1847                                 /* Let us know we need to use ip authentication */
1848                                 user->host = 1;
1849                         } else if (!strcasecmp(v->name, "amaflags")) {
1850                                 format = ast_cdr_amaflags2int(v->value);
1851                                 if (format < 0) {
1852                                         ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
1853                                 } else {
1854                                         user->amaflags = format;
1855                                 }
1856                         }
1857                         v = v->next;
1858                 }
1859         }
1860         return user;
1861 }
1862
1863 static struct oh323_peer *build_peer(char *name, struct ast_variable *v)
1864 {
1865         struct oh323_peer *peer;
1866         struct oh323_peer *prev;
1867         struct ast_ha *oldha = NULL;
1868         int found=0;
1869         int format;     
1870
1871         prev = NULL;
1872         ast_mutex_lock(&peerl.lock);
1873         peer = peerl.peers;
1874
1875         while(peer) {
1876                 if (!strcasecmp(peer->name, name)) {    
1877                         break;
1878                 }
1879                 prev = peer;
1880                 peer = peer->next;
1881         }
1882
1883         if (peer) {
1884                 found++;
1885                 /* Already in the list, remove it and it will be added back (or FREE'd) */
1886                 if (prev) {
1887                         prev->next = peer->next;
1888                 } else {
1889                         peerl.peers = peer->next;
1890                 }
1891                 ast_mutex_unlock(&peerl.lock);
1892         } else {
1893                 ast_mutex_unlock(&peerl.lock);
1894                 peer = (struct oh323_peer*)malloc(sizeof(struct oh323_peer));
1895                 if (peer)
1896                         memset(peer, 0, sizeof(struct oh323_peer));
1897         }
1898         if (peer) {
1899                 if (!found) {
1900                         strncpy(peer->name, name, sizeof(peer->name) - 1);
1901                         peer->addr.sin_port = htons(h323_signalling_port);
1902                         peer->addr.sin_family = AF_INET;
1903                 }
1904                 oldha = peer->ha;
1905                 peer->ha = NULL;
1906                 peer->addr.sin_family = AF_INET;
1907                 peer->capability = capability;
1908                 peer->dtmfmode = dtmfmode;
1909                 peer->bridge = bridging;
1910                 memcpy(&peer->options, &global_options, sizeof(peer->options));
1911
1912                 while(v) {
1913                         if (!strcasecmp(v->name, "bridge")) {
1914                                 peer->bridge = ast_true(v->value);
1915                         } else if (!strcasecmp(v->name, "nat")) {
1916                                 peer->nat = ast_true(v->value);
1917                         } else if (!strcasecmp(v->name, "noFastStart")) {
1918                                 peer->options.noFastStart = ast_true(v->value);
1919                         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
1920                                 peer->options.noH245Tunneling = ast_true(v->value);
1921                         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
1922                                 peer->options.noSilenceSuppression = ast_true(v->value);
1923                         } else if (!strcasecmp(v->name, "progress_setup")) {
1924                                 int progress_setup = atoi(v->value);
1925                                 if ((progress_setup != 0) &&
1926                                    (progress_setup != 1) &&
1927                                    (progress_setup != 3) &&
1928                                    (progress_setup != 8)) {
1929                                         ast_log(LOG_WARNING, "Invalid value %d for progress_setup at line %d, assuming 0\n", progress_setup, v->lineno);
1930                                         progress_setup = 0;
1931                                 }
1932                                 peer->options.progress_setup = progress_setup;
1933                         } else if (!strcasecmp(v->name, "progress_alert")) {
1934                                 int progress_alert = atoi(v->value);
1935                                 if ((progress_alert != 0) &&
1936                                    (progress_alert != 8)) {
1937                                         ast_log(LOG_WARNING, "Invalid value %d for progress_alert at line %d, assuming 0\n", progress_alert, v->lineno);
1938                                         progress_alert = 0;
1939                                 }
1940                                 peer->options.progress_alert = progress_alert;
1941                         } else if (!strcasecmp(v->name, "progress_audio")) {
1942                                 peer->options.progress_audio = ast_true(v->value);
1943                         } else if (!strcasecmp(v->name, "dtmfcodec")) {
1944                                 peer->options.dtmfcodec = atoi(v->value);
1945                         } else if (!strcasecmp(v->name, "dtmfmode")) {
1946                                 if (!strcasecmp(v->value, "inband")) {
1947                                         peer->dtmfmode = H323_DTMF_INBAND;
1948                                 } else if (!strcasecmp(v->value, "rfc2833")) {
1949                                         peer->dtmfmode = H323_DTMF_RFC2833;
1950                                 } else {
1951                                         ast_log(LOG_WARNING, "Unknown DTMF Mode %s, using RFC2833\n", v->value);
1952                                         peer->dtmfmode = H323_DTMF_RFC2833;
1953                                 }       
1954                         } else if (!strcasecmp(v->name, "allow")) {
1955                                 format = ast_getformatbyname(v->value);
1956                                 if (format < 1) {
1957                                         ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1958                                 } else {
1959                                         peer->capability |= format;
1960                                 }
1961                         } else if (!strcasecmp(v->name, "disallow")) {
1962                                 format = ast_getformatbyname(v->value);
1963                                 if (format < 1) {
1964                                         ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1965                                 } else {
1966                                         peer->capability &= ~format;
1967                                 }
1968                         } else if (!strcasecmp(v->name, "host")) {
1969                                 if (!strcasecmp(v->value, "dynamic")) {
1970                                         ast_log(LOG_ERROR, "Dynamic host configuration not implemented.\n");
1971                                         free(peer);
1972                                         return NULL;
1973                                 }
1974                                 if (ast_get_ip(&peer->addr, v->value)) {
1975                                                 ast_log(LOG_ERROR, "Could not determine IP for %s\n", v->value);
1976                                                 free(peer);
1977                                                 return NULL;
1978                                 }
1979                         } else if (!strcasecmp(v->name, "port")) {
1980                                 peer->addr.sin_port = htons(atoi(v->value));
1981                         }
1982                         v=v->next;
1983                 }
1984         }
1985         return peer;
1986 }
1987
1988 int reload_config(void)
1989 {       
1990         int format;
1991         struct ast_config *cfg;
1992         struct ast_variable *v;
1993         struct oh323_peer *peer   = NULL;
1994         struct oh323_user *user   = NULL;
1995         struct oh323_alias *alias = NULL;
1996         struct ast_hostent ahp; struct hostent *hp;
1997         char *cat;
1998         char *utype;
1999         
2000         cfg = ast_config_load(config);
2001
2002         /* We *must* have a config file otherwise stop immediately */
2003         if (!cfg) {
2004                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
2005                 return 1;
2006         }
2007         
2008        /* fire up the H.323 Endpoint */       
2009         if (!h323_end_point_exist()) {
2010                h323_end_point_create();        
2011         }
2012         h323debug = 0;
2013         dtmfmode = H323_DTMF_RFC2833;
2014         memset(&bindaddr, 0, sizeof(bindaddr));
2015         memset(&global_options, 0, sizeof(global_options));
2016         global_options.dtmfcodec = 101;
2017         v = ast_variable_browse(cfg, "general");
2018         while(v) {
2019                 /* Create the interface list */
2020                 if (!strcasecmp(v->name, "port")) {
2021                         h323_signalling_port = (int)strtol(v->value, NULL, 10);
2022                 } else if (!strcasecmp(v->name, "bindaddr")) {
2023                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
2024                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
2025                         } else {
2026                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
2027                         }
2028                 } else if (!strcasecmp(v->name, "allow")) {
2029                         format = ast_getformatbyname(v->value);
2030                         if (format < 1) 
2031                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
2032                         else
2033                                 capability |= format;
2034                 } else if (!strcasecmp(v->name, "disallow")) {
2035                         format = ast_getformatbyname(v->value);
2036                         if (format < 1) 
2037                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
2038                         else
2039                                 capability &= ~format;
2040                 } else if (!strcasecmp(v->name, "tos")) {
2041                         if (sscanf(v->value, "%d", &format)) {
2042                                 tos = format & 0xff;
2043                         } else if (!strcasecmp(v->value, "lowdelay")) {
2044                                 tos = IPTOS_LOWDELAY;
2045                         } else if (!strcasecmp(v->value, "throughput")) {
2046                                 tos = IPTOS_THROUGHPUT;
2047                         } else if (!strcasecmp(v->value, "reliability")) {
2048                                 tos = IPTOS_RELIABILITY;
2049                         } else if (!strcasecmp(v->value, "mincost")) {
2050                                 tos = IPTOS_MINCOST;
2051                         } else if (!strcasecmp(v->value, "none")) {
2052                                 tos = 0;
2053                         } else {
2054                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
2055                         }
2056                 } else if (!strcasecmp(v->name, "gatekeeper")) {
2057                         if (!strcasecmp(v->value, "DISABLE")) {
2058                                 gatekeeper_disable = 1;
2059                                 usingGk = 0;
2060                         } else if (!strcasecmp(v->value, "DISCOVER")) {
2061                                 gatekeeper_disable = 0;
2062                                 gatekeeper_discover = 1;
2063                                 usingGk = 1;
2064                         } else {
2065                                 gatekeeper_disable = 0;
2066                                 usingGk = 1;
2067                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper) - 1);
2068                         }
2069                 } else if (!strcasecmp(v->name, "secret")) {
2070                         strncpy(secret, v->value, sizeof(secret) - 1);
2071                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
2072                         gkroute = ast_true(v->value);
2073                 } else if (!strcasecmp(v->name, "context")) {
2074                         strncpy(default_context, v->value, sizeof(default_context) - 1);
2075                         ast_verbose(VERBOSE_PREFIX_2 "Setting default context to %s\n", default_context);       
2076                 } else if (!strcasecmp(v->name, "dtmfmode")) {
2077                         if (!strcasecmp(v->value, "inband")) {
2078                                 dtmfmode=H323_DTMF_INBAND;
2079                         } else if (!strcasecmp(v->value, "rfc2833")) {
2080                                 dtmfmode = H323_DTMF_RFC2833;
2081                         } else {
2082                                 ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
2083                                 dtmfmode = H323_DTMF_RFC2833;
2084                         }
2085                 } else if (!strcasecmp(v->name, "dtmfcodec")) {
2086                         global_options.dtmfcodec = atoi(v->value);
2087                 } else if (!strcasecmp(v->name, "UserByAlias")) {
2088                         userbyalias = ast_true(v->value);
2089                 } else if (!strcasecmp(v->name, "bridge")) {
2090                         bridging = ast_true(v->value);
2091                 } else if (!strcasecmp(v->name, "noFastStart")) {
2092                         global_options.noFastStart = ast_true(v->value);
2093                 } else if (!strcasecmp(v->name, "noH245Tunneling")) {
2094                         global_options.noH245Tunneling = ast_true(v->value);
2095                 } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
2096                         global_options.noSilenceSuppression = ast_true(v->value);
2097                 }
2098                 v = v->next;    
2099         }
2100         
2101         cat = ast_category_browse(cfg, NULL);
2102         while(cat) {
2103                 if (strcasecmp(cat, "general")) {
2104                         utype = ast_variable_retrieve(cfg, cat, "type");
2105                         if (utype) {
2106                                 if (!strcasecmp(utype, "user")) {
2107                                         user = build_user(cat, ast_variable_browse(cfg, cat));
2108                                         if (user) {
2109                                                 ast_mutex_lock(&userl.lock);
2110                                                 user->next = userl.users;
2111                                                 userl.users = user;
2112                                                 ast_mutex_unlock(&userl.lock);
2113                                         }
2114                                 }  else if (!strcasecmp(utype, "peer")) {
2115                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
2116                                         if (peer) {
2117                                                 ast_mutex_lock(&peerl.lock);
2118                                                 peer->next = peerl.peers;
2119                                                 peerl.peers = peer;
2120                                                 ast_mutex_unlock(&peerl.lock);
2121                                         }
2122                                 }  else if (!strcasecmp(utype, "friend")) {
2123                                         user = build_user(cat, ast_variable_browse(cfg, cat));
2124                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
2125                                         if (user) {
2126                                                 ast_mutex_lock(&userl.lock);
2127                                                 user->next = userl.users;
2128                                                 userl.users = user;
2129                                                 ast_mutex_unlock(&userl.lock);
2130                                         }
2131                                         if (peer) {
2132                                                 ast_mutex_lock(&peerl.lock);
2133                                                 peer->next = peerl.peers;
2134                                                 peerl.peers = peer;
2135                                                 ast_mutex_unlock(&peerl.lock);
2136                                         }
2137                                 }  else if (!strcasecmp(utype, "h323") || !strcasecmp(utype, "alias")) {
2138                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
2139                                         if (alias) {
2140                                                 ast_mutex_lock(&aliasl.lock);
2141                                                 alias->next = aliasl.aliases;
2142                                                 aliasl.aliases = alias;
2143                                                 ast_mutex_unlock(&aliasl.lock);
2144                                         }
2145                                 } else {
2146                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
2147                                 }
2148                         } else {
2149                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
2150                         }
2151                 }
2152                 cat = ast_category_browse(cfg, cat);
2153         }
2154         ast_config_destroy(cfg);
2155
2156         /* Register our H.323 aliases if any*/
2157         while (alias) {         
2158                 if (h323_set_alias(alias)) {
2159                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
2160                         return -1;
2161                 }       
2162                 alias = alias->next;
2163         }
2164
2165         /* Add our capabilities */
2166         ast_mutex_lock(&caplock);
2167         if (h323_set_capability(capability, dtmfmode)) {
2168                 ast_log(LOG_ERROR, "Capabilities failure, this is bad.\n");
2169                 ast_mutex_unlock(&caplock);
2170                 return -1;
2171         }
2172         ast_mutex_unlock(&caplock);
2173         return 0;
2174 }
2175
2176 void delete_users(void)
2177 {
2178         struct oh323_user *user, *userlast;
2179         struct oh323_peer *peer;
2180         
2181         /* Delete all users */
2182         ast_mutex_lock(&userl.lock);
2183         for (user=userl.users;user;) {
2184                 userlast = user;
2185                 user=user->next;
2186                 free(userlast);
2187         }
2188         userl.users=NULL;
2189         ast_mutex_unlock(&userl.lock);
2190         ast_mutex_lock(&peerl.lock);
2191         for (peer=peerl.peers;peer;) {
2192                 /* Assume all will be deleted, and we'll find out for sure later */
2193                 peer->delme = 1;
2194                 peer = peer->next;
2195         }
2196         ast_mutex_unlock(&peerl.lock);
2197 }
2198
2199 void delete_aliases(void)
2200 {
2201         struct oh323_alias *alias, *aliaslast;
2202                 
2203         /* Delete all users */
2204         ast_mutex_lock(&aliasl.lock);
2205         for (alias=aliasl.aliases;alias;) {
2206                 aliaslast = alias;
2207                 alias=alias->next;
2208                 free(aliaslast);
2209         }
2210         aliasl.aliases=NULL;
2211         ast_mutex_unlock(&aliasl.lock);
2212 }
2213
2214 void prune_peers(void)
2215 {
2216         /* Prune peers who still are supposed to be deleted */
2217         struct oh323_peer *peer, *peerlast, *peernext;
2218         ast_mutex_lock(&peerl.lock);
2219         peerlast = NULL;
2220         for (peer=peerl.peers;peer;) {
2221                 peernext = peer->next;
2222                 if (peer->delme) {
2223                         free(peer);
2224                         if (peerlast) {
2225                                 peerlast->next = peernext;
2226                         } else {
2227                                 peerl.peers = peernext;
2228                         }
2229                 } else {
2230                         peerlast = peer;
2231                 }
2232                 peer = peernext;
2233         }
2234         ast_mutex_unlock(&peerl.lock);
2235 }
2236
2237 static int h323_reload(int fd, int argc, char *argv[])
2238 {
2239         ast_mutex_lock(&h323_reload_lock);
2240         if (h323_reloading) {
2241                 ast_verbose("Previous H.323 reload not yet done\n");
2242         } else {
2243                 h323_reloading = 1;
2244         }
2245         ast_mutex_unlock(&h323_reload_lock);
2246         restart_monitor();
2247         return 0;
2248 }
2249
2250 static int h323_do_reload(void)
2251 {
2252         delete_users();
2253         delete_aliases();
2254         prune_peers();
2255         reload_config();
2256         restart_monitor();
2257         return 0;
2258 }
2259
2260 int reload(void)
2261 {
2262         return h323_reload(0, 0, NULL);
2263 }
2264
2265 static struct ast_cli_entry  cli_h323_reload =
2266         { { "h.323", "reload", NULL }, h323_reload, "Reload H.323 configuration", h323_reload_usage };
2267
2268 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
2269 {
2270         struct oh323_pvt *pvt;
2271         pvt = (struct oh323_pvt *) chan->tech_pvt;
2272         if (pvt && pvt->rtp && pvt->bridge) {
2273                 return pvt->rtp;
2274         }
2275         return NULL;
2276 }
2277
2278 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
2279 {
2280         return NULL;
2281 }
2282
2283 static char *convertcap(int cap)
2284 {
2285         switch (cap) {
2286         case AST_FORMAT_G723_1:
2287                 return "G.723";
2288         case AST_FORMAT_GSM:
2289                 return "GSM";
2290         case AST_FORMAT_ULAW:
2291                 return "ULAW";
2292         case AST_FORMAT_ALAW:
2293                 return "ALAW";
2294         case AST_FORMAT_ADPCM:
2295                 return "G.728";
2296         case AST_FORMAT_G729A:
2297                 return "G.729";
2298         case AST_FORMAT_SPEEX:
2299                 return "SPEEX";
2300         case AST_FORMAT_ILBC:
2301                 return "ILBC";
2302         default:
2303                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
2304                 return NULL;
2305         }
2306 }
2307
2308 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs)
2309 {
2310         /* XXX Deal with Video */
2311         struct oh323_pvt *pvt;
2312         struct sockaddr_in them;
2313         struct sockaddr_in us;
2314         char *mode;
2315         char iabuf[INET_ADDRSTRLEN];
2316
2317         if (!rtp) {
2318                 return 0;
2319         }
2320
2321         mode = convertcap(chan->writeformat); 
2322         pvt = (struct oh323_pvt *) chan->tech_pvt;
2323         if (!pvt) {
2324                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
2325                 return -1;
2326         }
2327         ast_rtp_get_peer(rtp, &them);   
2328         ast_rtp_get_us(rtp, &us);
2329         h323_native_bridge(pvt->cd.call_token, ast_inet_ntoa(iabuf, sizeof(iabuf), them.sin_addr), mode);
2330         return 0;
2331 }
2332
2333 static struct ast_rtp_protocol oh323_rtp = {
2334         .type = type,
2335         .get_rtp_info = oh323_get_rtp_peer,
2336         .get_vrtp_info = oh323_get_vrtp_peer,
2337         .set_rtp_peer=  oh323_set_rtp_peer,
2338 };
2339
2340 int load_module()
2341 {
2342         int res;
2343         ast_mutex_init(&userl.lock);
2344         ast_mutex_init(&peerl.lock);
2345         ast_mutex_init(&aliasl.lock);
2346         sched = sched_context_create();
2347         if (!sched) {
2348                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2349         }
2350         io = io_context_create();
2351         if (!io) {
2352                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2353         }
2354         res = reload_config();
2355         if (res) {
2356                 return 0;
2357         } else {
2358                 /* Make sure we can register our channel type */
2359                 if (ast_channel_register(&oh323_tech)) {
2360                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
2361                         h323_end_process();
2362                         return -1;
2363                 }
2364                 ast_cli_register(&cli_debug);
2365                 ast_cli_register(&cli_no_debug);
2366                 ast_cli_register(&cli_trace);
2367                 ast_cli_register(&cli_no_trace);
2368                 ast_cli_register(&cli_show_codecs);
2369                 ast_cli_register(&cli_gk_cycle);
2370                 ast_cli_register(&cli_hangup_call);
2371                 ast_cli_register(&cli_show_tokens);
2372                 ast_cli_register(&cli_h323_reload);
2373
2374                 ast_rtp_proto_register(&oh323_rtp);
2375
2376                 /* Register our callback functions */
2377                 h323_callback_register(setup_incoming_call, 
2378                                                 setup_outgoing_call,                                                     
2379                                                 external_rtp_create, 
2380                                                 setup_rtp_connection, 
2381                                                 cleanup_connection, 
2382                                                 chan_ringing,
2383                                                 connection_made, 
2384                                                 send_digit,
2385                                                 answer_call,
2386                                                 progress,
2387                                                 set_dtmf_payload,
2388                                                 hangup_connection);
2389                 /* start the h.323 listener */
2390                 if (h323_start_listener(h323_signalling_port, bindaddr)) {
2391                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
2392                         return -1;
2393                 }
2394                 /* Possibly register with a GK */
2395                 if (!gatekeeper_disable) {
2396                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
2397                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
2398                                 return 0;
2399                         }
2400                 }
2401                 /* And start the monitor for the first time */
2402                 restart_monitor();
2403         }
2404         return res;
2405 }
2406
2407 int unload_module() 
2408 {
2409         struct oh323_pvt *p, *pl;
2410
2411         /* unregister commands */
2412         ast_cli_unregister(&cli_debug);
2413         ast_cli_unregister(&cli_no_debug);
2414         ast_cli_unregister(&cli_trace);
2415         ast_cli_unregister(&cli_no_trace);   
2416         ast_cli_unregister(&cli_show_codecs);
2417         ast_cli_unregister(&cli_gk_cycle);
2418         ast_cli_unregister(&cli_hangup_call);
2419         ast_cli_unregister(&cli_show_tokens);
2420         ast_cli_unregister(&cli_h323_reload);
2421         ast_rtp_proto_unregister(&oh323_rtp);
2422         ast_channel_unregister(&oh323_tech);
2423                 
2424         if (!ast_mutex_lock(&iflock)) {
2425                 /* hangup all interfaces if they have an owner */
2426                 p = iflist;
2427                 while(p) {
2428                         if (p->owner) {
2429                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
2430                         }
2431                         p = p->next;
2432                 }
2433                 iflist = NULL;
2434                 ast_mutex_unlock(&iflock);
2435         } else {
2436                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
2437                 return -1;
2438         }
2439         if (!ast_mutex_lock(&monlock)) {
2440                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
2441                         /* this causes a seg, anyone know why? */
2442                         pthread_cancel(monitor_thread);
2443                         pthread_kill(monitor_thread, SIGURG);
2444                         pthread_join(monitor_thread, NULL);
2445                 }
2446                 monitor_thread = AST_PTHREADT_STOP;
2447                 ast_mutex_unlock(&monlock);
2448         } else {
2449                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2450                 return -1;
2451         }
2452         if (!ast_mutex_lock(&iflock)) {
2453                 /* destroy all the interfaces and free their memory */
2454                 p = iflist;
2455                 while(p) {
2456                         pl = p;
2457                         p = p->next;
2458                         /* free associated memory */
2459                         ast_mutex_destroy(&pl->lock);
2460                         free(pl);
2461                 }
2462                 iflist = NULL;
2463                 ast_mutex_unlock(&iflock);
2464         } else {
2465                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
2466                 return -1;
2467         }
2468         h323_gk_urq();
2469         h323_end_process();
2470         io_context_destroy(io);
2471         sched_context_destroy(sched);
2472         delete_users();
2473         delete_aliases();
2474         prune_peers();
2475         ast_mutex_destroy(&aliasl.lock);
2476         ast_mutex_destroy(&userl.lock);
2477         ast_mutex_destroy(&peerl.lock);
2478         return 0; 
2479
2480
2481 int usecount()
2482 {
2483         int res;
2484         ast_mutex_lock(&usecnt_lock);
2485         res = usecnt;
2486         ast_mutex_unlock(&usecnt_lock);
2487         return res;
2488 }
2489
2490 char *description()
2491 {
2492         return (char *) desc;
2493 }
2494
2495 char *key()
2496 {
2497         return ASTERISK_GPL_KEY;
2498 }