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