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