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