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