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