dc498a2d9dccb872215e0ed18724dd7ffcc075c6
[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_trace =
1825         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1826 static struct ast_cli_entry  cli_no_trace =
1827         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1828 static struct ast_cli_entry  cli_debug =
1829         { { "h.323", "debug", NULL }, h323_do_debug, "Enable H.323 debug", debug_usage };
1830 static struct ast_cli_entry  cli_no_debug =
1831         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable H.323 debug", no_debug_usage };
1832 static struct ast_cli_entry  cli_show_codecs =
1833         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1834 static struct ast_cli_entry  cli_gk_cycle =
1835         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1836 static struct ast_cli_entry  cli_hangup_call =
1837         { { "h.323", "hangup", NULL }, h323_ep_hangup, "Manually try to hang up a call", show_hangup_usage };
1838 static struct ast_cli_entry  cli_show_tokens =
1839         { { "h.323", "show", "tokens", NULL }, h323_tokens_show, "Show all active call tokens", show_tokens_usage };
1840
1841 static int update_common_options(struct ast_variable *v, struct call_options *options)
1842 {
1843         unsigned int format;
1844         int tmp;
1845
1846         if (!strcasecmp(v->name, "allow")) {
1847                 format = ast_getformatbyname(v->value);
1848                 if (format < 1) 
1849                         ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1850                 else
1851                         options->capability |= format;
1852         } else if (!strcasecmp(v->name, "disallow")) {
1853                 format = ast_getformatbyname(v->value);
1854                 if (format < 1) 
1855                         ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1856                 else
1857                         options->capability &= ~format;
1858         } else if (!strcasecmp(v->name, "dtmfmode")) {
1859                 if (!strcasecmp(v->value, "inband")) {
1860                         options->dtmfmode = H323_DTMF_INBAND;
1861                 } else if (!strcasecmp(v->value, "rfc2833")) {
1862                         options->dtmfmode = H323_DTMF_RFC2833;
1863                 } else {
1864                         ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1865                         options->dtmfmode = H323_DTMF_RFC2833;
1866                 }
1867         } else if (!strcasecmp(v->name, "dtmfcodec")) {
1868                 tmp = atoi(v->value);
1869                 if (tmp < 96)
1870                         ast_log(LOG_WARNING, "Invalid global dtmfcodec value %s\n", v->value);
1871                 else
1872                         options->dtmfcodec = tmp;
1873         } else if (!strcasecmp(v->name, "bridge")) {
1874                 options->bridge = ast_true(v->value);
1875         } else if (!strcasecmp(v->name, "nat")) {
1876                 options->nat = ast_true(v->value);
1877         } else if (!strcasecmp(v->name, "noFastStart")) {
1878                 options->noFastStart = ast_true(v->value);
1879         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
1880                 options->noH245Tunneling = ast_true(v->value);
1881         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
1882                 options->noSilenceSuppression = ast_true(v->value);
1883         } else if (!strcasecmp(v->name, "progress_setup")) {
1884                 tmp = atoi(v->value);
1885                 if ((tmp != 0) && (tmp != 1) && (tmp != 3) && (tmp != 8)) {
1886                         ast_log(LOG_WARNING, "Invalid value %d for progress_setup at line %d, assuming 0\n", tmp, v->lineno);
1887                         tmp = 0;
1888                 }
1889                 options->progress_setup = tmp;
1890         } else if (!strcasecmp(v->name, "progress_alert")) {
1891                 tmp = atoi(v->value);
1892                 if ((tmp != 0) && (tmp != 8)) {
1893                         ast_log(LOG_WARNING, "Invalud value %d for progress_alert at line %d, assuming 0\n", tmp, v->lineno);
1894                         tmp = 0;
1895                 }
1896                 options->progress_alert = tmp;
1897         } else if (!strcasecmp(v->name, "progress_audio")) {
1898                 options->progress_audio = ast_true(v->value);
1899         } else
1900                 return 1;
1901
1902         return 0;
1903 }
1904
1905 static struct oh323_alias *build_alias(char *name, struct ast_variable *v)
1906 {
1907         struct oh323_alias *alias;
1908
1909         alias = (struct oh323_alias *)malloc(sizeof(struct oh323_alias));
1910         if (alias) {
1911                 memset(alias, 0, sizeof(struct oh323_alias));
1912                 strncpy(alias->name, name, sizeof(alias->name) - 1);
1913                 while (v) {
1914                         if (!strcasecmp(v->name, "e164")) {
1915                                 strncpy(alias->e164,  v->value, sizeof(alias->e164) - 1);
1916                         } else if (!strcasecmp(v->name, "prefix")) {
1917                                 strncpy(alias->prefix,  v->value, sizeof(alias->prefix) - 1);
1918                         } else if (!strcasecmp(v->name, "context")) {
1919                                 strncpy(alias->context,  v->value, sizeof(alias->context) - 1);
1920                         } else if (!strcasecmp(v->name, "secret")) {
1921                                 strncpy(alias->secret,  v->value, sizeof(alias->secret) - 1);
1922                         } else {
1923                                 if (strcasecmp(v->value, "h323")) {     
1924                                         ast_log(LOG_WARNING, "Keyword %s does not make sense in type=h323\n", v->value);
1925                                 }
1926                         }
1927                         v = v->next;
1928                 }
1929         }
1930         return alias;
1931 }
1932
1933 static struct oh323_user *build_user(char *name, struct ast_variable *v)
1934 {
1935         struct oh323_user *user;
1936         int format;
1937
1938         user = (struct oh323_user *)malloc(sizeof(struct oh323_user));
1939         if (user) {
1940                 memset(user, 0, sizeof(struct oh323_user));
1941                 strncpy(user->name, name, sizeof(user->name) - 1);
1942                 memcpy(&user->options, &global_options, sizeof(user->options));
1943                 /* Set default context */
1944                 strncpy(user->context, default_context, sizeof(user->context) - 1);
1945                 while(v) {
1946                         if (!strcasecmp(v->name, "context")) {
1947                                 strncpy(user->context, v->value, sizeof(user->context) - 1);
1948                         } else if (!update_common_options(v, &user->options)) {
1949                                 /* dummy */
1950                         } else if (!strcasecmp(v->name, "secret")) {
1951                                 strncpy(user->secret, v->value, sizeof(user->secret) - 1);
1952                         } else if (!strcasecmp(v->name, "callerid")) {
1953                                 strncpy(user->callerid, v->value, sizeof(user->callerid) - 1);
1954                         } else if (!strcasecmp(v->name, "accountcode")) {
1955                                 strncpy(user->accountcode, v->value, sizeof(user->accountcode) - 1);
1956                         } else if (!strcasecmp(v->name, "host")) {
1957                                 if (!strcasecmp(v->value, "dynamic")) {
1958                                         ast_log(LOG_ERROR, "A dynamic host on a type=user does not make any sense\n");
1959                                         free(user);
1960                                         return NULL;
1961                                 } else if (ast_get_ip(&user->addr, v->value)) {
1962                                         free(user);
1963                                         return NULL;
1964                                 } 
1965                                 /* Let us know we need to use ip authentication */
1966                                 user->host = 1;
1967                         } else if (!strcasecmp(v->name, "amaflags")) {
1968                                 format = ast_cdr_amaflags2int(v->value);
1969                                 if (format < 0) {
1970                                         ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
1971                                 } else {
1972                                         user->amaflags = format;
1973                                 }
1974                         }
1975                         v = v->next;
1976                 }
1977         }
1978         return user;
1979 }
1980
1981 static struct oh323_peer *build_peer(char *name, struct ast_variable *v)
1982 {
1983         struct oh323_peer *peer;
1984         struct oh323_peer *prev;
1985         struct ast_ha *oldha = NULL;
1986         int found=0;
1987
1988         prev = NULL;
1989         ast_mutex_lock(&peerl.lock);
1990         peer = peerl.peers;
1991
1992         while(peer) {
1993                 if (!strcasecmp(peer->name, name)) {    
1994                         break;
1995                 }
1996                 prev = peer;
1997                 peer = peer->next;
1998         }
1999
2000         if (peer) {
2001                 found++;
2002                 /* Already in the list, remove it and it will be added back (or FREE'd) */
2003                 if (prev) {
2004                         prev->next = peer->next;
2005                 } else {
2006                         peerl.peers = peer->next;
2007                 }
2008                 ast_mutex_unlock(&peerl.lock);
2009         } else {
2010                 ast_mutex_unlock(&peerl.lock);
2011                 peer = (struct oh323_peer*)malloc(sizeof(struct oh323_peer));
2012                 if (peer)
2013                         memset(peer, 0, sizeof(struct oh323_peer));
2014         }
2015         if (peer) {
2016                 if (!found) {
2017                         strncpy(peer->name, name, sizeof(peer->name) - 1);
2018                         peer->addr.sin_port = htons(h323_signalling_port);
2019                         peer->addr.sin_family = AF_INET;
2020                 }
2021                 oldha = peer->ha;
2022                 peer->ha = NULL;
2023                 peer->addr.sin_family = AF_INET;
2024                 memcpy(&peer->options, &global_options, sizeof(peer->options));
2025
2026                 while(v) {
2027                         if (!update_common_options(v, &peer->options)) {
2028                                 /* dummy */
2029                         } else if (!strcasecmp(v->name, "host")) {
2030                                 if (!strcasecmp(v->value, "dynamic")) {
2031                                         ast_log(LOG_ERROR, "Dynamic host configuration not implemented.\n");
2032                                         free(peer);
2033                                         return NULL;
2034                                 }
2035                                 if (ast_get_ip(&peer->addr, v->value)) {
2036                                                 ast_log(LOG_ERROR, "Could not determine IP for %s\n", v->value);
2037                                                 free(peer);
2038                                                 return NULL;
2039                                 }
2040                         } else if (!strcasecmp(v->name, "port")) {
2041                                 peer->addr.sin_port = htons(atoi(v->value));
2042                         }
2043                         v=v->next;
2044                 }
2045         }
2046         return peer;
2047 }
2048
2049 int reload_config(void)
2050 {       
2051         int format;
2052         struct ast_config *cfg;
2053         struct ast_variable *v;
2054         struct oh323_peer *peer   = NULL;
2055         struct oh323_user *user   = NULL;
2056         struct oh323_alias *alias = NULL;
2057         struct ast_hostent ahp; struct hostent *hp;
2058         char *cat;
2059         char *utype;
2060         
2061         cfg = ast_config_load(config);
2062
2063         /* We *must* have a config file otherwise stop immediately */
2064         if (!cfg) {
2065                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
2066                 return 1;
2067         }
2068         
2069        /* fire up the H.323 Endpoint */       
2070         if (!h323_end_point_exist()) {
2071                h323_end_point_create();        
2072         }
2073         h323debug = 0;
2074         memset(&bindaddr, 0, sizeof(bindaddr));
2075         memset(&global_options, 0, sizeof(global_options));
2076         global_options.dtmfcodec = 101;
2077         global_options.dtmfmode = H323_DTMF_RFC2833;
2078         global_options.capability = GLOBAL_CAPABILITY;
2079         global_options.bridge = 1;              /* Do native bridging by default */
2080
2081         /* Copy the default jb config over global_jbconf */
2082         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
2083
2084         v = ast_variable_browse(cfg, "general");
2085         while (v) {
2086                 /* handle jb conf */
2087                 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
2088                         v = v->next;
2089                         continue;
2090                 }
2091
2092                 /* Create the interface list */
2093                 if (!strcasecmp(v->name, "port")) {
2094                         h323_signalling_port = (int)strtol(v->value, NULL, 10);
2095                 } else if (!strcasecmp(v->name, "bindaddr")) {
2096                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
2097                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
2098                         } else {
2099                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
2100                         }
2101                 } else if (!strcasecmp(v->name, "tos")) {
2102                         if (sscanf(v->value, "%d", &format)) {
2103                                 tos = format & 0xff;
2104                         } else if (!strcasecmp(v->value, "lowdelay")) {
2105                                 tos = IPTOS_LOWDELAY;
2106                         } else if (!strcasecmp(v->value, "throughput")) {
2107                                 tos = IPTOS_THROUGHPUT;
2108                         } else if (!strcasecmp(v->value, "reliability")) {
2109                                 tos = IPTOS_RELIABILITY;
2110                         } else if (!strcasecmp(v->value, "mincost")) {
2111                                 tos = IPTOS_MINCOST;
2112                         } else if (!strcasecmp(v->value, "none")) {
2113                                 tos = 0;
2114                         } else {
2115                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
2116                         }
2117                 } else if (!strcasecmp(v->name, "gatekeeper")) {
2118                         if (!strcasecmp(v->value, "DISABLE")) {
2119                                 gatekeeper_disable = 1;
2120                                 usingGk = 0;
2121                         } else if (!strcasecmp(v->value, "DISCOVER")) {
2122                                 gatekeeper_disable = 0;
2123                                 gatekeeper_discover = 1;
2124                                 usingGk = 1;
2125                         } else {
2126                                 gatekeeper_disable = 0;
2127                                 usingGk = 1;
2128                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper) - 1);
2129                         }
2130                 } else if (!strcasecmp(v->name, "secret")) {
2131                         strncpy(secret, v->value, sizeof(secret) - 1);
2132                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
2133                         gkroute = ast_true(v->value);
2134                 } else if (!strcasecmp(v->name, "context")) {
2135                         strncpy(default_context, v->value, sizeof(default_context) - 1);
2136                         ast_verbose(VERBOSE_PREFIX_2 "Setting default context to %s\n", default_context);       
2137                 } else if (!strcasecmp(v->name, "UserByAlias")) {
2138                         userbyalias = ast_true(v->value);
2139                 } else if (!update_common_options(v, &global_options)) {
2140                         /* dummy */
2141                 }
2142                 v = v->next;    
2143         }
2144         
2145         cat = ast_category_browse(cfg, NULL);
2146         while(cat) {
2147                 if (strcasecmp(cat, "general")) {
2148                         utype = ast_variable_retrieve(cfg, cat, "type");
2149                         if (utype) {
2150                                 if (!strcasecmp(utype, "user")) {
2151                                         user = build_user(cat, ast_variable_browse(cfg, cat));
2152                                         if (user) {
2153                                                 ast_mutex_lock(&userl.lock);
2154                                                 user->next = userl.users;
2155                                                 userl.users = user;
2156                                                 ast_mutex_unlock(&userl.lock);
2157                                         }
2158                                 }  else if (!strcasecmp(utype, "peer")) {
2159                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
2160                                         if (peer) {
2161                                                 ast_mutex_lock(&peerl.lock);
2162                                                 peer->next = peerl.peers;
2163                                                 peerl.peers = peer;
2164                                                 ast_mutex_unlock(&peerl.lock);
2165                                         }
2166                                 }  else if (!strcasecmp(utype, "friend")) {
2167                                         user = build_user(cat, ast_variable_browse(cfg, cat));
2168                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
2169                                         if (user) {
2170                                                 ast_mutex_lock(&userl.lock);
2171                                                 user->next = userl.users;
2172                                                 userl.users = user;
2173                                                 ast_mutex_unlock(&userl.lock);
2174                                         }
2175                                         if (peer) {
2176                                                 ast_mutex_lock(&peerl.lock);
2177                                                 peer->next = peerl.peers;
2178                                                 peerl.peers = peer;
2179                                                 ast_mutex_unlock(&peerl.lock);
2180                                         }
2181                                 }  else if (!strcasecmp(utype, "h323") || !strcasecmp(utype, "alias")) {
2182                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
2183                                         if (alias) {
2184                                                 ast_mutex_lock(&aliasl.lock);
2185                                                 alias->next = aliasl.aliases;
2186                                                 aliasl.aliases = alias;
2187                                                 ast_mutex_unlock(&aliasl.lock);
2188                                         }
2189                                 } else {
2190                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
2191                                 }
2192                         } else {
2193                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
2194                         }
2195                 }
2196                 cat = ast_category_browse(cfg, cat);
2197         }
2198         ast_config_destroy(cfg);
2199
2200         /* Register our H.323 aliases if any*/
2201         while (alias) {         
2202                 if (h323_set_alias(alias)) {
2203                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
2204                         return -1;
2205                 }       
2206                 alias = alias->next;
2207         }
2208
2209         return 0;
2210 }
2211
2212 void delete_users(void)
2213 {
2214         struct oh323_user *user, *userlast;
2215         struct oh323_peer *peer;
2216         
2217         /* Delete all users */
2218         ast_mutex_lock(&userl.lock);
2219         for (user=userl.users;user;) {
2220                 userlast = user;
2221                 user=user->next;
2222                 free(userlast);
2223         }
2224         userl.users=NULL;
2225         ast_mutex_unlock(&userl.lock);
2226         ast_mutex_lock(&peerl.lock);
2227         for (peer=peerl.peers;peer;) {
2228                 /* Assume all will be deleted, and we'll find out for sure later */
2229                 peer->delme = 1;
2230                 peer = peer->next;
2231         }
2232         ast_mutex_unlock(&peerl.lock);
2233 }
2234
2235 void delete_aliases(void)
2236 {
2237         struct oh323_alias *alias, *aliaslast;
2238                 
2239         /* Delete all users */
2240         ast_mutex_lock(&aliasl.lock);
2241         for (alias=aliasl.aliases;alias;) {
2242                 aliaslast = alias;
2243                 alias=alias->next;
2244                 free(aliaslast);
2245         }
2246         aliasl.aliases=NULL;
2247         ast_mutex_unlock(&aliasl.lock);
2248 }
2249
2250 void prune_peers(void)
2251 {
2252         /* Prune peers who still are supposed to be deleted */
2253         struct oh323_peer *peer, *peerlast, *peernext;
2254         ast_mutex_lock(&peerl.lock);
2255         peerlast = NULL;
2256         for (peer=peerl.peers;peer;) {
2257                 peernext = peer->next;
2258                 if (peer->delme) {
2259                         free(peer);
2260                         if (peerlast) {
2261                                 peerlast->next = peernext;
2262                         } else {
2263                                 peerl.peers = peernext;
2264                         }
2265                 } else {
2266                         peerlast = peer;
2267                 }
2268                 peer = peernext;
2269         }
2270         ast_mutex_unlock(&peerl.lock);
2271 }
2272
2273 static int h323_reload(int fd, int argc, char *argv[])
2274 {
2275         ast_mutex_lock(&h323_reload_lock);
2276         if (h323_reloading) {
2277                 ast_verbose("Previous H.323 reload not yet done\n");
2278         } else {
2279                 h323_reloading = 1;
2280         }
2281         ast_mutex_unlock(&h323_reload_lock);
2282         restart_monitor();
2283         return 0;
2284 }
2285
2286 static int h323_do_reload(void)
2287 {
2288         delete_users();
2289         delete_aliases();
2290         prune_peers();
2291         reload_config();
2292         restart_monitor();
2293         return 0;
2294 }
2295
2296 static int reload(void *mod)
2297 {
2298         return h323_reload(0, 0, NULL);
2299 }
2300
2301 static struct ast_cli_entry  cli_h323_reload =
2302         { { "h.323", "reload", NULL }, h323_reload, "Reload H.323 configuration", h323_reload_usage };
2303
2304 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
2305 {
2306         struct oh323_pvt *pvt;
2307         pvt = (struct oh323_pvt *) chan->tech_pvt;
2308         if (pvt && pvt->rtp && pvt->options.bridge) {
2309                 return pvt->rtp;
2310         }
2311         return NULL;
2312 }
2313
2314 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
2315 {
2316         return NULL;
2317 }
2318
2319 static char *convertcap(int cap)
2320 {
2321         switch (cap) {
2322         case AST_FORMAT_G723_1:
2323                 return "G.723";
2324         case AST_FORMAT_GSM:
2325                 return "GSM";
2326         case AST_FORMAT_ULAW:
2327                 return "ULAW";
2328         case AST_FORMAT_ALAW:
2329                 return "ALAW";
2330         case AST_FORMAT_ADPCM:
2331                 return "G.728";
2332         case AST_FORMAT_G729A:
2333                 return "G.729";
2334         case AST_FORMAT_SPEEX:
2335                 return "SPEEX";
2336         case AST_FORMAT_ILBC:
2337                 return "ILBC";
2338         default:
2339                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
2340                 return NULL;
2341         }
2342 }
2343
2344 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
2345 {
2346         /* XXX Deal with Video */
2347         struct oh323_pvt *pvt;
2348         struct sockaddr_in them;
2349         struct sockaddr_in us;
2350         char *mode;
2351         char iabuf[INET_ADDRSTRLEN];
2352
2353         if (!rtp) {
2354                 return 0;
2355         }
2356
2357         mode = convertcap(chan->writeformat); 
2358         pvt = (struct oh323_pvt *) chan->tech_pvt;
2359         if (!pvt) {
2360                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
2361                 return -1;
2362         }
2363         ast_rtp_get_peer(rtp, &them);   
2364         ast_rtp_get_us(rtp, &us);
2365         h323_native_bridge(pvt->cd.call_token, ast_inet_ntoa(iabuf, sizeof(iabuf), them.sin_addr), mode);
2366         return 0;
2367 }
2368
2369 static struct ast_rtp_protocol oh323_rtp = {
2370         .type = "H323",
2371         .get_rtp_info = oh323_get_rtp_peer,
2372         .get_vrtp_info = oh323_get_vrtp_peer,
2373         .set_rtp_peer=  oh323_set_rtp_peer,
2374 };
2375
2376 static int load_module(void *mod)
2377 {
2378         int res;
2379         ast_mutex_init(&userl.lock);
2380         ast_mutex_init(&peerl.lock);
2381         ast_mutex_init(&aliasl.lock);
2382         sched = sched_context_create();
2383         if (!sched) {
2384                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2385         }
2386         io = io_context_create();
2387         if (!io) {
2388                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2389         }
2390         res = reload_config();
2391         if (res) {
2392                 return 0;
2393         } else {
2394                 /* Make sure we can register our channel type */
2395                 if (ast_channel_register(&oh323_tech)) {
2396                         ast_log(LOG_ERROR, "Unable to register channel class 'H323'\n");
2397                         h323_end_process();
2398                         return -1;
2399                 }
2400                 ast_cli_register(&cli_debug);
2401                 ast_cli_register(&cli_no_debug);
2402                 ast_cli_register(&cli_trace);
2403                 ast_cli_register(&cli_no_trace);
2404                 ast_cli_register(&cli_show_codecs);
2405                 ast_cli_register(&cli_gk_cycle);
2406                 ast_cli_register(&cli_hangup_call);
2407                 ast_cli_register(&cli_show_tokens);
2408                 ast_cli_register(&cli_h323_reload);
2409
2410                 ast_rtp_proto_register(&oh323_rtp);
2411
2412                 /* Register our callback functions */
2413                 h323_callback_register(setup_incoming_call, 
2414                                                 setup_outgoing_call,                                                     
2415                                                 external_rtp_create, 
2416                                                 setup_rtp_connection, 
2417                                                 cleanup_connection, 
2418                                                 chan_ringing,
2419                                                 connection_made, 
2420                                                 send_digit,
2421                                                 answer_call,
2422                                                 progress,
2423                                                 set_dtmf_payload,
2424                                                 hangup_connection,
2425                                                 set_local_capabilities);
2426                 /* start the h.323 listener */
2427                 if (h323_start_listener(h323_signalling_port, bindaddr)) {
2428                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
2429                         return -1;
2430                 }
2431                 /* Possibly register with a GK */
2432                 if (!gatekeeper_disable) {
2433                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
2434                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
2435                                 return 0;
2436                         }
2437                 }
2438                 /* And start the monitor for the first time */
2439                 restart_monitor();
2440         }
2441         return res;
2442 }
2443
2444 static int unload_module(void *mod)
2445 {
2446         struct oh323_pvt *p, *pl;
2447
2448         /* unregister commands */
2449         ast_cli_unregister(&cli_debug);
2450         ast_cli_unregister(&cli_no_debug);
2451         ast_cli_unregister(&cli_trace);
2452         ast_cli_unregister(&cli_no_trace);   
2453         ast_cli_unregister(&cli_show_codecs);
2454         ast_cli_unregister(&cli_gk_cycle);
2455         ast_cli_unregister(&cli_hangup_call);
2456         ast_cli_unregister(&cli_show_tokens);
2457         ast_cli_unregister(&cli_h323_reload);
2458         ast_rtp_proto_unregister(&oh323_rtp);
2459         ast_channel_unregister(&oh323_tech);
2460                 
2461         if (!ast_mutex_lock(&iflock)) {
2462                 /* hangup all interfaces if they have an owner */
2463                 p = iflist;
2464                 while(p) {
2465                         if (p->owner) {
2466                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
2467                         }
2468                         p = p->next;
2469                 }
2470                 iflist = NULL;
2471                 ast_mutex_unlock(&iflock);
2472         } else {
2473                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
2474                 return -1;
2475         }
2476         if (!ast_mutex_lock(&monlock)) {
2477                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
2478                         /* this causes a seg, anyone know why? */
2479                         pthread_cancel(monitor_thread);
2480                         pthread_kill(monitor_thread, SIGURG);
2481                         pthread_join(monitor_thread, NULL);
2482                 }
2483                 monitor_thread = AST_PTHREADT_STOP;
2484                 ast_mutex_unlock(&monlock);
2485         } else {
2486                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2487                 return -1;
2488         }
2489         if (!ast_mutex_lock(&iflock)) {
2490                 /* destroy all the interfaces and free their memory */
2491                 p = iflist;
2492                 while(p) {
2493                         pl = p;
2494                         p = p->next;
2495                         /* free associated memory */
2496                         ast_mutex_destroy(&pl->lock);
2497                         free(pl);
2498                 }
2499                 iflist = NULL;
2500                 ast_mutex_unlock(&iflock);
2501         } else {
2502                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
2503                 return -1;
2504         }
2505         h323_gk_urq();
2506         h323_end_process();
2507         io_context_destroy(io);
2508         sched_context_destroy(sched);
2509         delete_users();
2510         delete_aliases();
2511         prune_peers();
2512         ast_mutex_destroy(&aliasl.lock);
2513         ast_mutex_destroy(&userl.lock);
2514         ast_mutex_destroy(&peerl.lock);
2515         return 0; 
2516
2517
2518 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "The NuFone Network's OpenH323 Channel Driver",
2519                 .load = load_module,
2520                 .unload = unload_module,
2521                 .reload = reload,
2522                );