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