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