Fix H.323 locking (bug #3540)
[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[1024];
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                 snprintf(called_addr, sizeof(called_addr), "%s@%s:%d", pvt->exten, addr, pvt->options.port);
515         } else {
516                 snprintf(called_addr, sizeof(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 (pvt->cd.call_source_e164 && !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 (pvt->cd.call_source_e164 && !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         return ch;
836 }
837
838 static struct oh323_pvt *oh323_alloc(int callid)
839 {
840         struct oh323_pvt *pvt;
841
842         pvt = (struct oh323_pvt *) malloc(sizeof(struct oh323_pvt));
843         if (!pvt) {
844                 ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
845                 return NULL;
846         }
847         memset(pvt, 0, sizeof(struct oh323_pvt));
848         pvt->rtp = ast_rtp_new(sched, io, 1, 0);
849         if (!pvt->rtp) {
850                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
851                 free(pvt);
852                 return NULL;
853         }
854         ast_rtp_settos(pvt->rtp, tos);
855         ast_mutex_init(&pvt->lock);
856         /* Ensure the call token is allocated */
857         if ((pvt->cd).call_token == NULL) {
858                 (pvt->cd).call_token = (char *)malloc(128);
859         }
860         memset((char *)(pvt->cd).call_token, 0, 128);
861         if (!pvt->cd.call_token) {
862                 ast_log(LOG_ERROR, "Not enough memory to alocate call token\n");
863                 return NULL;
864         }
865         pvt->cd.call_reference = callid;
866         pvt->bridge = bridging; 
867         pvt->dtmfmode = dtmfmode;
868         if (pvt->dtmfmode & H323_DTMF_RFC2833) {
869                 pvt->nonCodecCapability |= AST_RTP_DTMF;
870         }
871         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
872         /* Add to interface list */
873         ast_mutex_lock(&iflock);
874         pvt->next = iflist;
875         iflist = pvt;
876         ast_mutex_unlock(&iflock);
877         return pvt;
878 }
879
880 static struct oh323_pvt *find_call(int call_reference, const char *token)
881 {  
882         struct oh323_pvt *pvt;
883
884         ast_mutex_lock(&iflock);
885         pvt = iflist; 
886         while(pvt) {
887                 if ((signed int)pvt->cd.call_reference == call_reference) {
888                         /* Found the call */             
889                         if ((token != NULL) && (!strcmp(pvt->cd.call_token, token))) {
890                                 ast_mutex_unlock(&iflock);
891                                 return pvt;
892                         } else if (token == NULL) {
893                                 ast_log(LOG_DEBUG, "Call Token is NULL\n");
894                                 ast_mutex_unlock(&iflock);
895                                 return pvt;
896                         }
897                 }
898                 pvt = pvt->next; 
899         }
900         ast_mutex_unlock(&iflock);
901         return NULL;
902 }
903
904 struct oh323_user *find_user(const call_details_t cd)
905 {
906         struct oh323_user *u;
907         char iabuf[INET_ADDRSTRLEN];
908         u = userl.users;
909         if (userbyalias) {
910                 while(u) {
911                         if (!strcasecmp(u->name, cd.call_source_aliases)) {
912                                 break;
913                         }
914                         u = u->next;
915                 }
916         } else {
917                 while(u) {
918                         if (!strcasecmp(cd.sourceIp, ast_inet_ntoa(iabuf, sizeof(iabuf), u->addr.sin_addr))) {
919                                 break;
920                         }
921                         u = u->next;
922                 }
923         }
924         return u;
925 }
926
927 struct oh323_peer *find_peer(const char *peer, struct sockaddr_in *sin)
928 {
929         struct oh323_peer *p = NULL;
930         static char iabuf[INET_ADDRSTRLEN];
931
932         p = peerl.peers;
933         if (peer) {
934                 while(p) {
935                         if (!strcasecmp(p->name, peer)) {
936                                 ast_log(LOG_DEBUG, "Found peer %s by name\n", peer);
937                                 break;
938                         }
939                         p = p->next;
940                 }
941         } else {
942                 /* find by sin */
943                 if (sin) {
944                         while (p) {
945                                 if ((!inaddrcmp(&p->addr, sin)) || 
946                                         (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
947                                         ast_log(LOG_DEBUG, "Found peer %s/%s by addr\n", peer, ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr));
948                                         break;
949                                 }
950                                 p = p->next;
951                         }
952                 }       
953         }
954         if (!p) {
955                 ast_log(LOG_DEBUG, "Could not find peer %s by name or address\n", peer);
956         }
957         return p;
958 }
959
960 static int create_addr(struct oh323_pvt *pvt, char *opeer)
961 {
962         struct hostent *hp;
963         struct ast_hostent ahp;
964         struct oh323_peer *p;
965         int portno;
966         int found = 0;
967         char *port;
968         char *hostn;
969         char peer[256] = "";
970
971         strncpy(peer, opeer, sizeof(peer) - 1);
972         port = strchr(peer, ':');
973         if (port) {
974                 *port = '\0';
975                 port++;
976         }
977         pvt->sa.sin_family = AF_INET;
978         ast_mutex_lock(&peerl.lock);
979         p = find_peer(peer, NULL);
980         if (p) {
981                 found++;
982                 pvt->capability = p->capability;
983                 pvt->nat = p->nat;
984                 if (pvt->rtp) {
985                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", pvt->nat);
986                         ast_rtp_setnat(pvt->rtp, pvt->nat);
987                 }
988                 memcpy(&pvt->options, &p->options, sizeof(pvt->options));
989                 if (p->dtmfmode) {
990                         pvt->dtmfmode = p->dtmfmode;
991                         if (pvt->dtmfmode & H323_DTMF_RFC2833) {
992                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
993                         } else {
994                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
995                         }
996                 }
997                 if (p->addr.sin_addr.s_addr) {
998                         pvt->sa.sin_addr = p->addr.sin_addr;    
999                         pvt->sa.sin_port = p->addr.sin_port;    
1000                 } 
1001         }
1002         ast_mutex_unlock(&peerl.lock);
1003         if (!p && !found) {
1004                 hostn = peer;
1005                 if (port) {
1006                         portno = atoi(port);
1007                 } else {
1008                         portno = h323_signalling_port;
1009                 }               
1010                 hp = ast_gethostbyname(hostn, &ahp);
1011                 if (hp) {
1012                         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1013                         memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
1014                         pvt->sa.sin_port = htons(portno);
1015                         return 0;       
1016                 } else {
1017                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1018                         return -1;
1019                 }
1020         } else if (!p) {
1021                 return -1;
1022         } else {        
1023                 return 0;
1024         }
1025 }
1026 static struct ast_channel *oh323_request(const char *type, int format, void *data, int *cause)
1027 {
1028         int oldformat;
1029         struct oh323_pvt *pvt;
1030         struct ast_channel *tmpc = NULL;
1031         char *dest = (char *)data;
1032         char *ext, *host;
1033         char *h323id = NULL;
1034         char tmp[256];
1035         
1036         ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
1037         pvt = oh323_alloc(0);
1038         if (!pvt) {
1039                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
1040                 return NULL;
1041         }       
1042         oldformat = format;
1043         format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
1044         if (!format) {
1045                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
1046                 return NULL;
1047         }
1048         /* Assign default capabilities */
1049         pvt->capability = capability;
1050         pvt->dtmfmode = H323_DTMF_RFC2833;
1051
1052         strncpy(tmp, dest, sizeof(tmp) - 1);    
1053         host = strchr(tmp, '@');
1054         if (host) {
1055                 *host = '\0';
1056                 host++;
1057                 ext = tmp;
1058         } else {
1059                 host = tmp;
1060                 ext = NULL;
1061         }
1062         strtok_r(host, "/", &(h323id));         
1063         if (h323id && !ast_strlen_zero(h323id)) {
1064                 h323_set_id(h323id);
1065         }
1066         if (ext) {
1067                 strncpy(pvt->exten, ext, sizeof(pvt->exten) - 1);
1068         }
1069         ast_log(LOG_DEBUG, "Extension: %s Host: %s\n",  pvt->exten, host);
1070         if (!usingGk) {
1071                 if (create_addr(pvt, host)) {
1072                         oh323_destroy(pvt);
1073                         return NULL;
1074                 }
1075         }
1076
1077         /* pass on our capabilites to the H.323 stack */
1078         ast_mutex_lock(&caplock);
1079         h323_set_capability(pvt->capability, pvt->dtmfmode);
1080         ast_mutex_unlock(&caplock);
1081         
1082         ast_mutex_lock(&pvt->lock);
1083         tmpc = oh323_new(pvt, AST_STATE_DOWN, host);
1084         ast_mutex_unlock(&pvt->lock);
1085         if (!tmpc) {
1086                 oh323_destroy(pvt);
1087         }
1088         ast_update_use_count();
1089         restart_monitor();
1090         return tmpc;
1091 }
1092
1093 /** Find a call by alias */
1094 struct oh323_alias *find_alias(const char *source_aliases)
1095 {
1096         struct oh323_alias *a;
1097
1098         a = aliasl.aliases;
1099         while(a) {
1100                 if (!strcasecmp(a->name, source_aliases)) {
1101                         break;
1102                 }
1103                 a = a->next;
1104         }
1105         return a;
1106 }
1107
1108 /**
1109   * Callback for sending digits from H.323 up to asterisk
1110   *
1111   */
1112 int send_digit(unsigned call_reference, char digit, const char *token)
1113 {
1114         struct oh323_pvt *pvt;
1115         struct ast_frame f;
1116
1117         ast_log(LOG_DEBUG, "Recieved Digit: %c\n", digit);
1118         pvt = find_call(call_reference, token); 
1119         if (!pvt) {
1120                 ast_log(LOG_ERROR, "Private structure not found in send_digit.\n");
1121                 return -1;
1122         }
1123         memset(&f, 0, sizeof(f));
1124         f.frametype = AST_FRAME_DTMF;
1125         f.subclass = digit;
1126         f.datalen = 0;
1127         f.samples = 800;
1128         f.offset = 0;
1129         f.data = NULL;
1130         f.mallocd = 0;
1131         f.src = "SEND_DIGIT";   
1132         return ast_queue_frame(pvt->owner, &f); 
1133 }
1134
1135 /**
1136   * Callback function used to inform the H.323 stack of the local rtp ip/port details
1137   *
1138   * Returns the local RTP information
1139   */
1140 struct rtp_info *external_rtp_create(unsigned call_reference, const char * token)
1141 {       
1142         struct oh323_pvt *pvt;
1143         struct sockaddr_in us;
1144         struct rtp_info *info;
1145         static char iabuf[INET_ADDRSTRLEN];
1146
1147         info = (struct rtp_info *)malloc(sizeof(struct rtp_info));
1148         if (!info) {
1149                 ast_log(LOG_ERROR, "Unable to allocated info structure, this is very bad\n");
1150                 return NULL;
1151         }
1152         pvt = find_call(call_reference, token); 
1153         if (!pvt) {
1154                 ast_log(LOG_ERROR, "Unable to find call %s(%d)\n", token, call_reference);
1155                 return NULL;
1156         }
1157         /* figure out our local RTP port and tell the H.323 stack about it */
1158         ast_rtp_get_us(pvt->rtp, &us);
1159         /* evil hack, until I (or someone?) figures out a better way */
1160         info->addr = ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr);
1161         info->port = ntohs(us.sin_port);
1162         ast_log(LOG_DEBUG, "Sending RTP 'US' %s:%d\n", info->addr, info->port);
1163         return info;
1164 }
1165
1166 int progress(unsigned call_reference, const char *token, int inband);
1167
1168 /**
1169  * Definition taken from rtp.c for rtpPayloadType because we need it here.
1170  */
1171 struct rtpPayloadType {
1172         int isAstFormat;        /* whether the following code is an AST_FORMAT */
1173         int code;
1174 };
1175
1176 /**
1177   * Call-back function passing remote ip/port information from H.323 to asterisk 
1178   *
1179   * Returns nothing 
1180   */
1181 void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort, const char *token, int pt)
1182 {
1183         struct oh323_pvt *pvt = NULL;
1184         struct sockaddr_in them;
1185         struct rtpPayloadType rtptype;
1186         int fmt;
1187
1188         /* Find the call or allocate a private structure if call not found */
1189         pvt = find_call(call_reference, token); 
1190         if (!pvt) {
1191                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1192                 return;
1193         }
1194
1195         rtptype = ast_rtp_lookup_pt(pvt->rtp, pt);
1196
1197         fmt = ast_best_codec(pvt->owner->nativeformats);
1198
1199         ast_mutex_lock(&pvt->lock);
1200         pvt->owner->nativeformats = rtptype.code;
1201         pvt->owner->readformat = fmt;
1202         pvt->owner->writeformat = fmt;
1203         ast_set_read_format(pvt->owner, pvt->owner->readformat);
1204         ast_set_write_format(pvt->owner, pvt->owner->writeformat);
1205         ast_mutex_unlock(&pvt->lock);
1206
1207         them.sin_family = AF_INET;
1208         /* only works for IPv4 */
1209         them.sin_addr.s_addr = inet_addr(remoteIp); 
1210         them.sin_port = htons(remotePort);
1211         ast_rtp_set_peer(pvt->rtp, &them);
1212
1213         if (pvt->options.progress_audio) {
1214                 progress(call_reference, token, 1);
1215         }
1216
1217         return;
1218 }
1219
1220 /**  
1221   *     Call-back function to signal asterisk that the channel has been answered 
1222   * Returns nothing
1223   */
1224 void connection_made(unsigned call_reference, const char *token)
1225 {
1226         struct ast_channel *c = NULL;
1227         struct oh323_pvt *pvt = NULL;
1228         
1229         pvt = find_call(call_reference, token); 
1230         
1231         if (!pvt) {
1232                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1233                 return;
1234         }
1235
1236         if (!pvt->owner) {
1237                 ast_log(LOG_ERROR, "Channel has no owner\n");
1238                 return;
1239         }
1240         c = pvt->owner; 
1241         ast_setstate(c, AST_STATE_UP);
1242         ast_queue_control(c, AST_CONTROL_ANSWER);
1243         return;
1244 }
1245
1246 int progress(unsigned call_reference, const char *token, int inband)
1247 {
1248         struct oh323_pvt *p;
1249
1250         ast_log(LOG_DEBUG, "Received ALERT/PROGRESS message for %s tones\n", (inband ? "inband" : "self-generated"));
1251         p = find_call(call_reference, token);
1252
1253         if (!p) {
1254                 ast_log(LOG_ERROR, "Private structure not found in progress.\n");
1255                 return -1;
1256         }
1257         if (!p->owner) {
1258                 ast_log(LOG_ERROR, "No Asterisk channel associated with private structure.\n");
1259                 return -1;
1260         }
1261
1262         ast_queue_control(p->owner, (inband ? AST_CONTROL_PROGRESS : AST_CONTROL_RINGING));
1263
1264         return 0;
1265 }
1266
1267 /**
1268  *  Call-back function for incoming calls
1269  *
1270  *  Returns 1 on success
1271  */
1272 call_options_t *setup_incoming_call(call_details_t cd)
1273 {
1274         struct oh323_pvt *pvt = NULL;
1275         struct oh323_user *user = NULL;
1276         struct oh323_alias *alias = NULL;
1277         call_options_t *call_options = NULL;
1278         char iabuf[INET_ADDRSTRLEN];
1279
1280         /* allocate the call*/
1281         pvt = oh323_alloc(cd.call_reference);
1282
1283         if (!pvt) {
1284                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
1285                 return NULL;
1286         }
1287
1288         /* Populate the call details in the private structure */
1289         pvt->cd.call_token = strdup(cd.call_token);
1290         pvt->cd.call_source_aliases = strdup(cd.call_source_aliases);
1291         pvt->cd.call_dest_alias = strdup(cd.call_dest_alias);
1292         pvt->cd.call_source_name = strdup(cd.call_source_name);
1293         pvt->cd.call_source_e164 = strdup(cd.call_source_e164);
1294         pvt->cd.call_dest_e164 = strdup(cd.call_dest_e164);
1295
1296         if (h323debug) {
1297                 ast_verbose(VERBOSE_PREFIX_3 "Setting up Call\n");
1298                 ast_verbose(VERBOSE_PREFIX_3 "\tCall token:  [%s]\n", pvt->cd.call_token);
1299                 ast_verbose(VERBOSE_PREFIX_3 "\tCalling party name:  [%s]\n", pvt->cd.call_source_name);
1300                 ast_verbose(VERBOSE_PREFIX_3 "\tCalling party number:  [%s]\n", pvt->cd.call_source_e164);
1301                 ast_verbose(VERBOSE_PREFIX_3 "\tCalled party name:  [%s]\n", pvt->cd.call_dest_alias);
1302                 ast_verbose(VERBOSE_PREFIX_3 "\tCalled party number:  [%s]\n", pvt->cd.call_dest_e164);
1303         }
1304
1305         /* Decide if we are allowing Gatekeeper routed calls*/
1306         if ((!strcasecmp(cd.sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk)) {           
1307                 if (!ast_strlen_zero(cd.call_dest_e164)) {
1308                         strncpy(pvt->exten, cd.call_dest_e164, sizeof(pvt->exten) - 1);
1309                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1); 
1310                 } else {
1311                         alias = find_alias(cd.call_dest_alias);
1312                         if (!alias) {
1313                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd.call_dest_alias);
1314                                 return NULL;
1315                         }
1316                         strncpy(pvt->exten, alias->name, sizeof(pvt->exten) - 1);
1317                         strncpy(pvt->context, alias->context, sizeof(pvt->context) - 1);
1318                 }
1319         } else { 
1320                 /* Either this call is not from the Gatekeeper 
1321                    or we are not allowing gk routed calls */
1322                 user  = find_user(cd);
1323                 if (!user) {
1324                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
1325                                 strncpy(pvt->exten, cd.call_dest_e164, sizeof(pvt->exten) - 1);
1326                         } else {
1327                                 strncpy(pvt->exten, cd.call_dest_alias, sizeof(pvt->exten) - 1);
1328                         }
1329                         if (ast_strlen_zero(default_context)) {
1330                                 ast_log(LOG_ERROR, "Call from '%s' rejected due to no default context\n", pvt->cd.call_source_aliases);
1331                                 return NULL;
1332                         }
1333                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
1334                         ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd.call_source_aliases, pvt->context);
1335                         memset(&pvt->options, 0, sizeof(pvt->options));
1336                 } else {                                        
1337                         if (user->host) {
1338                                 if (strcasecmp(cd.sourceIp, ast_inet_ntoa(iabuf, sizeof(iabuf), user->addr.sin_addr))){                                 
1339                                         if (ast_strlen_zero(user->context)) {
1340                                                 if (ast_strlen_zero(default_context)) {                                 
1341                                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s) and no default context\n", user->name, cd.sourceIp);
1342                                                         return NULL;
1343                                                 }
1344                                                 strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
1345                                         } else {
1346                                                 strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
1347                                         }
1348                                         pvt->exten[0] = 'i';
1349                                         pvt->exten[1] = '\0';
1350                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s)s\n", user->name, cd.sourceIp);
1351                                         goto exit;                                      
1352                                 }
1353                         }
1354                         strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
1355                         pvt->bridge = user->bridge;
1356                         pvt->nat = user->nat;
1357                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
1358                                 strncpy(pvt->exten, cd.call_dest_e164, sizeof(pvt->exten) - 1);
1359                         } else {
1360                                 strncpy(pvt->exten, cd.call_dest_alias, sizeof(pvt->exten) - 1);
1361                         }
1362                         if (!ast_strlen_zero(user->accountcode)) {
1363                                 strncpy(pvt->accountcode, user->accountcode, sizeof(pvt->accountcode) - 1);
1364                         } 
1365                         if (user->amaflags) {
1366                                 pvt->amaflags = user->amaflags;
1367                         } 
1368                         call_options = &user->options;
1369                 } 
1370         }
1371 exit:
1372         return call_options;
1373 }
1374
1375 /**
1376  * Call-back function to start PBX when OpenH323 ready to serve incoming call
1377  *
1378  * Returns 1 on success
1379  */
1380 static int answer_call(unsigned call_reference, const char *token)
1381 {
1382         struct oh323_pvt *pvt = NULL;
1383         struct ast_channel *c = NULL;
1384
1385         /* Find the call or allocate a private structure if call not found */
1386         pvt = find_call(call_reference, token); 
1387         if (!pvt) {
1388                 ast_log(LOG_ERROR, "Something is wrong: answer_call\n");
1389                 return 0;
1390         }
1391         /* Briefly lock call for oh323_new() */
1392         ast_mutex_lock(&pvt->lock);
1393
1394         /* allocate a channel and tell asterisk about it */
1395         c = oh323_new(pvt, AST_STATE_RINGING, pvt->cd.call_token);
1396
1397         /* And release when done */
1398         ast_mutex_unlock(&pvt->lock);
1399         if (!c) {
1400                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1401                 return 0;
1402         }
1403         return 1;
1404 }
1405
1406 /**
1407  * Call-back function to establish an outgoing H.323 call
1408  * 
1409  * Returns 1 on success 
1410  */
1411 int setup_outgoing_call(call_details_t cd)
1412 {       
1413         return 1;
1414 }
1415
1416 /**
1417   *  Call-back function to signal asterisk that the channel is ringing
1418   *  Returns nothing
1419   */
1420 void chan_ringing(unsigned call_reference, const char *token)
1421 {
1422         struct ast_channel *c = NULL;
1423         struct oh323_pvt *pvt = NULL;
1424
1425         pvt = find_call(call_reference, token); 
1426         if (!pvt) {
1427                 ast_log(LOG_ERROR, "Something is wrong: ringing\n");
1428         }
1429         if (!pvt->owner) {
1430                 ast_log(LOG_ERROR, "Channel has no owner\n");
1431                 return;
1432         }
1433         c = pvt->owner;
1434         ast_setstate(c, AST_STATE_RINGING);
1435         ast_queue_control(c, AST_CONTROL_RINGING);
1436         return;
1437 }
1438
1439 void cleanup_call_details(call_details_t cd) 
1440 {
1441         if (cd.call_token) {
1442                 free(cd.call_token);
1443         }
1444         if (cd.call_source_aliases) {
1445                 free(cd.call_source_aliases);
1446         }
1447         if (cd.call_dest_alias) {
1448                 free(cd.call_dest_alias);
1449         }
1450         if (cd.call_source_name) { 
1451                 free(cd.call_source_name);
1452         }
1453         if (cd.call_source_e164) {
1454                 free(cd.call_source_e164);
1455         }
1456         if (cd.call_dest_e164) {
1457                 free(cd.call_dest_e164);
1458         }
1459         if (cd.sourceIp) {
1460                 free(cd.sourceIp);
1461         }
1462 }
1463
1464 /**
1465   * Call-back function to cleanup communication
1466   * Returns nothing,
1467   */
1468 void cleanup_connection(call_details_t cd)
1469 {       
1470         struct oh323_pvt *pvt = NULL;
1471         struct ast_rtp *rtp = NULL;
1472         
1473         pvt = find_call(cd.call_reference, cd.call_token); 
1474         if (!pvt) {
1475                 return;
1476         }
1477         ast_mutex_lock(&pvt->lock);
1478         if (pvt->rtp) {
1479                 rtp = pvt->rtp;
1480                 pvt->rtp = NULL;
1481                 /* Immediately stop RTP */
1482                 ast_rtp_destroy(rtp);
1483         }
1484         cleanup_call_details(pvt->cd);
1485         pvt->alreadygone = 1;
1486         /* Send hangup */       
1487         if (pvt->owner) {
1488                 ast_queue_hangup(pvt->owner);
1489         } 
1490         ast_mutex_unlock(&pvt->lock);
1491         return; 
1492 }
1493
1494 void set_dtmf_payload(unsigned call_reference, const char *token, int payload)
1495 {
1496         struct oh323_pvt *pvt = NULL;
1497
1498         pvt = find_call(call_reference, token);
1499         if (!pvt) {
1500                 return;
1501         }
1502         ast_mutex_lock(&pvt->lock);
1503         if (pvt->rtp) {
1504                 ast_rtp_set_rtpmap_type(pvt->rtp, payload, "audio", "telephone-event");
1505         }
1506         ast_mutex_unlock(&pvt->lock);
1507 }
1508
1509 static void *do_monitor(void *data)
1510 {
1511         int res;
1512         int reloading;
1513         struct oh323_pvt *oh323 = NULL;
1514         
1515         for(;;) {
1516                  /* Check for a reload request */
1517                 ast_mutex_lock(&h323_reload_lock);
1518                 reloading = h323_reloading;
1519                 h323_reloading = 0;
1520                 ast_mutex_unlock(&h323_reload_lock);
1521                 if (reloading) {
1522                         if (option_verbose > 0) {
1523                                 ast_verbose(VERBOSE_PREFIX_1 "Reloading H.323\n");
1524                         }
1525                         h323_do_reload();
1526                 }
1527                 /* Check for interfaces needing to be killed */
1528                 ast_mutex_lock(&iflock);
1529 restartsearch:          
1530                 oh323 = iflist;
1531                 while(oh323) {
1532                         if (oh323->needdestroy) {
1533                                 __oh323_destroy(oh323);
1534                                 goto restartsearch;
1535                         }
1536                         oh323 = oh323->next;
1537                 }
1538                 ast_mutex_unlock(&iflock);
1539                 pthread_testcancel();
1540                 /* Wait for sched or io */
1541                 res = ast_sched_wait(sched);
1542                 if ((res < 0) || (res > 1000)) {
1543                         res = 1000;
1544                 }
1545                 res = ast_io_wait(io, res);
1546                 ast_mutex_lock(&monlock);
1547                 if (res >= 0) {
1548                         ast_sched_runq(sched);
1549                 }
1550                 ast_mutex_unlock(&monlock);
1551         }
1552         /* Never reached */
1553         return NULL;
1554 }
1555
1556 static int restart_monitor(void)
1557 {
1558         pthread_attr_t attr;
1559         /* If we're supposed to be stopped -- stay stopped */
1560         if (monitor_thread == AST_PTHREADT_STOP) {
1561                 return 0;
1562         }
1563         if (ast_mutex_lock(&monlock)) {
1564                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1565                 return -1;
1566         }
1567         if (monitor_thread == pthread_self()) {
1568                 ast_mutex_unlock(&monlock);
1569                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1570                 return -1;
1571         }
1572         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
1573                 /* Wake up the thread */
1574                 pthread_kill(monitor_thread, SIGURG);
1575         } else {        
1576                 pthread_attr_init(&attr);
1577                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1578                 /* Start a new monitor */
1579                 if (ast_pthread_create(&monitor_thread, &attr, do_monitor, NULL) < 0) {
1580                         ast_mutex_unlock(&monlock);
1581                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1582                         return -1;
1583                 }
1584
1585         }
1586         ast_mutex_unlock(&monlock);
1587         return 0;
1588 }
1589
1590 static int h323_do_trace(int fd, int argc, char *argv[])
1591 {
1592         if (argc != 3) {
1593                 return RESULT_SHOWUSAGE;
1594         }
1595         h323_debug(1, atoi(argv[2]));
1596         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1597         return RESULT_SUCCESS;
1598 }
1599
1600 static int h323_no_trace(int fd, int argc, char *argv[])
1601 {
1602         if (argc != 3) {
1603                 return RESULT_SHOWUSAGE;
1604         }
1605         h323_debug(0,0);
1606         ast_cli(fd, "H.323 trace disabled\n");
1607         return RESULT_SUCCESS;
1608 }
1609
1610 static int h323_do_debug(int fd, int argc, char *argv[])
1611 {
1612         if (argc != 2) {
1613                 return RESULT_SHOWUSAGE;
1614         }
1615         h323debug = 1;
1616         ast_cli(fd, "H323 debug enabled\n");
1617         return RESULT_SUCCESS;
1618 }
1619
1620 static int h323_no_debug(int fd, int argc, char *argv[])
1621 {
1622         if (argc != 3) {
1623                 return RESULT_SHOWUSAGE;
1624         }
1625         h323debug = 0;
1626         ast_cli(fd, "H323 Debug disabled\n");
1627         return RESULT_SUCCESS;
1628 }
1629
1630 static int h323_gk_cycle(int fd, int argc, char *argv[])
1631 {
1632         return RESULT_SUCCESS;
1633 #if 0
1634         if (argc != 3) {
1635                 return RESULT_SHOWUSAGE;
1636         }       
1637         h323_gk_urq();
1638         
1639         /* Possibly register with a GK */
1640         if (!gatekeeper_disable) {
1641                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1642                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1643                 }
1644         }
1645         return RESULT_SUCCESS;
1646 #endif
1647 }
1648
1649 static int h323_ep_hangup(int fd, int argc, char *argv[])
1650 {
1651         if (argc != 3) {
1652                 return RESULT_SHOWUSAGE;
1653         }
1654         if (h323_soft_hangup(argv[2])) {
1655                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
1656         } else { 
1657                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
1658         }
1659         return RESULT_SUCCESS;
1660 }
1661
1662 static int h323_tokens_show(int fd, int argc, char *argv[])
1663 {
1664         if (argc != 3) {
1665                 return RESULT_SHOWUSAGE;
1666         }
1667         h323_show_tokens();
1668         return RESULT_SUCCESS;
1669 }
1670
1671 static char trace_usage[] = 
1672 "Usage: h.323 trace <level num>\n"
1673 "       Enables H.323 stack tracing for debugging purposes\n";
1674
1675 static char no_trace_usage[] = 
1676 "Usage: h.323 no trace\n"
1677 "       Disables H.323 stack tracing for debugging purposes\n";
1678
1679 static char debug_usage[] = 
1680 "Usage: h.323 debug\n"
1681 "       Enables H.323 debug output\n";
1682
1683 static char no_debug_usage[] = 
1684 "Usage: h.323 no debug\n"
1685 "       Disables H.323 debug output\n";
1686
1687 static char show_codec_usage[] = 
1688 "Usage: h.323 show codec\n"
1689 "       Shows all enabled codecs\n";
1690
1691 static char show_cycle_usage[] = 
1692 "Usage: h.323 gk cycle\n"
1693 "       Manually re-register with the Gatekeper (Currently Disabled)\n";
1694
1695 static char show_hangup_usage[] = 
1696 "Usage: h.323 hangup <token>\n"
1697 "       Manually try to hang up call identified by <token>\n";
1698
1699 static char show_tokens_usage[] = 
1700 "Usage: h.323 show tokens\n"
1701 "       Print out all active call tokens\n";
1702
1703 static char h323_reload_usage[] =
1704 "Usage: h323 reload\n"
1705 "       Reloads H.323 configuration from sip.conf\n";
1706
1707 static struct ast_cli_entry  cli_trace =
1708         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1709 static struct ast_cli_entry  cli_no_trace =
1710         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1711 static struct ast_cli_entry  cli_debug =
1712         { { "h.323", "debug", NULL }, h323_do_debug, "Enable H.323 debug", debug_usage };
1713 static struct ast_cli_entry  cli_no_debug =
1714         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable H.323 debug", no_debug_usage };
1715 static struct ast_cli_entry  cli_show_codecs =
1716         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1717 static struct ast_cli_entry  cli_gk_cycle =
1718         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1719 static struct ast_cli_entry  cli_hangup_call =
1720         { { "h.323", "hangup", NULL }, h323_ep_hangup, "Manually try to hang up a call", show_hangup_usage };
1721 static struct ast_cli_entry  cli_show_tokens =
1722         { { "h.323", "show", "tokens", NULL }, h323_tokens_show, "Show all active call tokens", show_tokens_usage };
1723
1724 int reload_config(void)
1725 {       
1726         int format;
1727         struct ast_config *cfg;
1728         struct ast_variable *v;
1729         struct oh323_peer *peer   = NULL;
1730         struct oh323_user *user   = NULL;
1731         struct oh323_alias *alias = NULL;
1732         struct ast_hostent ahp; struct hostent *hp;
1733         char *cat;
1734         char *utype;
1735         
1736         cfg = ast_config_load(config);
1737
1738         /* We *must* have a config file otherwise stop immediately */
1739         if (!cfg) {
1740                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
1741                 return 1;
1742         }
1743         
1744        /* fire up the H.323 Endpoint */       
1745         if (!h323_end_point_exist()) {
1746                h323_end_point_create();        
1747         }
1748         h323debug = 0;
1749         dtmfmode = H323_DTMF_RFC2833;
1750         memset(&bindaddr, 0, sizeof(bindaddr));
1751         memset(&global_options, 0, sizeof(global_options));
1752         global_options.dtmfcodec = 101;
1753         v = ast_variable_browse(cfg, "general");
1754         while(v) {
1755                 /* Create the interface list */
1756                 if (!strcasecmp(v->name, "port")) {
1757                         h323_signalling_port = (int)strtol(v->value, NULL, 10);
1758                 } else if (!strcasecmp(v->name, "bindaddr")) {
1759                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
1760                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1761                         } else {
1762                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1763                         }
1764                 } else if (!strcasecmp(v->name, "allow")) {
1765                         format = ast_getformatbyname(v->value);
1766                         if (format < 1) 
1767                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1768                         else
1769                                 capability |= format;
1770                 } else if (!strcasecmp(v->name, "disallow")) {
1771                         format = ast_getformatbyname(v->value);
1772                         if (format < 1) 
1773                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1774                         else
1775                                 capability &= ~format;
1776                 } else if (!strcasecmp(v->name, "tos")) {
1777                         if (sscanf(v->value, "%i", &format)) {
1778                                 tos = format & 0xff;
1779                         } else if (!strcasecmp(v->value, "lowdelay")) {
1780                                 tos = IPTOS_LOWDELAY;
1781                         } else if (!strcasecmp(v->value, "throughput")) {
1782                                 tos = IPTOS_THROUGHPUT;
1783                         } else if (!strcasecmp(v->value, "reliability")) {
1784                                 tos = IPTOS_RELIABILITY;
1785                         } else if (!strcasecmp(v->value, "mincost")) {
1786                                 tos = IPTOS_MINCOST;
1787                         } else if (!strcasecmp(v->value, "none")) {
1788                                 tos = 0;
1789                         } else {
1790                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
1791                         }
1792                 } else if (!strcasecmp(v->name, "gatekeeper")) {
1793                         if (!strcasecmp(v->value, "DISABLE")) {
1794                                 gatekeeper_disable = 1;
1795                                 usingGk = 0;
1796                         } else if (!strcasecmp(v->value, "DISCOVER")) {
1797                                 gatekeeper_disable = 0;
1798                                 gatekeeper_discover = 1;
1799                                 usingGk = 1;
1800                         } else {
1801                                 gatekeeper_disable = 0;
1802                                 usingGk = 1;
1803                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper) - 1);
1804                         }
1805                 } else if (!strcasecmp(v->name, "secret")) {
1806                         strncpy(secret, v->value, sizeof(secret) - 1);
1807                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
1808                         gkroute = ast_true(v->value);
1809                 } else if (!strcasecmp(v->name, "context")) {
1810                         strncpy(default_context, v->value, sizeof(default_context) - 1);
1811                         ast_verbose(VERBOSE_PREFIX_2 "Setting default context to %s\n", default_context);       
1812                 } else if (!strcasecmp(v->name, "dtmfmode")) {
1813                         if (!strcasecmp(v->value, "inband")) {
1814                                 dtmfmode=H323_DTMF_INBAND;
1815                         } else if (!strcasecmp(v->value, "rfc2833")) {
1816                                 dtmfmode = H323_DTMF_RFC2833;
1817                         } else {
1818                                 ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1819                                 dtmfmode = H323_DTMF_RFC2833;
1820                         }
1821                 } else if (!strcasecmp(v->name, "dtmfcodec")) {
1822                         global_options.dtmfcodec = atoi(v->value);
1823                 } else if (!strcasecmp(v->name, "UserByAlias")) {
1824                         userbyalias = ast_true(v->value);
1825                 } else if (!strcasecmp(v->name, "bridge")) {
1826                         bridging = ast_true(v->value);
1827                 } else if (!strcasecmp(v->name, "noFastStart")) {
1828                         global_options.noFastStart = ast_true(v->value);
1829                 } else if (!strcasecmp(v->name, "noH245Tunneling")) {
1830                         global_options.noH245Tunneling = ast_true(v->value);
1831                 } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
1832                         global_options.noSilenceSuppression = ast_true(v->value);
1833                 }
1834                 v = v->next;    
1835         }
1836         
1837         cat = ast_category_browse(cfg, NULL);
1838         while(cat) {
1839                 if (strcasecmp(cat, "general")) {
1840                         utype = ast_variable_retrieve(cfg, cat, "type");
1841                         if (utype) {
1842                                 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
1843                                         user = build_user(cat, ast_variable_browse(cfg, cat));
1844                                         if (user) {
1845                                                 ast_mutex_lock(&userl.lock);
1846                                                 user->next = userl.users;
1847                                                 userl.users = user;
1848                                                 ast_mutex_unlock(&userl.lock);
1849                                         }
1850                                 }  else if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
1851                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
1852                                         if (peer) {
1853                                                 ast_mutex_lock(&peerl.lock);
1854                                                 peer->next = peerl.peers;
1855                                                 peerl.peers = peer;
1856                                                 ast_mutex_unlock(&peerl.lock);
1857                                         }
1858                                 }  else if (!strcasecmp(utype, "h323") || !strcasecmp(utype, "alias")) {
1859                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
1860                                         if (alias) {
1861                                                 ast_mutex_lock(&aliasl.lock);
1862                                                 alias->next = aliasl.aliases;
1863                                                 aliasl.aliases = alias;
1864                                                 ast_mutex_unlock(&aliasl.lock);
1865                                         }
1866                                 } else {
1867                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
1868                                 }
1869                         } else {
1870                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
1871                         }
1872                 }
1873                 cat = ast_category_browse(cfg, cat);
1874         }
1875         ast_config_destroy(cfg);
1876
1877         /* Register our H.323 aliases if any*/
1878         while (alias) {         
1879                 if (h323_set_alias(alias)) {
1880                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
1881                         return -1;
1882                 }       
1883                 alias = alias->next;
1884         }
1885
1886         /* Add our capabilities */
1887         ast_mutex_lock(&caplock);
1888         if (h323_set_capability(capability, dtmfmode)) {
1889                 ast_log(LOG_ERROR, "Capabilities failure, this is bad.\n");
1890                 ast_mutex_unlock(&caplock);
1891                 return -1;
1892         }
1893         ast_mutex_unlock(&caplock);
1894         return 0;
1895 }
1896
1897 void delete_users(void)
1898 {
1899         struct oh323_user *user, *userlast;
1900         struct oh323_peer *peer;
1901         
1902         /* Delete all users */
1903         ast_mutex_lock(&userl.lock);
1904         for (user=userl.users;user;) {
1905                 userlast = user;
1906                 user=user->next;
1907                 free(userlast);
1908         }
1909         userl.users=NULL;
1910         ast_mutex_unlock(&userl.lock);
1911         ast_mutex_lock(&peerl.lock);
1912         for (peer=peerl.peers;peer;) {
1913                 /* Assume all will be deleted, and we'll find out for sure later */
1914                 peer->delme = 1;
1915                 peer = peer->next;
1916         }
1917         ast_mutex_unlock(&peerl.lock);
1918 }
1919
1920 void delete_aliases(void)
1921 {
1922         struct oh323_alias *alias, *aliaslast;
1923                 
1924         /* Delete all users */
1925         ast_mutex_lock(&aliasl.lock);
1926         for (alias=aliasl.aliases;alias;) {
1927                 aliaslast = alias;
1928                 alias=alias->next;
1929                 free(aliaslast);
1930         }
1931         aliasl.aliases=NULL;
1932         ast_mutex_unlock(&aliasl.lock);
1933 }
1934
1935 void prune_peers(void)
1936 {
1937         /* Prune peers who still are supposed to be deleted */
1938         struct oh323_peer *peer, *peerlast, *peernext;
1939         ast_mutex_lock(&peerl.lock);
1940         peerlast = NULL;
1941         for (peer=peerl.peers;peer;) {
1942                 peernext = peer->next;
1943                 if (peer->delme) {
1944                         free(peer);
1945                         if (peerlast) {
1946                                 peerlast->next = peernext;
1947                         } else {
1948                                 peerl.peers = peernext;
1949                         }
1950                 } else {
1951                         peerlast = peer;
1952                 }
1953                 peer = peernext;
1954         }
1955         ast_mutex_unlock(&peerl.lock);
1956 }
1957
1958 static int h323_reload(int fd, int argc, char *argv[])
1959 {
1960         ast_mutex_lock(&h323_reload_lock);
1961         if (h323_reloading) {
1962                 ast_verbose("Previous H.323 reload not yet done\n");
1963         } else {
1964                 h323_reloading = 1;
1965         }
1966         ast_mutex_unlock(&h323_reload_lock);
1967         restart_monitor();
1968         return 0;
1969 }
1970
1971 static int h323_do_reload(void)
1972 {
1973         delete_users();
1974         delete_aliases();
1975         prune_peers();
1976         reload_config();
1977         restart_monitor();
1978         return 0;
1979 }
1980
1981 int reload(void)
1982 {
1983         return h323_reload(0, 0, NULL);
1984 }
1985
1986 static struct ast_cli_entry  cli_h323_reload =
1987         { { "h.323", "reload", NULL }, h323_reload, "Reload H.323 configuration", h323_reload_usage };
1988
1989 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
1990 {
1991         struct oh323_pvt *p;
1992         p = (struct oh323_pvt *) chan->pvt->pvt;
1993         if (p && p->rtp && p->bridge) {
1994                 return p->rtp;
1995         }
1996         return NULL;
1997 }
1998
1999 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
2000 {
2001         return NULL;
2002 }
2003
2004 static char *convertcap(int cap)
2005 {
2006         switch (cap) {
2007         case AST_FORMAT_G723_1:
2008                 return "G.723";
2009         case AST_FORMAT_GSM:
2010                 return "GSM";
2011         case AST_FORMAT_ULAW:
2012                 return "ULAW";
2013         case AST_FORMAT_ALAW:
2014                 return "ALAW";
2015         case AST_FORMAT_ADPCM:
2016                 return "G.728";
2017         case AST_FORMAT_G729A:
2018                 return "G.729";
2019         case AST_FORMAT_SPEEX:
2020                 return "SPEEX";
2021         case AST_FORMAT_ILBC:
2022                 return "ILBC";
2023         default:
2024                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
2025                 return NULL;
2026         }
2027 }
2028
2029 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs)
2030 {
2031         /* XXX Deal with Video */
2032         struct oh323_pvt *p;
2033         struct sockaddr_in them;
2034         struct sockaddr_in us;
2035         char *mode;
2036         char iabuf[INET_ADDRSTRLEN];
2037
2038         if (!rtp) {
2039                 return 0;
2040         }
2041
2042         mode = convertcap(chan->writeformat); 
2043         p = (struct oh323_pvt *) chan->pvt->pvt;
2044         if (!p) {
2045                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
2046                 return -1;
2047         }
2048         ast_rtp_get_peer(rtp, &them);   
2049         ast_rtp_get_us(rtp, &us);
2050         h323_native_bridge(p->cd.call_token, ast_inet_ntoa(iabuf, sizeof(iabuf), them.sin_addr), mode);
2051         return 0;
2052 }
2053
2054 static struct ast_rtp_protocol oh323_rtp = {
2055         get_rtp_info: oh323_get_rtp_peer,
2056         get_vrtp_info: oh323_get_vrtp_peer,
2057         set_rtp_peer: oh323_set_rtp_peer,
2058 };
2059
2060 int load_module()
2061 {
2062         int res;
2063         ast_mutex_init(&userl.lock);
2064         ast_mutex_init(&peerl.lock);
2065         ast_mutex_init(&aliasl.lock);
2066         sched = sched_context_create();
2067         if (!sched) {
2068                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2069         }
2070         io = io_context_create();
2071         if (!io) {
2072                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2073         }
2074         res = reload_config();
2075         if (res) {
2076                 return 0;
2077         } else {
2078                 /* Make sure we can register our channel type */
2079                 if (ast_channel_register(type, tdesc, capability, oh323_request)) {
2080                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
2081                         h323_end_process();
2082                         return -1;
2083                 }
2084                 ast_cli_register(&cli_debug);
2085                 ast_cli_register(&cli_no_debug);
2086                 ast_cli_register(&cli_trace);
2087                 ast_cli_register(&cli_no_trace);
2088                 ast_cli_register(&cli_show_codecs);
2089                 ast_cli_register(&cli_gk_cycle);
2090                 ast_cli_register(&cli_hangup_call);
2091                 ast_cli_register(&cli_show_tokens);
2092                 ast_cli_register(&cli_h323_reload);
2093
2094                 oh323_rtp.type = type;
2095                 ast_rtp_proto_register(&oh323_rtp);
2096
2097                 /* Register our callback functions */
2098                 h323_callback_register(setup_incoming_call, 
2099                                        setup_outgoing_call,                                                      
2100                                        external_rtp_create, 
2101                                        setup_rtp_connection, 
2102                                        cleanup_connection, 
2103                                        chan_ringing,
2104                                        connection_made, 
2105                                        send_digit,
2106                                        answer_call,
2107                                        progress,
2108                                        set_dtmf_payload);
2109                 /* start the h.323 listener */
2110                 if (h323_start_listener(h323_signalling_port, bindaddr)) {
2111                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
2112                         return -1;
2113                 }
2114                 /* Possibly register with a GK */
2115                 if (!gatekeeper_disable) {
2116                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
2117                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
2118                                 return 0;
2119                         }
2120                 }
2121                 /* And start the monitor for the first time */
2122                 restart_monitor();
2123         }
2124         return res;
2125 }
2126
2127 int unload_module() 
2128 {
2129         struct oh323_pvt *p, *pl;
2130
2131         /* unregister commands */
2132         ast_cli_unregister(&cli_debug);
2133         ast_cli_unregister(&cli_no_debug);
2134         ast_cli_unregister(&cli_trace);
2135         ast_cli_unregister(&cli_no_trace);   
2136         ast_cli_unregister(&cli_show_codecs);
2137         ast_cli_unregister(&cli_gk_cycle);
2138         ast_cli_unregister(&cli_hangup_call);
2139         ast_cli_unregister(&cli_show_tokens);
2140         ast_cli_unregister(&cli_h323_reload);
2141         ast_rtp_proto_unregister(&oh323_rtp);
2142         ast_channel_unregister(type);
2143                 
2144         if (!ast_mutex_lock(&iflock)) {
2145                 /* hangup all interfaces if they have an owner */
2146                 p = iflist;
2147                 while(p) {
2148                         if (p->owner) {
2149                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
2150                         }
2151                         p = p->next;
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         if (!ast_mutex_lock(&monlock)) {
2160                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
2161                         /* this causes a seg, anyone know why? */
2162                         pthread_cancel(monitor_thread);
2163                         pthread_kill(monitor_thread, SIGURG);
2164                         pthread_join(monitor_thread, NULL);
2165                  }
2166                 monitor_thread = AST_PTHREADT_STOP;
2167                 ast_mutex_unlock(&monlock);
2168         } else {
2169                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2170                 return -1;
2171         }
2172         if (!ast_mutex_lock(&iflock)) {
2173                 /* destroy all the interfaces and free their memory */
2174                 p = iflist;
2175                 while(p) {
2176                         pl = p;
2177                         p = p->next;
2178                         /* free associated memory */
2179                         ast_mutex_destroy(&pl->lock);
2180                         free(pl);
2181                 }
2182                 iflist = NULL;
2183                 ast_mutex_unlock(&iflock);
2184         } else {
2185                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
2186                 return -1;
2187         }
2188         h323_gk_urq();
2189         h323_end_process();
2190         ast_mutex_destroy(&userl.lock);
2191         ast_mutex_destroy(&peerl.lock);
2192         return 0; 
2193
2194
2195 int usecount()
2196 {
2197         int res;
2198         ast_mutex_lock(&usecnt_lock);
2199         res = usecnt;
2200         ast_mutex_unlock(&usecnt_lock);
2201         return res;
2202 }
2203
2204 char *description()
2205 {
2206         return desc;
2207 }
2208
2209 char *key()
2210 {
2211         return ASTERISK_GPL_KEY;
2212 }