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