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