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