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