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