Introduce Cisco G.726-32 capability (g726aal2 form)
[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>openh323</depend>
38         <defaultenabled>no</defaultenabled>
39  ***/
40
41 #ifdef __cplusplus
42 extern "C" {
43 #endif
44
45 #include "asterisk.h"
46
47 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
48
49 #ifdef __cplusplus
50 }
51 #endif
52
53 #include <sys/socket.h>
54 #include <sys/signal.h>
55 #include <sys/param.h>
56 #if defined(BSD)
57 #ifndef IPTOS_MINCOST
58 #define IPTOS_MINCOST 0x02
59 #endif
60 #endif
61 #include <arpa/inet.h>
62 #include <net/if.h>
63 #include <netinet/in.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/ip.h>
66 #include <unistd.h>
67 #include <stdlib.h>
68 #include <netdb.h>
69 #include <stdio.h>
70 #include <string.h>
71 #include <errno.h>
72 #include <fcntl.h>
73
74 #ifdef __cplusplus
75 extern "C" {
76 #endif
77
78 #include "asterisk/lock.h"
79 #include "asterisk/logger.h"
80 #include "asterisk/channel.h"
81 #include "asterisk/config.h"
82 #include "asterisk/module.h"
83 #include "asterisk/musiconhold.h"
84 #include "asterisk/pbx.h"
85 #include "asterisk/options.h"
86 #include "asterisk/utils.h"
87 #include "asterisk/lock.h"
88 #include "asterisk/sched.h"
89 #include "asterisk/io.h"
90 #include "asterisk/rtp.h"
91 #include "asterisk/acl.h"
92 #include "asterisk/callerid.h"
93 #include "asterisk/cli.h"
94 #include "asterisk/dsp.h"
95 #include "asterisk/causes.h"
96 #include "asterisk/stringfields.h"
97 #include "asterisk/abstract_jb.h"
98 #include "asterisk/astobj.h"
99
100 #ifdef __cplusplus
101 }
102 #endif
103
104 #include "h323/chan_h323.h"
105
106 receive_digit_cb on_receive_digit;
107 on_rtp_cb on_external_rtp_create;
108 start_rtp_cb on_start_rtp_channel;
109 setup_incoming_cb on_incoming_call;
110 setup_outbound_cb on_outgoing_call;
111 chan_ringing_cb on_chan_ringing;
112 con_established_cb on_connection_established;
113 clear_con_cb on_connection_cleared;
114 answer_call_cb on_answer_call;
115 progress_cb on_progress;
116 rfc2833_cb on_set_rfc2833_payload;
117 hangup_cb on_hangup;
118 setcapabilities_cb on_setcapabilities;
119 setpeercapabilities_cb on_setpeercapabilities;
120
121 /* global debug flag */
122 int h323debug;
123
124 /*! Global jitterbuffer configuration - by default, jb is disabled */
125 static struct ast_jb_conf default_jbconf =
126 {
127         .flags = 0,
128         .max_size = -1,
129         .resync_threshold = -1,
130         .impl = ""
131 };
132 static struct ast_jb_conf global_jbconf;
133
134 /** Variables required by Asterisk */
135 static const char tdesc[] = "The NuFone Network's Open H.323 Channel Driver";
136 static const char config[] = "h323.conf";
137 static char default_context[AST_MAX_CONTEXT] = "default";
138 static struct sockaddr_in bindaddr;
139
140 #define GLOBAL_CAPABILITY (AST_FORMAT_G723_1 | AST_FORMAT_GSM | AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_G729A | AST_FORMAT_G726_AAL2 | AST_FORMAT_H261)
141
142 /** H.323 configuration values */
143 static int h323_signalling_port = 1720;
144 static char gatekeeper[100];
145 static int gatekeeper_disable = 1;
146 static int gatekeeper_discover = 0;
147 static int gkroute = 0;
148 /* Find user by alias (h.323 id) is default, alternative is the incomming call's source IP address*/
149 static int userbyalias = 1;
150 static int acceptAnonymous = 1;
151 static int tos = 0;
152 static char secret[50];
153 static unsigned int unique = 0;
154
155 static call_options_t global_options;
156
157 /** Private structure of a OpenH323 channel */
158 struct oh323_pvt {
159         ast_mutex_t lock;                                       /* Channel private lock */
160         call_options_t options;                         /* Options to be used during call setup */
161         int alreadygone;                                        /* Whether or not we've already been destroyed by our peer */
162         int needdestroy;                                        /* if we need to be destroyed */
163         call_details_t cd;                                      /* Call details */
164         struct ast_channel *owner;                      /* Who owns us */
165         struct sockaddr_in sa;                          /* Our peer */
166         struct sockaddr_in redirip;                     /* Where our RTP should be going if not to us */
167         int nonCodecCapability;                         /* non-audio capability */
168         int outgoing;                                           /* Outgoing or incoming call? */
169         char exten[AST_MAX_EXTENSION];          /* Requested extension */
170         char context[AST_MAX_CONTEXT];          /* Context where to start */
171         char accountcode[256];                          /* Account code */
172         char rdnis[80];                                         /* Referring DNIS, if available */
173         int amaflags;                                           /* AMA Flags */
174         struct ast_rtp *rtp;                            /* RTP Session */
175         struct ast_dsp *vad;                            /* Used for in-band DTMF detection */
176         int nativeformats;                                      /* Codec formats supported by a channel */
177         int needhangup;                                         /* Send hangup when Asterisk is ready */
178         int hangupcause;                                        /* Hangup cause from OpenH323 layer */
179         int newstate;                                           /* Pending state change */
180         int newcontrol;                                         /* Pending control to send */
181         int newdigit;                                           /* Pending DTMF digit to send */
182         int newduration;                                        /* Pending DTMF digit duration to send */
183         int pref_codec;                                         /* Preferred codec */
184         int peercapability;                                     /* Capabilities learned from peer */
185         int jointcapability;                            /* Common capabilities for local and remote side */
186         struct ast_codec_pref peer_prefs;       /* Preferenced list of codecs which remote side supports */
187         int dtmf_pt;                                            /* Payload code used for RFC2833 messages */
188         int curDTMF;                                            /* DTMF tone being generated to Asterisk side */
189         int DTMFsched;                                          /* Scheduler descriptor for DTMF */
190         int update_rtp_info;                            /* Configuration of fd's array is pending */
191         int recvonly;                                           /* Peer isn't wish to receive our voice stream */
192         int txDtmfDigit;                                        /* DTMF digit being to send to H.323 side */
193         int noInbandDtmf;                                       /* Inband DTMF processing by DSP isn't available */
194         int connection_established;                     /* Call got CONNECT message */
195         struct oh323_pvt *next;                         /* Next channel in list */
196 } *iflist = NULL;
197
198 static struct ast_user_list {
199         ASTOBJ_CONTAINER_COMPONENTS(struct oh323_user);
200 } userl;
201
202 static struct ast_peer_list {
203         ASTOBJ_CONTAINER_COMPONENTS(struct oh323_peer);
204 } peerl;
205
206 static struct ast_alias_list {
207         ASTOBJ_CONTAINER_COMPONENTS(struct oh323_alias);
208 } aliasl;
209
210 /** Asterisk RTP stuff */
211 static struct sched_context *sched;
212 static struct io_context *io;
213
214 /** Protect the interface list (oh323_pvt) */
215 AST_MUTEX_DEFINE_STATIC(iflock);
216
217 /* Protect the monitoring thread, so only one process can kill or start it, and not
218    when it's doing something critical. */
219 AST_MUTEX_DEFINE_STATIC(monlock);
220
221 /* Protect the H.323 capabilities list, to avoid more than one channel to set the capabilities simultaneaously in the h323 stack. */
222 AST_MUTEX_DEFINE_STATIC(caplock);
223
224 /* Protect the reload process */
225 AST_MUTEX_DEFINE_STATIC(h323_reload_lock);
226 static int h323_reloading = 0;
227
228 /* This is the thread for the monitor which checks for input on the channels
229    which are not currently in use. */
230 static pthread_t monitor_thread = AST_PTHREADT_NULL;
231 static int restart_monitor(void);
232 static int h323_do_reload(void);
233
234 static struct ast_channel *oh323_request(const char *type, int format, void *data, int *cause);
235 static int oh323_digit_begin(struct ast_channel *c, char digit);
236 static int oh323_digit_end(struct ast_channel *c, char digit);
237 static int oh323_call(struct ast_channel *c, char *dest, int timeout);
238 static int oh323_hangup(struct ast_channel *c);
239 static int oh323_answer(struct ast_channel *c);
240 static struct ast_frame *oh323_read(struct ast_channel *c);
241 static int oh323_write(struct ast_channel *c, struct ast_frame *frame);
242 static int oh323_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
243 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
244
245 static const struct ast_channel_tech oh323_tech = {
246         .type = "H323",
247         .description = tdesc,
248         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
249         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
250         .requester = oh323_request,
251         .send_digit_begin = oh323_digit_begin,
252         .send_digit_end = oh323_digit_end,
253         .call = oh323_call,
254         .hangup = oh323_hangup,
255         .answer = oh323_answer,
256         .read = oh323_read,
257         .write = oh323_write,
258         .indicate = oh323_indicate,
259         .fixup = oh323_fixup,
260         /* disable, for now */
261 #if 0
262         .bridge = ast_rtp_bridge,
263 #endif
264 };
265
266 static const char* redirectingreason2str(int redirectingreason)
267 {
268         switch (redirectingreason) {
269         case 0:
270                 return "UNKNOWN";
271         case 1:
272                 return "BUSY";
273         case 2:
274                 return "NO_REPLY";
275         case 0xF:
276                 return "UNCONDITIONAL";
277         default:
278                 return "NOREDIRECT";
279         }
280 }
281
282 static void oh323_destroy_alias(struct oh323_alias *alias)
283 {
284         if (h323debug)
285                 ast_log(LOG_DEBUG, "Destroying alias '%s'\n", alias->name);
286         free(alias);
287 }
288
289 static void oh323_destroy_user(struct oh323_user *user)
290 {
291         if (h323debug)
292                 ast_log(LOG_DEBUG, "Destroying user '%s'\n", user->name);
293         ast_free_ha(user->ha);
294         free(user);
295 }
296
297 static void oh323_destroy_peer(struct oh323_peer *peer)
298 {
299         if (h323debug)
300                 ast_log(LOG_DEBUG, "Destroying peer '%s'\n", peer->name);
301         ast_free_ha(peer->ha);
302         free(peer);
303 }
304
305 static int oh323_simulate_dtmf_end(void *data)
306 {
307         struct oh323_pvt *pvt = data;
308
309         if (pvt) {
310                 ast_mutex_lock(&pvt->lock);
311                 /* Don't hold pvt lock while trying to lock the channel */
312                 while(pvt->owner && ast_channel_trylock(pvt->owner)) {
313                         ast_mutex_unlock(&pvt->lock);
314                         usleep(1);
315                         ast_mutex_lock(&pvt->lock);
316                 }
317
318                 if (pvt->owner) {
319                         struct ast_frame f = {
320                                 .frametype = AST_FRAME_DTMF_END,
321                                 .subclass = pvt->curDTMF,
322                                 .samples = 0,
323                                 .src = "SIMULATE_DTMF_END",
324                         };
325                         ast_queue_frame(pvt->owner, &f);
326                         ast_channel_unlock(pvt->owner);
327                 }
328
329                 pvt->DTMFsched = -1;
330                 ast_mutex_unlock(&pvt->lock);
331         }
332
333         return 0;
334 }
335
336 /* Channel and private structures should be already locked */
337 static void __oh323_update_info(struct ast_channel *c, struct oh323_pvt *pvt)
338 {
339         if (c->nativeformats != pvt->nativeformats) {
340                 if (h323debug)
341                         ast_log(LOG_DEBUG, "Preparing %s for new native format\n", c->name);
342                 c->nativeformats = pvt->nativeformats;
343                 ast_set_read_format(c, c->readformat);
344                 ast_set_write_format(c, c->writeformat);
345         }
346         if (pvt->needhangup) {
347                 if (h323debug)
348                         ast_log(LOG_DEBUG, "Process pending hangup for %s\n", c->name);
349                 c->_softhangup |= AST_SOFTHANGUP_DEV;
350                 c->hangupcause = pvt->hangupcause;
351                 ast_queue_hangup(c);
352                 pvt->needhangup = 0;
353                 pvt->newstate = pvt->newcontrol = pvt->newdigit = pvt->DTMFsched = -1;
354         }
355         if (pvt->newstate >= 0) {
356                 ast_setstate(c, pvt->newstate);
357                 pvt->newstate = -1;
358         }
359         if (pvt->newcontrol >= 0) {
360                 ast_queue_control(c, pvt->newcontrol);
361                 pvt->newcontrol = -1;
362         }
363         if (pvt->newdigit >= 0) {
364                 struct ast_frame f = {
365                         .frametype = AST_FRAME_DTMF_END,
366                         .subclass = pvt->newdigit,
367                         .samples = pvt->newduration * 8,
368                         .src = "UPDATE_INFO",
369                 };
370                 if (pvt->newdigit == ' ') {             /* signalUpdate message */
371                         f.subclass = pvt->curDTMF;
372                         if (pvt->DTMFsched >= 0) {
373                                 ast_sched_del(sched, pvt->DTMFsched);
374                                 pvt->DTMFsched = -1;
375                         }
376                 } else {                                                /* Regular input or signal message */
377                         if (pvt->newduration) {         /* This is a signal, signalUpdate follows */
378                                 f.frametype = AST_FRAME_DTMF_BEGIN;
379                                 if (pvt->DTMFsched >= 0)
380                                         ast_sched_del(sched, pvt->DTMFsched);
381                                 pvt->DTMFsched = ast_sched_add(sched, pvt->newduration, oh323_simulate_dtmf_end, pvt);
382                                 if (h323debug)
383                                         ast_log(LOG_DTMF, "Scheduled DTMF END simulation for %d ms, id=%d\n", pvt->newduration, pvt->DTMFsched);
384                         }
385                         pvt->curDTMF = pvt->newdigit;
386                 }
387                 ast_queue_frame(c, &f);
388                 pvt->newdigit = -1;
389         }
390         if (pvt->update_rtp_info > 0) {
391                 if (pvt->rtp) {
392                         ast_jb_configure(c, &global_jbconf);
393                         c->fds[0] = ast_rtp_fd(pvt->rtp);
394                         c->fds[1] = ast_rtcp_fd(pvt->rtp);
395                         ast_queue_frame(pvt->owner, &ast_null_frame);   /* Tell Asterisk to apply changes */
396                 }
397                 pvt->update_rtp_info = -1;
398         }
399 }
400
401 /* Only channel structure should be locked */
402 static void oh323_update_info(struct ast_channel *c)
403 {
404         struct oh323_pvt *pvt = c->tech_pvt;
405
406         if (pvt) {
407                 ast_mutex_lock(&pvt->lock);
408                 __oh323_update_info(c, pvt);
409                 ast_mutex_unlock(&pvt->lock);
410         }
411 }
412
413 static void cleanup_call_details(call_details_t *cd)
414 {
415         if (cd->call_token) {
416                 free(cd->call_token);
417                 cd->call_token = NULL;
418         }
419         if (cd->call_source_aliases) {
420                 free(cd->call_source_aliases);
421                 cd->call_source_aliases = NULL;
422         }
423         if (cd->call_dest_alias) {
424                 free(cd->call_dest_alias);
425                 cd->call_dest_alias = NULL;
426         }
427         if (cd->call_source_name) {
428                 free(cd->call_source_name);
429                 cd->call_source_name = NULL;
430         }
431         if (cd->call_source_e164) {
432                 free(cd->call_source_e164);
433                 cd->call_source_e164 = NULL;
434         }
435         if (cd->call_dest_e164) {
436                 free(cd->call_dest_e164);
437                 cd->call_dest_e164 = NULL;
438         }
439         if (cd->sourceIp) {
440                 free(cd->sourceIp);
441                 cd->sourceIp = NULL;
442         }
443         if (cd->redirect_number) {
444                 free(cd->redirect_number);
445                 cd->redirect_number = NULL;
446         }
447 }
448
449 static void __oh323_destroy(struct oh323_pvt *pvt)
450 {
451         struct oh323_pvt *cur, *prev = NULL;
452
453         if (pvt->DTMFsched >= 0) {
454                 ast_sched_del(sched, pvt->DTMFsched);
455                 pvt->DTMFsched = -1;
456         }
457
458         if (pvt->rtp) {
459                 ast_rtp_destroy(pvt->rtp);
460         }
461
462         /* Free dsp used for in-band DTMF detection */
463         if (pvt->vad) {
464                 ast_dsp_free(pvt->vad);
465         }
466         cleanup_call_details(&pvt->cd);
467
468         /* Unlink us from the owner if we have one */
469         if (pvt->owner) {
470                 ast_channel_lock(pvt->owner);
471                 if (h323debug)
472                         ast_log(LOG_DEBUG, "Detaching from %s\n", pvt->owner->name);
473                 pvt->owner->tech_pvt = NULL;
474                 ast_channel_unlock(pvt->owner);
475         }
476         cur = iflist;
477         while(cur) {
478                 if (cur == pvt) {
479                         if (prev)
480                                 prev->next = cur->next;
481                         else
482                                 iflist = cur->next;
483                         break;
484                 }
485                 prev = cur;
486                 cur = cur->next;
487         }
488         if (!cur) {
489                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
490         } else {
491                 ast_mutex_unlock(&pvt->lock);
492                 ast_mutex_destroy(&pvt->lock);
493                 free(pvt);
494         }
495 }
496
497 static void oh323_destroy(struct oh323_pvt *pvt)
498 {
499         if (h323debug) {
500                 ast_log(LOG_DEBUG, "Destroying channel %s\n", (pvt->owner ? pvt->owner->name : "<unknown>"));
501         }
502         ast_mutex_lock(&iflock);
503         ast_mutex_lock(&pvt->lock);
504         __oh323_destroy(pvt);
505         ast_mutex_unlock(&iflock);
506 }
507
508 static int oh323_digit_begin(struct ast_channel *c, char digit)
509 {
510         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
511         char *token;
512
513         if (!pvt) {
514                 ast_log(LOG_ERROR, "No private structure?! This is bad\n");
515                 return -1;
516         }
517         ast_mutex_lock(&pvt->lock);
518         if (pvt->rtp && (pvt->options.dtmfmode & H323_DTMF_RFC2833) && (pvt->dtmf_pt > 0)) {
519                 /* out-of-band DTMF */
520                 if (h323debug) {
521                         ast_log(LOG_DTMF, "Begin sending out-of-band digit %c on %s\n", digit, c->name);
522                 }
523                 ast_rtp_senddigit_begin(pvt->rtp, digit);
524                 ast_mutex_unlock(&pvt->lock);
525         } else if (pvt->txDtmfDigit != digit) {
526                 /* in-band DTMF */
527                 if (h323debug) {
528                         ast_log(LOG_DTMF, "Begin sending inband digit %c on %s\n", digit, c->name);
529                 }
530                 pvt->txDtmfDigit = digit;
531                 token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
532                 ast_mutex_unlock(&pvt->lock);
533                 h323_send_tone(token, digit);
534                 if (token) {
535                         free(token);
536                 }
537         } else
538                 ast_mutex_unlock(&pvt->lock);
539         oh323_update_info(c);
540         return 0;
541 }
542
543 /**
544  * Send (play) the specified digit to the channel.
545  *
546  */
547 static int oh323_digit_end(struct ast_channel *c, char digit)
548 {
549         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
550         char *token;
551
552         if (!pvt) {
553                 ast_log(LOG_ERROR, "No private structure?! This is bad\n");
554                 return -1;
555         }
556         ast_mutex_lock(&pvt->lock);
557         if (pvt->rtp && (pvt->options.dtmfmode & H323_DTMF_RFC2833) && (pvt->dtmf_pt > 0)) {
558                 /* out-of-band DTMF */
559                 if (h323debug) {
560                         ast_log(LOG_DTMF, "End sending out-of-band digit %c on %s\n", digit, c->name);
561                 }
562                 ast_rtp_senddigit_end(pvt->rtp, digit);
563                 ast_mutex_unlock(&pvt->lock);
564         } else {
565                 /* in-band DTMF */
566                 if (h323debug) {
567                         ast_log(LOG_DTMF, "End sending inband digit %c on %s\n", digit, c->name);
568                 }
569                 pvt->txDtmfDigit = ' ';
570                 token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
571                 ast_mutex_unlock(&pvt->lock);
572                 h323_send_tone(token, ' ');
573                 if (token) {
574                         free(token);
575                 }
576         }
577         oh323_update_info(c);
578         return 0;
579 }
580
581 /**
582  * Make a call over the specified channel to the specified
583  * destination.
584  * Returns -1 on error, 0 on success.
585  */
586 static int oh323_call(struct ast_channel *c, char *dest, int timeout)
587 {
588         int res = 0;
589         struct oh323_pvt *pvt = (struct oh323_pvt *)c->tech_pvt;
590         const char *addr;
591         char called_addr[1024];
592
593         if (h323debug) {
594                 ast_log(LOG_DEBUG, "Calling to %s on %s\n", dest, c->name);
595         }
596         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
597                 ast_log(LOG_WARNING, "Line is already in use (%s)\n", c->name);
598                 return -1;
599         }
600         ast_mutex_lock(&pvt->lock);
601         if (!gatekeeper_disable) {
602                 if (ast_strlen_zero(pvt->exten)) {
603                         strncpy(called_addr, dest, sizeof(called_addr));
604                 } else {
605                         snprintf(called_addr, sizeof(called_addr), "%s@%s", pvt->exten, dest);
606                 }
607         } else {
608                 res = htons(pvt->sa.sin_port);
609                 addr = ast_inet_ntoa(pvt->sa.sin_addr);
610                 if (ast_strlen_zero(pvt->exten)) {
611                         snprintf(called_addr, sizeof(called_addr), "%s:%d", addr, res);
612                 } else {
613                         snprintf(called_addr, sizeof(called_addr), "%s@%s:%d", pvt->exten, addr, res);
614                 }
615         }
616         /* make sure null terminated */
617         called_addr[sizeof(called_addr) - 1] = '\0';
618
619         if (c->cid.cid_num)
620                 strncpy(pvt->options.cid_num, c->cid.cid_num, sizeof(pvt->options.cid_num));
621
622         if (c->cid.cid_name)
623                 strncpy(pvt->options.cid_name, c->cid.cid_name, sizeof(pvt->options.cid_name));
624
625         if (c->cid.cid_rdnis) {
626                 strncpy(pvt->options.cid_rdnis, c->cid.cid_rdnis, sizeof(pvt->options.cid_rdnis));
627         }
628
629         if ((addr = pbx_builtin_getvar_helper(c, "PRIREDIRECTREASON"))) {
630                 if (!strcasecmp(addr, "UNKNOWN"))
631                         pvt->options.redirect_reason = 0;
632                 else if (!strcasecmp(addr, "BUSY"))
633                         pvt->options.redirect_reason = 1;
634                 else if (!strcasecmp(addr, "NO_REPLY"))
635                         pvt->options.redirect_reason = 2;
636                 else if (!strcasecmp(addr, "UNCONDITIONAL"))
637                         pvt->options.redirect_reason = 15;
638                 else
639                         pvt->options.redirect_reason = -1;
640         } else
641                 pvt->options.redirect_reason = -1;
642
643         /* indicate that this is an outgoing call */
644         pvt->outgoing = 1;
645
646         if (h323debug)
647                 ast_log(LOG_DEBUG, "Placing outgoing call to %s, %d\n", called_addr, pvt->options.dtmfcodec);
648         ast_mutex_unlock(&pvt->lock);
649         res = h323_make_call(called_addr, &(pvt->cd), &pvt->options);
650         if (res) {
651                 ast_log(LOG_NOTICE, "h323_make_call failed(%s)\n", c->name);
652                 return -1;
653         }
654         oh323_update_info(c);
655         return 0;
656 }
657
658 static int oh323_answer(struct ast_channel *c)
659 {
660         int res;
661         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
662         char *token;
663
664         if (h323debug)
665                 ast_log(LOG_DEBUG, "Answering on %s\n", c->name);
666
667         ast_mutex_lock(&pvt->lock);
668         token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
669         ast_mutex_unlock(&pvt->lock);
670         res = h323_answering_call(token, 0);
671         if (token)
672                 free(token);
673
674         oh323_update_info(c);
675         if (c->_state != AST_STATE_UP) {
676                 ast_setstate(c, AST_STATE_UP);
677         }
678         return res;
679 }
680
681 static int oh323_hangup(struct ast_channel *c)
682 {
683         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
684         int q931cause = AST_CAUSE_NORMAL_CLEARING;
685         char *call_token;
686
687
688         if (h323debug)
689                 ast_log(LOG_DEBUG, "Hanging up and scheduling destroy of call %s\n", c->name);
690
691         if (!c->tech_pvt) {
692                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
693                 return 0;
694         }
695         ast_mutex_lock(&pvt->lock);
696         /* Determine how to disconnect */
697         if (pvt->owner != c) {
698                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
699                 ast_mutex_unlock(&pvt->lock);
700                 return 0;
701         }
702
703         pvt->owner = NULL;
704         c->tech_pvt = NULL;
705
706         if (c->hangupcause) {
707                 q931cause = c->hangupcause;
708         } else {
709                 const char *cause = pbx_builtin_getvar_helper(c, "DIALSTATUS");
710                 if (cause) {
711                         if (!strcmp(cause, "CONGESTION")) {
712                                 q931cause = AST_CAUSE_NORMAL_CIRCUIT_CONGESTION;
713                         } else if (!strcmp(cause, "BUSY")) {
714                                 q931cause = AST_CAUSE_USER_BUSY;
715                         } else if (!strcmp(cause, "CHANISUNVAIL")) {
716                                 q931cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL;
717                         } else if (!strcmp(cause, "NOANSWER")) {
718                                 q931cause = AST_CAUSE_NO_ANSWER;
719                         } else if (!strcmp(cause, "CANCEL")) {
720                                 q931cause = AST_CAUSE_CALL_REJECTED;
721                         }
722                 }
723         }
724
725         /* Start the process if it's not already started */
726         if (!pvt->alreadygone && !pvt->hangupcause) {
727                 call_token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
728                 if (call_token) {
729                         /* Release lock to eliminate deadlock */
730                         ast_mutex_unlock(&pvt->lock);
731                         if (h323_clear_call(call_token, q931cause)) {
732                                 ast_log(LOG_WARNING, "ClearCall failed.\n");
733                         }
734                         free(call_token);
735                         ast_mutex_lock(&pvt->lock);
736                 }
737         }
738         pvt->needdestroy = 1;
739         ast_mutex_unlock(&pvt->lock);
740
741         /* Update usage counter */
742         ast_module_unref(ast_module_info->self);
743
744         return 0;
745 }
746
747 static struct ast_frame *oh323_rtp_read(struct oh323_pvt *pvt)
748 {
749         /* Retrieve audio/etc from channel. Assumes pvt->lock is already held. */
750         struct ast_frame *f;
751
752         /* Only apply it for the first packet, we just need the correct ip/port */
753         if (pvt->options.nat) {
754                 ast_rtp_setnat(pvt->rtp, pvt->options.nat);
755                 pvt->options.nat = 0;
756         }
757
758         f = ast_rtp_read(pvt->rtp);
759         /* Don't send RFC2833 if we're not supposed to */
760         if (f && (f->frametype == AST_FRAME_DTMF) && !(pvt->options.dtmfmode & H323_DTMF_RFC2833)) {
761                 return &ast_null_frame;
762         }
763         if (pvt->owner) {
764                 /* We already hold the channel lock */
765                 if (f->frametype == AST_FRAME_VOICE) {
766                         if (f->subclass != pvt->owner->nativeformats) {
767                                 /* Try to avoid deadlock */
768                                 if (ast_channel_trylock(pvt->owner)) {
769                                         ast_log(LOG_NOTICE, "Format changed but channel is locked. Ignoring frame...\n");
770                                         return &ast_null_frame;
771                                 }
772                                 if (h323debug)
773                                         ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
774                                 pvt->owner->nativeformats = f->subclass;
775                                 pvt->nativeformats = f->subclass;
776                                 ast_set_read_format(pvt->owner, pvt->owner->readformat);
777                                 ast_set_write_format(pvt->owner, pvt->owner->writeformat);
778                                 ast_channel_unlock(pvt->owner);
779                         }
780                         /* Do in-band DTMF detection */
781                         if ((pvt->options.dtmfmode & H323_DTMF_INBAND) && pvt->vad) {
782                                 if ((pvt->nativeformats & (AST_FORMAT_SLINEAR | AST_FORMAT_ALAW | AST_FORMAT_ULAW))) {
783                                         if (!ast_channel_trylock(pvt->owner)) {
784                                                 f = ast_dsp_process(pvt->owner, pvt->vad, f);
785                                                 ast_channel_unlock(pvt->owner);
786                                         }
787                                         else
788                                                 ast_log(LOG_NOTICE, "Unable to process inband DTMF while channel is locked\n");
789                                 } else if (pvt->nativeformats && !pvt->noInbandDtmf) {
790                                         ast_log(LOG_NOTICE, "Inband DTMF is not supported on codec %s. Use RFC2833\n", ast_getformatname(f->subclass));
791                                         pvt->noInbandDtmf = 1;
792                                 }
793                                 if (f &&(f->frametype == AST_FRAME_DTMF)) {
794                                         if (h323debug)
795                                                 ast_log(LOG_DTMF, "Received in-band digit %c.\n", f->subclass);
796                                 }
797                         }
798                 }
799         }
800         return f;
801 }
802
803 static struct ast_frame *oh323_read(struct ast_channel *c)
804 {
805         struct ast_frame *fr;
806         struct oh323_pvt *pvt = (struct oh323_pvt *)c->tech_pvt;
807         ast_mutex_lock(&pvt->lock);
808         __oh323_update_info(c, pvt);
809         switch(c->fdno) {
810         case 0:
811                 fr = oh323_rtp_read(pvt);
812                 break;
813         case 1:
814                 if (pvt->rtp)
815                         fr = ast_rtcp_read(pvt->rtp);
816                 else
817                         fr = &ast_null_frame;
818                 break;
819         default:
820                 ast_log(LOG_ERROR, "Unable to handle fd %d on channel %s\n", c->fdno, c->name);
821                 fr = &ast_null_frame;
822                 break;
823         }
824         ast_mutex_unlock(&pvt->lock);
825         return fr;
826 }
827
828 static int oh323_write(struct ast_channel *c, struct ast_frame *frame)
829 {
830         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
831         int res = 0;
832         if (frame->frametype != AST_FRAME_VOICE) {
833                 if (frame->frametype == AST_FRAME_IMAGE) {
834                         return 0;
835                 } else {
836                         ast_log(LOG_WARNING, "Can't send %d type frames with H323 write\n", frame->frametype);
837                         return 0;
838                 }
839         } else {
840                 if (!(frame->subclass & c->nativeformats)) {
841                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
842                                 frame->subclass, c->nativeformats, c->readformat, c->writeformat);
843                         return 0;
844                 }
845         }
846         if (pvt) {
847                 ast_mutex_lock(&pvt->lock);
848                 if (pvt->rtp && !pvt->recvonly)
849                         res = ast_rtp_write(pvt->rtp, frame);
850                 __oh323_update_info(c, pvt);
851                 ast_mutex_unlock(&pvt->lock);
852         }
853         return res;
854 }
855
856 static int oh323_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
857 {
858
859         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
860         char *token = (char *)NULL;
861
862         ast_mutex_lock(&pvt->lock);
863         token = (pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL);
864         ast_mutex_unlock(&pvt->lock);
865
866         if (h323debug)
867                 ast_log(LOG_DEBUG, "OH323: Indicating %d on %s\n", condition, token);
868
869         switch(condition) {
870         case AST_CONTROL_RINGING:
871                 if (c->_state == AST_STATE_RING || c->_state == AST_STATE_RINGING) {
872                         h323_send_alerting(token);
873                         break;
874                 }
875                 if (token)
876                         free(token);
877                 return -1;
878         case AST_CONTROL_PROGRESS:
879                 if (c->_state != AST_STATE_UP) {
880                         h323_send_progress(token);
881                         break;
882                 }
883                 if (token)
884                         free(token);
885                 return -1;
886         case AST_CONTROL_BUSY:
887                 if (c->_state != AST_STATE_UP) {
888                         h323_answering_call(token, 1);
889                         ast_mutex_lock(&pvt->lock);
890                         pvt->alreadygone = 1;
891                         ast_mutex_unlock(&pvt->lock);
892                         ast_softhangup_nolock(c, AST_SOFTHANGUP_DEV);
893                         break;
894                 }
895                 if (token)
896                         free(token);
897                 return -1;
898         case AST_CONTROL_CONGESTION:
899                 if (c->_state != AST_STATE_UP) {
900                         h323_answering_call(token, 1);
901                         ast_mutex_lock(&pvt->lock);
902                         pvt->alreadygone = 1;
903                         ast_mutex_unlock(&pvt->lock);
904                         ast_softhangup_nolock(c, AST_SOFTHANGUP_DEV);
905                         break;
906                 }
907                 if (token)
908                         free(token);
909                 return -1;
910         case AST_CONTROL_HOLD:
911                 ast_moh_start(c, data, NULL);
912                 if (token)
913                         free(token);
914                 return 0;
915         case AST_CONTROL_UNHOLD:
916                 ast_moh_stop(c);
917                 if (token)
918                         free(token);
919                 return 0;
920         case AST_CONTROL_PROCEEDING:
921         case -1:
922                 if (token)
923                         free(token);
924                 return -1;
925         default:
926                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d on %s\n", condition, token);
927                 if (token)
928                         free(token);
929                 return -1;
930         }
931
932         if (h323debug)
933                 ast_log(LOG_DEBUG, "OH323: Indicated %d on %s\n", condition, token);
934         if (token)
935                 free(token);
936         oh323_update_info(c);
937
938         return -1;
939 }
940
941 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
942 {
943         struct oh323_pvt *pvt = (struct oh323_pvt *) newchan->tech_pvt;
944
945         ast_mutex_lock(&pvt->lock);
946         if (pvt->owner != oldchan) {
947                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, pvt->owner);
948                 return -1;
949         }
950         pvt->owner = newchan;
951         ast_mutex_unlock(&pvt->lock);
952         return 0;
953 }
954
955 static int __oh323_rtp_create(struct oh323_pvt *pvt)
956 {
957         struct in_addr our_addr;
958
959         if (pvt->rtp)
960                 return 0;
961
962         if (ast_find_ourip(&our_addr, bindaddr)) {
963                 ast_mutex_unlock(&pvt->lock);
964                 ast_log(LOG_ERROR, "Unable to locate local IP address for RTP stream\n");
965                 return -1;
966         }
967         pvt->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, our_addr);
968         if (!pvt->rtp) {
969                 ast_mutex_unlock(&pvt->lock);
970                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
971                 return -1;
972         }
973         if (h323debug)
974                 ast_log(LOG_DEBUG, "Created RTP channel\n");
975
976         ast_rtp_settos(pvt->rtp, tos);
977
978         if (h323debug)
979                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", pvt->options.nat);
980         ast_rtp_setnat(pvt->rtp, pvt->options.nat);
981
982         if (pvt->dtmf_pt > 0)
983                 ast_rtp_set_rtpmap_type(pvt->rtp, pvt->dtmf_pt, "audio", "telephone-event", 0);
984
985         if (pvt->peercapability)
986                 ast_rtp_codec_setpref(pvt->rtp, &pvt->peer_prefs);
987
988         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
989                 ast_jb_configure(pvt->owner, &global_jbconf);
990                 pvt->owner->fds[0] = ast_rtp_fd(pvt->rtp);
991                 pvt->owner->fds[1] = ast_rtcp_fd(pvt->rtp);
992                 ast_queue_frame(pvt->owner, &ast_null_frame);   /* Tell Asterisk to apply changes */
993                 ast_channel_unlock(pvt->owner);
994         } else
995                 pvt->update_rtp_info = 1;
996
997         return 0;
998 }
999
1000 /* Private structure should be locked on a call */
1001 static struct ast_channel *__oh323_new(struct oh323_pvt *pvt, int state, const char *host)
1002 {
1003         struct ast_channel *ch;
1004         int fmt;
1005
1006         /* Don't hold a oh323_pvt lock while we allocate a chanel */
1007         ast_mutex_unlock(&pvt->lock);
1008         ch = ast_channel_alloc(1);
1009         /* Update usage counter */
1010         ast_module_ref(ast_module_info->self);
1011         ast_mutex_lock(&pvt->lock);
1012         if (ch) {
1013                 ch->tech = &oh323_tech;
1014                 ast_string_field_build(ch, name, "H323/%s", host);
1015                 if (!(fmt = pvt->jointcapability) && !(fmt = pvt->options.capability))
1016                         fmt = global_options.capability;
1017                 ch->nativeformats = ast_codec_choose(&pvt->options.prefs, fmt, 1)/* | (pvt->jointcapability & AST_FORMAT_VIDEO_MASK)*/;
1018                 pvt->nativeformats = ch->nativeformats;
1019                 fmt = ast_best_codec(ch->nativeformats);
1020                 ch->writeformat = fmt;
1021                 ch->rawwriteformat = fmt;
1022                 ch->readformat = fmt;
1023                 ch->rawreadformat = fmt;
1024 #if 0
1025                 ch->fds[0] = ast_rtp_fd(pvt->rtp);
1026                 ch->fds[1] = ast_rtcp_fd(pvt->rtp);
1027 #endif
1028 #ifdef VIDEO_SUPPORT
1029                 if (pvt->vrtp) {
1030                         ch->fds[2] = ast_rtp_fd(pvt->vrtp);
1031                         ch->fds[3] = ast_rtcp_fd(pvt->vrtp);
1032                 }
1033 #endif
1034 #ifdef T38_SUPPORT
1035                 if (pvt->udptl) {
1036                         ch->fds[4] = ast_udptl_fd(pvt->udptl);
1037                 }
1038 #endif
1039                 if (state == AST_STATE_RING) {
1040                         ch->rings = 1;
1041                 }
1042                 /* Allocate dsp for in-band DTMF support */
1043                 if (pvt->options.dtmfmode & H323_DTMF_INBAND) {
1044                         pvt->vad = ast_dsp_new();
1045                         ast_dsp_set_features(pvt->vad, DSP_FEATURE_DTMF_DETECT);
1046                 }
1047                 /* Register channel functions. */
1048                 ch->tech_pvt = pvt;
1049                 /* Set the owner of this channel */
1050                 pvt->owner = ch;
1051
1052                 strncpy(ch->context, pvt->context, sizeof(ch->context) - 1);
1053                 strncpy(ch->exten, pvt->exten, sizeof(ch->exten) - 1);
1054                 ch->priority = 1;
1055                 if (!ast_strlen_zero(pvt->accountcode)) {
1056                         ast_string_field_set(ch, accountcode, pvt->accountcode);
1057                 }
1058                 if (pvt->amaflags) {
1059                         ch->amaflags = pvt->amaflags;
1060                 }
1061
1062                 /* Don't use ast_set_callerid() here because it will
1063                  * generate a NewCallerID event before the NewChannel event */
1064                 if (!ast_strlen_zero(pvt->options.cid_num)) {
1065                         ch->cid.cid_num = ast_strdup(pvt->options.cid_num);
1066                         ch->cid.cid_ani = ast_strdup(pvt->options.cid_num);
1067                 } else {
1068                         ch->cid.cid_num = ast_strdup(pvt->cd.call_source_e164);
1069                         ch->cid.cid_ani = ast_strdup(pvt->cd.call_source_e164);
1070                 }
1071                 if (!ast_strlen_zero(pvt->options.cid_name))
1072                         ch->cid.cid_name = ast_strdup(pvt->options.cid_name);
1073                 else
1074                         ch->cid.cid_name = ast_strdup(pvt->cd.call_source_name);
1075                 if (pvt->cd.redirect_reason >= 0) {
1076                         ch->cid.cid_rdnis = ast_strdup(pvt->cd.redirect_number);
1077                         pbx_builtin_setvar_helper(ch, "PRIREDIRECTREASON", redirectingreason2str(pvt->cd.redirect_reason));
1078                 }
1079
1080                 if (!ast_strlen_zero(pvt->exten) && strcmp(pvt->exten, "s")) {
1081                         ch->cid.cid_dnid = strdup(pvt->exten);
1082                 }
1083                 ast_setstate(ch, state);
1084                 if (state != AST_STATE_DOWN) {
1085                         if (ast_pbx_start(ch)) {
1086                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ch->name);
1087                                 ast_hangup(ch);
1088                                 ch = NULL;
1089                         }
1090                 }
1091         } else {
1092                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1093         }
1094         return ch;
1095 }
1096
1097 static struct oh323_pvt *oh323_alloc(int callid)
1098 {
1099         struct oh323_pvt *pvt;
1100
1101         pvt = (struct oh323_pvt *) malloc(sizeof(struct oh323_pvt));
1102         if (!pvt) {
1103                 ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
1104                 return NULL;
1105         }
1106         memset(pvt, 0, sizeof(struct oh323_pvt));
1107         pvt->cd.redirect_reason = -1;
1108         /* Ensure the call token is allocated for outgoing call */
1109         if (!callid) {
1110                 if ((pvt->cd).call_token == NULL) {
1111                         (pvt->cd).call_token = (char *)malloc(128);
1112                 }
1113                 if (!pvt->cd.call_token) {
1114                         ast_log(LOG_ERROR, "Not enough memory to alocate call token\n");
1115                         ast_rtp_destroy(pvt->rtp);
1116                         free(pvt);
1117                         return NULL;
1118                 }
1119                 memset((char *)(pvt->cd).call_token, 0, 128);
1120                 pvt->cd.call_reference = callid;
1121         }
1122         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1123         pvt->jointcapability = pvt->options.capability;
1124         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1125                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1126         } else {
1127                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1128         }
1129         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
1130         pvt->newstate = pvt->newcontrol = pvt->newdigit = pvt->update_rtp_info = pvt->DTMFsched = -1;
1131         ast_mutex_init(&pvt->lock);
1132         /* Add to interface list */
1133         ast_mutex_lock(&iflock);
1134         pvt->next = iflist;
1135         iflist = pvt;
1136         ast_mutex_unlock(&iflock);
1137         return pvt;
1138 }
1139
1140 static struct oh323_pvt *find_call_locked(int call_reference, const char *token)
1141 {
1142         struct oh323_pvt *pvt;
1143
1144         ast_mutex_lock(&iflock);
1145         pvt = iflist;
1146         while(pvt) {
1147                 if (!pvt->needdestroy && ((signed int)pvt->cd.call_reference == call_reference)) {
1148                         /* Found the call */
1149                         if ((token != NULL) && (!strcmp(pvt->cd.call_token, token))) {
1150                                 ast_mutex_lock(&pvt->lock);
1151                                 ast_mutex_unlock(&iflock);
1152                                 return pvt;
1153                         } else if (token == NULL) {
1154                                 ast_log(LOG_WARNING, "Call Token is NULL\n");
1155                                 ast_mutex_lock(&pvt->lock);
1156                                 ast_mutex_unlock(&iflock);
1157                                 return pvt;
1158                         }
1159                 }
1160                 pvt = pvt->next;
1161         }
1162         ast_mutex_unlock(&iflock);
1163         return NULL;
1164 }
1165
1166 static int update_state(struct oh323_pvt *pvt, int state, int signal)
1167 {
1168         if (!pvt)
1169                 return 0;
1170         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
1171                 if (state >= 0)
1172                         ast_setstate(pvt->owner, state);
1173                 if (signal >= 0)
1174                         ast_queue_control(pvt->owner, signal);
1175                 ast_channel_unlock(pvt->owner);
1176                 return 1;
1177         }
1178         else {
1179                 if (state >= 0)
1180                         pvt->newstate = state;
1181                 if (signal >= 0)
1182                         pvt->newcontrol = signal;
1183                 return 0;
1184         }
1185 }
1186
1187 static struct oh323_alias *build_alias(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
1188 {
1189         struct oh323_alias *alias;
1190         int found = 0;
1191
1192         alias = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&aliasl, name, name, 0, 0, strcasecmp);
1193
1194         if (alias)
1195                 found++;
1196         else {
1197                 if (!(alias = (struct oh323_alias *)calloc(1, sizeof(*alias))))
1198                         return NULL;
1199                 ASTOBJ_INIT(alias);
1200         }
1201         if (!found && name)
1202                 strncpy(alias->name, name, sizeof(alias->name) - 1);
1203         for (; v || ((v = alt) && !(alt = NULL)); v = v->next) {
1204                 if (!strcasecmp(v->name, "e164")) {
1205                         strncpy(alias->e164, v->value, sizeof(alias->e164) - 1);
1206                 } else if (!strcasecmp(v->name, "prefix")) {
1207                         strncpy(alias->prefix, v->value, sizeof(alias->prefix) - 1);
1208                 } else if (!strcasecmp(v->name, "context")) {
1209                         strncpy(alias->context, v->value, sizeof(alias->context) - 1);
1210                 } else if (!strcasecmp(v->name, "secret")) {
1211                         strncpy(alias->secret, v->value, sizeof(alias->secret) - 1);
1212                 } else {
1213                         if (strcasecmp(v->value, "h323")) {
1214                                 ast_log(LOG_WARNING, "Keyword %s does not make sense in type=h323\n", v->name);
1215                         }
1216                 }
1217         }
1218         ASTOBJ_UNMARK(alias);
1219         return alias;
1220 }
1221
1222 static struct oh323_alias *realtime_alias(const char *alias)
1223 {
1224         struct ast_variable *var, *tmp;
1225         struct oh323_alias *a;
1226
1227         var = ast_load_realtime("h323", "name", alias, NULL);
1228
1229         if (!var)
1230                 return NULL;
1231
1232         for (tmp = var; tmp; tmp = tmp->next) {
1233                 if (!strcasecmp(tmp->name, "type") &&
1234                 !(!strcasecmp(tmp->value, "alias") || !strcasecmp(tmp->value, "h323"))) {
1235                         ast_variables_destroy(var);
1236                         return NULL;
1237                 }
1238         }
1239
1240         a = build_alias(alias, var, NULL, 1);
1241
1242         ast_variables_destroy(var);
1243
1244         return a;
1245 }
1246
1247 #define DEPRECATED(_v, _new_opt) \
1248         ast_log(LOG_WARNING, "Option %s found at line %d has beed deprecated. Use %s instead.\n", (_v)->name, (_v)->lineno, (_new_opt))
1249
1250 static int update_common_options(struct ast_variable *v, struct call_options *options)
1251 {
1252         int tmp;
1253
1254         if (!strcasecmp(v->name, "allow")) {
1255                 ast_parse_allow_disallow(&options->prefs, &options->capability, v->value, 1);
1256         } else if (!strcasecmp(v->name, "disallow")) {
1257                 ast_parse_allow_disallow(&options->prefs, &options->capability, v->value, 0);
1258         } else if (!strcasecmp(v->name, "dtmfmode")) {
1259                 if (!strcasecmp(v->value, "inband")) {
1260                         options->dtmfmode = H323_DTMF_INBAND;
1261                 } else if (!strcasecmp(v->value, "rfc2833")) {
1262                         options->dtmfmode = H323_DTMF_RFC2833;
1263                 } else {
1264                         ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1265                         options->dtmfmode = H323_DTMF_RFC2833;
1266                 }
1267         } else if (!strcasecmp(v->name, "dtmfcodec")) {
1268                 tmp = atoi(v->value);
1269                 if (tmp < 96)
1270                         ast_log(LOG_WARNING, "Invalid %s value %s at line %d\n", v->name, v->value, v->lineno);
1271                 else
1272                         options->dtmfcodec = tmp;
1273         } else if (!strcasecmp(v->name, "bridge")) {
1274                 options->bridge = ast_true(v->value);
1275         } else if (!strcasecmp(v->name, "nat")) {
1276                 options->nat = ast_true(v->value);
1277         } else if (!strcasecmp(v->name, "noFastStart")) {
1278                 DEPRECATED(v, "fastStart");
1279                 options->fastStart = !ast_true(v->value);
1280         } else if (!strcasecmp(v->name, "fastStart")) {
1281                 options->fastStart = ast_true(v->value);
1282         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
1283                 DEPRECATED(v, "h245Tunneling");
1284                 options->h245Tunneling = !ast_true(v->value);
1285         } else if (!strcasecmp(v->name, "h245Tunneling")) {
1286                 options->h245Tunneling = ast_true(v->value);
1287         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
1288                 DEPRECATED(v, "silenceSuppression");
1289                 options->silenceSuppression = !ast_true(v->value);
1290         } else if (!strcasecmp(v->name, "silenceSuppression")) {
1291                 options->silenceSuppression = ast_true(v->value);
1292         } else if (!strcasecmp(v->name, "progress_setup")) {
1293                 tmp = atoi(v->value);
1294                 if ((tmp != 0) && (tmp != 1) && (tmp != 3) && (tmp != 8)) {
1295                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d, assuming 0\n", v->value, v->name, v->lineno);
1296                         tmp = 0;
1297                 }
1298                 options->progress_setup = tmp;
1299         } else if (!strcasecmp(v->name, "progress_alert")) {
1300                 tmp = atoi(v->value);
1301                 if ((tmp != 0) && (tmp != 1) && (tmp != 8)) {
1302                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d, assuming 0\n", v->value, v->name, v->lineno);
1303                         tmp = 0;
1304                 }
1305                 options->progress_alert = tmp;
1306         } else if (!strcasecmp(v->name, "progress_audio")) {
1307                 options->progress_audio = ast_true(v->value);
1308         } else if (!strcasecmp(v->name, "callerid")) {
1309                 ast_callerid_split(v->value, options->cid_name, sizeof(options->cid_name), options->cid_num, sizeof(options->cid_num));
1310         } else if (!strcasecmp(v->name, "fullname")) {
1311                 ast_copy_string(options->cid_name, v->value, sizeof(options->cid_name));
1312         } else if (!strcasecmp(v->name, "cid_number")) {
1313                 ast_copy_string(options->cid_num, v->value, sizeof(options->cid_num));
1314         } else if (!strcasecmp(v->name, "tunneling")) {
1315                 if (!strcasecmp(v->value, "none"))
1316                         options->tunnelOptions = 0;
1317                 else if (!strcasecmp(v->value, "cisco"))
1318                         options->tunnelOptions |= H323_TUNNEL_CISCO;
1319                 else if (!strcasecmp(v->value, "qsig"))
1320                         options->tunnelOptions |= H323_TUNNEL_QSIG;
1321                 else
1322                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d\n", v->value, v->name, v->lineno);
1323         } else
1324                 return 1;
1325
1326         return 0;
1327 }
1328 #undef DEPRECATED
1329
1330 static struct oh323_user *build_user(char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
1331 {
1332         struct oh323_user *user;
1333         struct ast_ha *oldha;
1334         int found = 0;
1335         int format;
1336
1337         user = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&userl, name, name, 0, 0, strcmp);
1338
1339         if (user)
1340                 found++;
1341         else {
1342                 if (!(user = (struct oh323_user *)calloc(1, sizeof(*user))))
1343                         return NULL;
1344                 ASTOBJ_INIT(user);
1345         }
1346         oldha = user->ha;
1347         user->ha = (struct ast_ha *)NULL;
1348         memcpy(&user->options, &global_options, sizeof(user->options));
1349         /* Set default context */
1350         strncpy(user->context, default_context, sizeof(user->context) - 1);
1351         if (user && !found)
1352                 strncpy(user->name, name, sizeof(user->name) - 1);
1353
1354 #if 0 /* XXX Port channel variables functionality from chan_sip XXX */
1355         if (user->chanvars) {
1356                 ast_variables_destroy(user->chanvars);
1357                 user->chanvars = NULL;
1358         }
1359 #endif
1360
1361         for (; v || ((v = alt) && !(alt = NULL)); v = v->next) {
1362                 if (!update_common_options(v, &user->options))
1363                         continue;
1364                 if (!strcasecmp(v->name, "context")) {
1365                         strncpy(user->context, v->value, sizeof(user->context) - 1);
1366                 } else if (!strcasecmp(v->name, "secret")) {
1367                         strncpy(user->secret, v->value, sizeof(user->secret) - 1);
1368                 } else if (!strcasecmp(v->name, "accountcode")) {
1369                         strncpy(user->accountcode, v->value, sizeof(user->accountcode) - 1);
1370                 } else if (!strcasecmp(v->name, "host")) {
1371                         if (!strcasecmp(v->value, "dynamic")) {
1372                                 ast_log(LOG_ERROR, "A dynamic host on a type=user does not make any sense\n");
1373                                 ASTOBJ_UNREF(user, oh323_destroy_user);
1374                                 return NULL;
1375                         } else if (ast_get_ip(&user->addr, v->value)) {
1376                                 ASTOBJ_UNREF(user, oh323_destroy_user);
1377                                 return NULL;
1378                         }
1379                         /* Let us know we need to use ip authentication */
1380                         user->host = 1;
1381                 } else if (!strcasecmp(v->name, "amaflags")) {
1382                         format = ast_cdr_amaflags2int(v->value);
1383                         if (format < 0) {
1384                                 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
1385                         } else {
1386                                 user->amaflags = format;
1387                         }
1388                 } else if (!strcasecmp(v->name, "permit") ||
1389                                         !strcasecmp(v->name, "deny")) {
1390                         user->ha = ast_append_ha(v->name, v->value, user->ha);
1391                 }
1392         }
1393         ASTOBJ_UNMARK(user);
1394         ast_free_ha(oldha);
1395         return user;
1396 }
1397
1398 static struct oh323_user *realtime_user(const call_details_t *cd)
1399 {
1400         struct ast_variable *var, *tmp;
1401         struct oh323_user *user;
1402         char *username;
1403
1404         if (userbyalias)
1405                 var = ast_load_realtime("h323", "name", username = cd->call_source_aliases, NULL);
1406         else {
1407                 username = (char *)NULL;
1408                 var = ast_load_realtime("h323", "host", cd->sourceIp, NULL);
1409         }
1410
1411         if (!var)
1412                 return NULL;
1413
1414         for (tmp = var; tmp; tmp = tmp->next) {
1415                 if (!strcasecmp(tmp->name, "type") &&
1416                 !(!strcasecmp(tmp->value, "user") || !strcasecmp(tmp->value, "friend"))) {
1417                         ast_variables_destroy(var);
1418                         return NULL;
1419                 } else if (!username && !strcasecmp(tmp->name, "name"))
1420                         username = tmp->value;
1421         }
1422
1423         if (!username) {
1424                 ast_log(LOG_WARNING, "Cannot determine user name for IP address %s\n", cd->sourceIp);
1425                 ast_variables_destroy(var);
1426                 return NULL;
1427         }
1428
1429         user = build_user(username, var, NULL, 1);
1430
1431         ast_variables_destroy(var);
1432
1433         return user;
1434 }
1435
1436 static struct oh323_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
1437 {
1438         struct oh323_peer *peer;
1439         struct ast_ha *oldha;
1440         int found = 0;
1441
1442         peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
1443
1444         if (peer)
1445                 found++;
1446         else {
1447                 if (!(peer = (struct oh323_peer*)calloc(1, sizeof(*peer))))
1448                         return NULL;
1449                 ASTOBJ_INIT(peer);
1450         }
1451         oldha = peer->ha;
1452         peer->ha = NULL;
1453         memcpy(&peer->options, &global_options, sizeof(peer->options));
1454         peer->addr.sin_port = htons(h323_signalling_port);
1455         peer->addr.sin_family = AF_INET;
1456         if (!found && name)
1457                 strncpy(peer->name, name, sizeof(peer->name) - 1);
1458
1459 #if 0 /* XXX Port channel variables functionality from chan_sip XXX */
1460         if (peer->chanvars) {
1461                 ast_variables_destroy(peer->chanvars);
1462                 peer->chanvars = NULL;
1463         }
1464 #endif
1465         /* Default settings for mailbox */
1466         peer->mailbox[0] = '\0';
1467
1468         for (; v || ((v = alt) && !(alt = NULL)); v = v->next) {
1469                 if (!update_common_options(v, &peer->options))
1470                         continue;
1471                 if (!strcasecmp(v->name, "host")) {
1472                         if (!strcasecmp(v->value, "dynamic")) {
1473                                 ast_log(LOG_ERROR, "Dynamic host configuration not implemented.\n");
1474                                 ASTOBJ_UNREF(peer, oh323_destroy_peer);
1475                                 return NULL;
1476                         }
1477                         if (ast_get_ip(&peer->addr, v->value)) {
1478                                 ast_log(LOG_ERROR, "Could not determine IP for %s\n", v->value);
1479                                 ASTOBJ_UNREF(peer, oh323_destroy_peer);
1480                                 return NULL;
1481                         }
1482                 } else if (!strcasecmp(v->name, "port")) {
1483                         peer->addr.sin_port = htons(atoi(v->value));
1484                 } else if (!strcasecmp(v->name, "permit") ||
1485                                         !strcasecmp(v->name, "deny")) {
1486                         peer->ha = ast_append_ha(v->name, v->value, peer->ha);
1487                 } else if (!strcasecmp(v->name, "mailbox")) {
1488                         ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
1489                 }
1490         }
1491         ASTOBJ_UNMARK(peer);
1492         ast_free_ha(oldha);
1493         return peer;
1494 }
1495
1496 static struct oh323_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1497 {
1498         struct oh323_peer *peer;
1499         struct ast_variable *var;
1500         struct ast_variable *tmp;
1501         const char *addr;
1502
1503         /* First check on peer name */
1504         if (peername)
1505                 var = ast_load_realtime("h323", "name", peername, addr = NULL);
1506         else if (sin) /* Then check on IP address for dynamic peers */
1507                 var = ast_load_realtime("h323", "host", addr = ast_inet_ntoa(sin->sin_addr), NULL);
1508         else
1509                 return NULL;
1510
1511         if (!var)
1512                 return NULL;
1513
1514         for (tmp = var; tmp; tmp = tmp->next) {
1515                 /* If this is type=user, then skip this object. */
1516                 if (!strcasecmp(tmp->name, "type") &&
1517                                 !(!strcasecmp(tmp->value, "peer") || !strcasecmp(tmp->value, "friend"))) {
1518                         ast_variables_destroy(var);
1519                         return NULL;
1520                 } else if (!peername && !strcasecmp(tmp->name, "name")) {
1521                         peername = tmp->value;
1522                 }
1523         }
1524
1525         if (!peername) {        /* Did not find peer in realtime */
1526                 ast_log(LOG_WARNING, "Cannot determine peer name for IP address %s\n", addr);
1527                 ast_variables_destroy(var);
1528                 return NULL;
1529         }
1530
1531         /* Peer found in realtime, now build it in memory */
1532         peer = build_peer(peername, var, NULL, 1);
1533
1534         ast_variables_destroy(var);
1535
1536         return peer;
1537 }
1538
1539 static int oh323_addrcmp_str(struct in_addr inaddr, char *addr)
1540 {
1541         return strcmp(ast_inet_ntoa(inaddr), addr);
1542 }
1543
1544 static struct oh323_user *find_user(const call_details_t *cd, int realtime)
1545 {
1546         struct oh323_user *u;
1547
1548         if (userbyalias)
1549                 u = ASTOBJ_CONTAINER_FIND(&userl, cd->call_source_aliases);
1550         else
1551                 u = ASTOBJ_CONTAINER_FIND_FULL(&userl, cd->sourceIp, addr.sin_addr, 0, 0, oh323_addrcmp_str);
1552
1553         if (!u && realtime)
1554                 u = realtime_user(cd);
1555
1556         if (!u && h323debug)
1557                 ast_log(LOG_DEBUG, "Could not find user by name %s or address %s\n", cd->call_source_aliases, cd->sourceIp);
1558
1559         return u;
1560 }
1561
1562 static int oh323_addrcmp(struct sockaddr_in addr, struct sockaddr_in *sin)
1563 {
1564         int res;
1565
1566         if (!sin)
1567                 res = -1;
1568         else
1569                 res = inaddrcmp(&addr , sin);
1570
1571         return res;
1572 }
1573
1574 static struct oh323_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1575 {
1576         struct oh323_peer *p;
1577
1578         if (peer)
1579                 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
1580         else
1581                 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, addr, 0, 0, oh323_addrcmp);
1582
1583         if (!p && realtime)
1584                 p = realtime_peer(peer, sin);
1585
1586         if (!p && h323debug)
1587                 ast_log(LOG_DEBUG, "Could not find peer by name %s or address %s\n", (peer ? peer : "<NONE>"), (sin ? ast_inet_ntoa(sin->sin_addr) : "<NONE>"));
1588
1589         return p;
1590 }
1591
1592 static int create_addr(struct oh323_pvt *pvt, char *opeer)
1593 {
1594         struct hostent *hp;
1595         struct ast_hostent ahp;
1596         struct oh323_peer *p;
1597         int portno;
1598         int found = 0;
1599         char *port;
1600         char *hostn;
1601         char peer[256] = "";
1602
1603         strncpy(peer, opeer, sizeof(peer) - 1);
1604         port = strchr(peer, ':');
1605         if (port) {
1606                 *port = '\0';
1607                 port++;
1608         }
1609         pvt->sa.sin_family = AF_INET;
1610         p = find_peer(peer, NULL, 1);
1611         if (p) {
1612                 found++;
1613                 memcpy(&pvt->options, &p->options, sizeof(pvt->options));
1614                 pvt->jointcapability = pvt->options.capability;
1615                 if (pvt->options.dtmfmode) {
1616                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1617                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1618                         } else {
1619                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1620                         }
1621                 }
1622                 if (p->addr.sin_addr.s_addr) {
1623                         pvt->sa.sin_addr = p->addr.sin_addr;
1624                         pvt->sa.sin_port = p->addr.sin_port;
1625                 }
1626                 ASTOBJ_UNREF(p, oh323_destroy_peer);
1627         }
1628         if (!p && !found) {
1629                 hostn = peer;
1630                 if (port) {
1631                         portno = atoi(port);
1632                 } else {
1633                         portno = h323_signalling_port;
1634                 }
1635                 hp = ast_gethostbyname(hostn, &ahp);
1636                 if (hp) {
1637                         memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
1638                         pvt->sa.sin_port = htons(portno);
1639                         /* Look peer by address */
1640                         p = find_peer(NULL, &pvt->sa, 1);
1641                         memcpy(&pvt->options, (p ? &p->options : &global_options), sizeof(pvt->options));
1642                         pvt->jointcapability = pvt->options.capability;
1643                         if (p) {
1644                                 ASTOBJ_UNREF(p, oh323_destroy_peer);
1645                         }
1646                         if (pvt->options.dtmfmode) {
1647                                 if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1648                                         pvt->nonCodecCapability |= AST_RTP_DTMF;
1649                                 } else {
1650                                         pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1651                                 }
1652                         }
1653                         return 0;
1654                 } else {
1655                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1656                         return -1;
1657                 }
1658         } else if (!found) {
1659                 return -1;
1660         } else {
1661                 return 0;
1662         }
1663 }
1664 static struct ast_channel *oh323_request(const char *type, int format, void *data, int *cause)
1665 {
1666         int oldformat;
1667         struct oh323_pvt *pvt;
1668         struct ast_channel *tmpc = NULL;
1669         char *dest = (char *)data;
1670         char *ext, *host;
1671         char *h323id = NULL;
1672         char tmp[256], tmp1[256];
1673
1674         if (h323debug)
1675                 ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
1676
1677         pvt = oh323_alloc(0);
1678         if (!pvt) {
1679                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
1680                 return NULL;
1681         }
1682         oldformat = format;
1683         format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
1684         if (!format) {
1685                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
1686                 oh323_destroy(pvt);
1687                 if (cause)
1688                         *cause = AST_CAUSE_INCOMPATIBLE_DESTINATION;
1689                 return NULL;
1690         }
1691         strncpy(tmp, dest, sizeof(tmp) - 1);
1692         host = strchr(tmp, '@');
1693         if (host) {
1694                 *host = '\0';
1695                 host++;
1696                 ext = tmp;
1697         } else {
1698                 ext = strrchr(tmp, '/');
1699                 if (ext)
1700                         *ext++ = '\0';
1701                 host = tmp;
1702         }
1703         strtok_r(host, "/", &(h323id));
1704         if (!ast_strlen_zero(h323id)) {
1705                 h323_set_id(h323id);
1706         }
1707         if (ext) {
1708                 strncpy(pvt->exten, ext, sizeof(pvt->exten) - 1);
1709         }
1710         if (h323debug)
1711                 ast_log(LOG_DEBUG, "Extension: %s Host: %s\n", pvt->exten, host);
1712
1713         if (gatekeeper_disable) {
1714                 if (create_addr(pvt, host)) {
1715                         oh323_destroy(pvt);
1716                         if (cause)
1717                                 *cause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1718                         return NULL;
1719                 }
1720         }
1721         else {
1722                 memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1723                 pvt->jointcapability = pvt->options.capability;
1724                 if (pvt->options.dtmfmode) {
1725                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1726                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1727                         } else {
1728                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1729                         }
1730                 }
1731         }
1732
1733         ast_mutex_lock(&caplock);
1734         /* Generate unique channel identifier */
1735         snprintf(tmp1, sizeof(tmp1)-1, "%s-%u", host, ++unique);
1736         tmp1[sizeof(tmp1)-1] = '\0';
1737         ast_mutex_unlock(&caplock);
1738
1739         ast_mutex_lock(&pvt->lock);
1740         tmpc = __oh323_new(pvt, AST_STATE_DOWN, tmp1);
1741         ast_mutex_unlock(&pvt->lock);
1742         if (!tmpc) {
1743                 oh323_destroy(pvt);
1744                 if (cause)
1745                         *cause = AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
1746         }
1747         ast_update_use_count();
1748         restart_monitor();
1749         return tmpc;
1750 }
1751
1752 /** Find a call by alias */
1753 static struct oh323_alias *find_alias(const char *source_aliases, int realtime)
1754 {
1755         struct oh323_alias *a;
1756
1757         a = ASTOBJ_CONTAINER_FIND(&aliasl, source_aliases);
1758
1759         if (!a && realtime)
1760                 a = realtime_alias(source_aliases);
1761
1762         return a;
1763 }
1764
1765 /**
1766   * Callback for sending digits from H.323 up to asterisk
1767   *
1768   */
1769 static int receive_digit(unsigned call_reference, char digit, const char *token, int duration)
1770 {
1771         struct oh323_pvt *pvt;
1772         int res;
1773
1774         pvt = find_call_locked(call_reference, token);
1775         if (!pvt) {
1776                 ast_log(LOG_ERROR, "Received digit '%c' (%u ms) for call %s without private structure\n", digit, duration, token);
1777                 return -1;
1778         }
1779         if (h323debug)
1780                 ast_log(LOG_DTMF, "Received %s digit '%c' (%u ms) for call %s\n", (digit == ' ' ? "update for" : "new"), (digit == ' ' ? pvt->curDTMF : digit), duration, token);
1781
1782         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
1783                 if (digit == '!')
1784                         res = ast_queue_control(pvt->owner, AST_CONTROL_FLASH);
1785                 else {
1786                         struct ast_frame f = {
1787                                 .frametype = AST_FRAME_DTMF_END,
1788                                 .subclass = digit,
1789                                 .samples = duration * 8,
1790                                 .src = "SEND_DIGIT",
1791                         };
1792                         if (digit == ' ') {             /* signalUpdate message */
1793                                 f.subclass = pvt->curDTMF;
1794                                 if (pvt->DTMFsched >= 0) {
1795                                         ast_sched_del(sched, pvt->DTMFsched);
1796                                         pvt->DTMFsched = -1;
1797                                 }
1798                         } else {                                /* Regular input or signal message */
1799                                 if (duration) {         /* This is a signal, signalUpdate follows */
1800                                         f.frametype = AST_FRAME_DTMF_BEGIN;
1801                                         if (pvt->DTMFsched >= 0)
1802                                                 ast_sched_del(sched, pvt->DTMFsched);
1803                                         pvt->DTMFsched = ast_sched_add(sched, duration, oh323_simulate_dtmf_end, pvt);
1804                                         if (h323debug)
1805                                                 ast_log(LOG_DTMF, "Scheduled DTMF END simulation for %d ms, id=%d\n", duration, pvt->DTMFsched);
1806                                 }
1807                                 pvt->curDTMF = digit;
1808                         }
1809                         res = ast_queue_frame(pvt->owner, &f);
1810                 }
1811                 ast_channel_unlock(pvt->owner);
1812         } else {
1813                 if (digit == '!')
1814                         pvt->newcontrol = AST_CONTROL_FLASH;
1815                 else {
1816                         pvt->newduration = duration;
1817                         pvt->newdigit = digit;
1818                 }
1819                 res = 0;
1820         }
1821         ast_mutex_unlock(&pvt->lock);
1822         return res;
1823 }
1824
1825 /**
1826   * Callback function used to inform the H.323 stack of the local rtp ip/port details
1827   *
1828   * Returns the local RTP information
1829   */
1830 static struct rtp_info *external_rtp_create(unsigned call_reference, const char * token)
1831 {
1832         struct oh323_pvt *pvt;
1833         struct sockaddr_in us;
1834         struct rtp_info *info;
1835
1836         info = (struct rtp_info *)malloc(sizeof(struct rtp_info));
1837         if (!info) {
1838                 ast_log(LOG_ERROR, "Unable to allocated info structure, this is very bad\n");
1839                 return NULL;
1840         }
1841         pvt = find_call_locked(call_reference, token);
1842         if (!pvt) {
1843                 free(info);
1844                 ast_log(LOG_ERROR, "Unable to find call %s(%d)\n", token, call_reference);
1845                 return NULL;
1846         }
1847         if (!pvt->rtp)
1848                 __oh323_rtp_create(pvt);
1849         if (!pvt->rtp) {
1850                 ast_mutex_unlock(&pvt->lock);
1851                 free(info);
1852                 ast_log(LOG_ERROR, "No RTP stream is available for call %s (%d)", token, call_reference);
1853                 return NULL;
1854         }
1855         /* figure out our local RTP port and tell the H.323 stack about it */
1856         ast_rtp_get_us(pvt->rtp, &us);
1857         ast_mutex_unlock(&pvt->lock);
1858
1859         strncpy(info->addr, ast_inet_ntoa(us.sin_addr), sizeof(info->addr));
1860         info->addr[sizeof(info->addr)-1] = '\0';
1861         info->port = ntohs(us.sin_port);
1862         if (h323debug)
1863                 ast_log(LOG_DEBUG, "Sending RTP 'US' %s:%d\n", info->addr, info->port);
1864         return info;
1865 }
1866
1867 /**
1868  * Definition taken from rtp.c for rtpPayloadType because we need it here.
1869  */
1870 struct rtpPayloadType {
1871         int isAstFormat;        /* whether the following code is an AST_FORMAT */
1872         int code;
1873 };
1874
1875 /**
1876   * Call-back function passing remote ip/port information from H.323 to asterisk
1877   *
1878   * Returns nothing
1879   */
1880 static void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort, const char *token, int pt)
1881 {
1882         struct oh323_pvt *pvt;
1883         struct sockaddr_in them;
1884         struct rtpPayloadType rtptype;
1885         int nativeformats_changed;
1886         enum { NEED_NONE, NEED_HOLD, NEED_UNHOLD } rtp_change = NEED_NONE;
1887
1888         if (h323debug)
1889                 ast_log(LOG_DEBUG, "Setting up RTP connection for %s\n", token);
1890
1891         /* Find the call or allocate a private structure if call not found */
1892         pvt = find_call_locked(call_reference, token);
1893         if (!pvt) {
1894                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1895                 return;
1896         }
1897         if (pvt->alreadygone) {
1898                 ast_mutex_unlock(&pvt->lock);
1899                 return;
1900         }
1901
1902         if (!pvt->rtp)
1903                 __oh323_rtp_create(pvt);
1904
1905         if ((pt == 2) && (pvt->jointcapability & AST_FORMAT_G726_AAL2)) {
1906                 ast_rtp_set_rtpmap_type(pvt->rtp, pt, "audio", "G726-32", AST_RTP_OPT_G726_NONSTANDARD);
1907         }
1908
1909         them.sin_family = AF_INET;
1910         /* only works for IPv4 */
1911         them.sin_addr.s_addr = inet_addr(remoteIp);
1912         them.sin_port = htons(remotePort);
1913
1914         if (them.sin_addr.s_addr) {
1915                 ast_rtp_set_peer(pvt->rtp, &them);
1916                 if (pvt->recvonly) {
1917                         pvt->recvonly = 0;
1918                         rtp_change = NEED_UNHOLD;
1919                 }
1920         } else {
1921                 ast_rtp_stop(pvt->rtp);
1922                 if (!pvt->recvonly) {
1923                         pvt->recvonly = 1;
1924                         rtp_change = NEED_HOLD;
1925                 }
1926         }
1927
1928         /* Change native format to reflect information taken from OLC/OLCAck */
1929         nativeformats_changed = 0;
1930         if (pt != 128 && pvt->rtp) {    /* Payload type is invalid, so try to use previously decided */
1931                 rtptype = ast_rtp_lookup_pt(pvt->rtp, pt);
1932                 if (h323debug)
1933                         ast_log(LOG_DEBUG, "Native format is set to %d from %d by RTP payload type %d\n", rtptype.code, pvt->nativeformats, pt);
1934                 if (pvt->nativeformats != rtptype.code) {
1935                         pvt->nativeformats = rtptype.code;
1936                         nativeformats_changed = 1;
1937                 }
1938         } else if (h323debug)
1939                 ast_log(LOG_NOTICE, "Payload type is unknown, formats isn't changed\n");
1940
1941         /* Don't try to lock the channel if nothing changed */
1942         if (nativeformats_changed || pvt->options.progress_audio || (rtp_change != NEED_NONE)) {
1943                 if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
1944                         /* Re-build translation path only if native format(s) has been changed */
1945                         if (pvt->owner->nativeformats != pvt->nativeformats) {
1946                                 if (h323debug)
1947                                         ast_log(LOG_DEBUG, "Native format changed to %d from %d, read format is %d, write format is %d\n", pvt->nativeformats, pvt->owner->nativeformats, pvt->owner->readformat, pvt->owner->writeformat);
1948                                 pvt->owner->nativeformats = pvt->nativeformats;
1949                                 ast_set_read_format(pvt->owner, pvt->owner->readformat);
1950                                 ast_set_write_format(pvt->owner, pvt->owner->writeformat);
1951                         }
1952                         if (pvt->options.progress_audio)
1953                                 ast_queue_control(pvt->owner, AST_CONTROL_PROGRESS);
1954                         switch (rtp_change) {
1955                         case NEED_HOLD:
1956                                 ast_queue_control(pvt->owner, AST_CONTROL_HOLD);
1957                                 break;
1958                         case NEED_UNHOLD:
1959                                 ast_queue_control(pvt->owner, AST_CONTROL_UNHOLD);
1960                                 break;
1961                         default:
1962                                 break;
1963                         }
1964                         ast_channel_unlock(pvt->owner);
1965                 }
1966                 else {
1967                         if (pvt->options.progress_audio)
1968                                 pvt->newcontrol = AST_CONTROL_PROGRESS;
1969                         else if (rtp_change == NEED_HOLD)
1970                                 pvt->newcontrol = AST_CONTROL_HOLD;
1971                         else if (rtp_change == NEED_UNHOLD)
1972                                 pvt->newcontrol = AST_CONTROL_UNHOLD;
1973                         if (h323debug)
1974                                 ast_log(LOG_DEBUG, "RTP connection preparation for %s is pending...\n", token);
1975                 }
1976         }
1977         ast_mutex_unlock(&pvt->lock);
1978
1979         if (h323debug)
1980                 ast_log(LOG_DEBUG, "RTP connection prepared for %s\n", token);
1981
1982         return;
1983 }
1984
1985 /**
1986   *     Call-back function to signal asterisk that the channel has been answered
1987   * Returns nothing
1988   */
1989 static void connection_made(unsigned call_reference, const char *token)
1990 {
1991         struct oh323_pvt *pvt;
1992
1993         if (h323debug)
1994                 ast_log(LOG_DEBUG, "Call %s answered\n", token);
1995
1996         pvt = find_call_locked(call_reference, token);
1997         if (!pvt) {
1998                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1999                 return;
2000         }
2001
2002         /* Inform asterisk about remote party connected only on outgoing calls */
2003         if (!pvt->outgoing) {
2004                 ast_mutex_unlock(&pvt->lock);
2005                 return;
2006         }
2007         /* Do not send ANSWER message more than once */
2008         if (!pvt->connection_established) {
2009                 pvt->connection_established = 1;
2010                 update_state(pvt, -1, AST_CONTROL_ANSWER);
2011         }
2012         ast_mutex_unlock(&pvt->lock);
2013         return;
2014 }
2015
2016 static int progress(unsigned call_reference, const char *token, int inband)
2017 {
2018         struct oh323_pvt *pvt;
2019
2020         if (h323debug)
2021                 ast_log(LOG_DEBUG, "Received ALERT/PROGRESS message for %s tones\n", (inband ? "inband" : "self-generated"));
2022
2023         pvt = find_call_locked(call_reference, token);
2024         if (!pvt) {
2025                 ast_log(LOG_ERROR, "Private structure not found in progress.\n");
2026                 return -1;
2027         }
2028         if (!pvt->owner) {
2029                 ast_mutex_unlock(&pvt->lock);
2030                 ast_log(LOG_ERROR, "No Asterisk channel associated with private structure.\n");
2031                 return -1;
2032         }
2033         update_state(pvt, -1, (inband ? AST_CONTROL_PROGRESS : AST_CONTROL_RINGING));
2034         ast_mutex_unlock(&pvt->lock);
2035
2036         return 0;
2037 }
2038
2039 /**
2040  *  Call-back function for incoming calls
2041  *
2042  *  Returns 1 on success
2043  */
2044 static call_options_t *setup_incoming_call(call_details_t *cd)
2045 {
2046         struct oh323_pvt *pvt;
2047         struct oh323_user *user = NULL;
2048         struct oh323_alias *alias = NULL;
2049
2050         if (h323debug)
2051                 ast_log(LOG_DEBUG, "Setting up incoming call for %s\n", cd->call_token);
2052
2053         /* allocate the call*/
2054         pvt = oh323_alloc(cd->call_reference);
2055
2056         if (!pvt) {
2057                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
2058                 cleanup_call_details(cd);
2059                 return NULL;
2060         }
2061
2062         /* Populate the call details in the private structure */
2063         memcpy(&pvt->cd, cd, sizeof(pvt->cd));
2064         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
2065         pvt->jointcapability = pvt->options.capability;
2066
2067         if (h323debug) {
2068                 ast_verbose(VERBOSE_PREFIX_3 "Setting up Call\n");
2069                 ast_verbose(VERBOSE_PREFIX_3 " \tCall token:  [%s]\n", pvt->cd.call_token);
2070                 ast_verbose(VERBOSE_PREFIX_3 " \tCalling party name:  [%s]\n", pvt->cd.call_source_name);
2071                 ast_verbose(VERBOSE_PREFIX_3 " \tCalling party number:  [%s]\n", pvt->cd.call_source_e164);
2072                 ast_verbose(VERBOSE_PREFIX_3 " \tCalled party name:  [%s]\n", pvt->cd.call_dest_alias);
2073                 ast_verbose(VERBOSE_PREFIX_3 " \tCalled party number:  [%s]\n", pvt->cd.call_dest_e164);
2074                 if (pvt->cd.redirect_reason >= 0)
2075                         ast_verbose(VERBOSE_PREFIX_3 " \tRedirecting party number:  [%s] (reason %d)\n", pvt->cd.redirect_number, pvt->cd.redirect_reason);
2076                 ast_verbose(VERBOSE_PREFIX_3 " \tCalling party IP:  [%s]\n", pvt->cd.sourceIp);
2077         }
2078
2079         /* Decide if we are allowing Gatekeeper routed calls*/
2080         if ((!strcasecmp(cd->sourceIp, gatekeeper)) && (gkroute == -1) && !gatekeeper_disable) {
2081                 if (!ast_strlen_zero(cd->call_dest_e164)) {
2082                         strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
2083                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
2084                 } else {
2085                         alias = find_alias(cd->call_dest_alias, 1);
2086                         if (!alias) {
2087                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd->call_dest_alias);
2088                                 oh323_destroy(pvt);
2089                                 return NULL;
2090                         }
2091                         strncpy(pvt->exten, alias->name, sizeof(pvt->exten) - 1);
2092                         strncpy(pvt->context, alias->context, sizeof(pvt->context) - 1);
2093                 }
2094         } else {
2095                 /* Either this call is not from the Gatekeeper
2096                    or we are not allowing gk routed calls */
2097                 user = find_user(cd, 1);
2098                 if (!user) {
2099                         if (!acceptAnonymous) {
2100                                 ast_log(LOG_NOTICE, "Anonymous call from '%s@%s' rejected\n", pvt->cd.call_source_aliases, pvt->cd.sourceIp);
2101                                 oh323_destroy(pvt);
2102                                 return NULL;
2103                         }
2104                         if (ast_strlen_zero(default_context)) {
2105                                 ast_log(LOG_ERROR, "Call from '%s@%s' rejected due to no default context\n", pvt->cd.call_source_aliases, pvt->cd.sourceIp);
2106                                 oh323_destroy(pvt);
2107                                 return NULL;
2108                         }
2109                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
2110                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
2111                                 strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
2112                         } else {
2113                                 strncpy(pvt->exten, cd->call_dest_alias, sizeof(pvt->exten) - 1);
2114                         }
2115                         if (h323debug)
2116                                 ast_log(LOG_DEBUG, "Sending %s@%s to context [%s] extension %s\n", cd->call_source_aliases, cd->sourceIp, pvt->context, pvt->exten);
2117                 } else {
2118                         if (user->host) {
2119                                 if (strcasecmp(cd->sourceIp, ast_inet_ntoa(user->addr.sin_addr))) {
2120                                         if (ast_strlen_zero(user->context)) {
2121                                                 if (ast_strlen_zero(default_context)) {
2122                                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s) and no default context\n", user->name, cd->sourceIp);
2123                                                         oh323_destroy(pvt);
2124                                                         ASTOBJ_UNREF(user, oh323_destroy_user);
2125                                                         return NULL;
2126                                                 }
2127                                                 strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
2128                                         } else {
2129                                                 strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
2130                                         }
2131                                         pvt->exten[0] = 'i';
2132                                         pvt->exten[1] = '\0';
2133                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s)s\n", user->name, cd->sourceIp);
2134                                         oh323_destroy(pvt);
2135                                         ASTOBJ_UNREF(user, oh323_destroy_user);
2136                                         return NULL;    /* XXX: Hmmm... Why to setup context if we drop connection immediately??? */
2137                                 }
2138                         }
2139                         strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
2140                         memcpy(&pvt->options, &user->options, sizeof(pvt->options));
2141                         pvt->jointcapability = pvt->options.capability;
2142                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
2143                                 strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
2144                         } else {
2145                                 strncpy(pvt->exten, cd->call_dest_alias, sizeof(pvt->exten) - 1);
2146                         }
2147                         if (!ast_strlen_zero(user->accountcode)) {
2148                                 strncpy(pvt->accountcode, user->accountcode, sizeof(pvt->accountcode) - 1);
2149                         }
2150                         if (user->amaflags) {
2151                                 pvt->amaflags = user->amaflags;
2152                         }
2153                         ASTOBJ_UNREF(user, oh323_destroy_user);
2154                 }
2155         }
2156         return &pvt->options;
2157 }
2158
2159 /**
2160  * Call-back function to start PBX when OpenH323 ready to serve incoming call
2161  *
2162  * Returns 1 on success
2163  */
2164 static int answer_call(unsigned call_reference, const char *token)
2165 {
2166         struct oh323_pvt *pvt;
2167         struct ast_channel *c = NULL;
2168         enum {ext_original, ext_s, ext_i, ext_notexists} try_exten;
2169         char tmp_exten[sizeof(pvt->exten)];
2170
2171         if (h323debug)
2172                 ast_log(LOG_DEBUG, "Preparing Asterisk to answer for %s\n", token);
2173
2174         /* Find the call or allocate a private structure if call not found */
2175         pvt = find_call_locked(call_reference, token);
2176         if (!pvt) {
2177                 ast_log(LOG_ERROR, "Something is wrong: answer_call\n");
2178                 return 0;
2179         }
2180         /* Check if requested extension@context pair exists in the dialplan */
2181         strncpy(tmp_exten, pvt->exten, sizeof(tmp_exten));
2182
2183         /* Try to find best extension in specified context */
2184         if ((tmp_exten[0] != '\0') && (tmp_exten[1] == '\0')) {
2185                 if (tmp_exten[0] == 's')
2186                         try_exten = ext_s;
2187                 else if (tmp_exten[0] == 'i')
2188                         try_exten = ext_i;
2189                 else
2190                         try_exten = ext_original;
2191         } else
2192                 try_exten = ext_original;
2193         do {
2194                 if (ast_exists_extension(NULL, pvt->context, tmp_exten, 1, NULL))
2195                         break;
2196                 switch (try_exten) {
2197                 case ext_original:
2198                         tmp_exten[0] = 's';
2199                         tmp_exten[1] = '\0';
2200                         try_exten = ext_s;
2201                         break;
2202                 case ext_s:
2203                         tmp_exten[0] = 'i';
2204                         try_exten = ext_i;
2205                         break;
2206                 case ext_i:
2207                         try_exten = ext_notexists;
2208                         break;
2209                 default:
2210                         break;
2211                 }
2212         } while (try_exten != ext_notexists);
2213
2214         /* Drop the call if we don't have <exten>, s and i extensions */
2215         if (try_exten == ext_notexists) {
2216                 ast_log(LOG_NOTICE, "Dropping call because extensions '%s', 's' and 'i' doesn't exists in context [%s]\n", pvt->exten, pvt->context);
2217                 ast_mutex_unlock(&pvt->lock);
2218                 h323_clear_call(token, AST_CAUSE_UNALLOCATED);
2219                 return 0;
2220         } else if ((try_exten != ext_original) && (strcmp(pvt->exten, tmp_exten) != 0)) {
2221                 if (h323debug)
2222                         ast_log(LOG_DEBUG, "Going to extension %s@%s because %s@%s isn't exists\n", tmp_exten, pvt->context, pvt->exten, pvt->context);
2223                 strncpy(pvt->exten, tmp_exten, sizeof(pvt->exten));
2224         }
2225
2226         /* allocate a channel and tell asterisk about it */
2227         c = __oh323_new(pvt, AST_STATE_RINGING, pvt->cd.call_token);
2228
2229         /* And release when done */
2230         ast_mutex_unlock(&pvt->lock);
2231         if (!c) {
2232                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
2233                 return 0;
2234         }
2235         return 1;
2236 }
2237
2238 /**
2239  * Call-back function to establish an outgoing H.323 call
2240  *
2241  * Returns 1 on success
2242  */
2243 static int setup_outgoing_call(call_details_t *cd)
2244 {
2245         /* Use argument here or free it immediately */
2246         cleanup_call_details(cd);
2247
2248         return 1;
2249 }
2250
2251 /**
2252   *  Call-back function to signal asterisk that the channel is ringing
2253   *  Returns nothing
2254   */
2255 static void chan_ringing(unsigned call_reference, const char *token)
2256 {
2257         struct oh323_pvt *pvt;
2258
2259         if (h323debug)
2260                 ast_log(LOG_DEBUG, "Ringing on %s\n", token);
2261
2262         pvt = find_call_locked(call_reference, token);
2263         if (!pvt) {
2264                 ast_log(LOG_ERROR, "Something is wrong: ringing\n");
2265                 return;
2266         }
2267         if (!pvt->owner) {
2268                 ast_mutex_unlock(&pvt->lock);
2269                 ast_log(LOG_ERROR, "Channel has no owner\n");
2270                 return;
2271         }
2272         update_state(pvt, AST_STATE_RINGING, AST_CONTROL_RINGING);
2273         ast_mutex_unlock(&pvt->lock);
2274         return;
2275 }
2276
2277 /**
2278   * Call-back function to cleanup communication
2279   * Returns nothing,
2280   */
2281 static void cleanup_connection(unsigned call_reference, const char *call_token)
2282 {
2283         struct oh323_pvt *pvt;
2284
2285         if (h323debug)
2286                 ast_log(LOG_DEBUG, "Cleaning connection to %s\n", call_token);
2287
2288         while (1) {
2289                 pvt = find_call_locked(call_reference, call_token);
2290                 if (!pvt) {
2291                         if (h323debug)
2292                                 ast_log(LOG_DEBUG, "No connection for %s\n", call_token);
2293                         return;
2294                 }
2295                 if (!pvt->owner || !ast_channel_trylock(pvt->owner))
2296                         break;
2297 #if 1
2298 #ifdef DEBUG_THREADS
2299                 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]);
2300 #else
2301                 ast_log(LOG_NOTICE, "Avoiding H.323 destory deadlock on %s\n", call_token);
2302 #endif
2303 #endif
2304                 ast_mutex_unlock(&pvt->lock);
2305                 usleep(1);
2306         }
2307         if (pvt->rtp) {
2308                 /* Immediately stop RTP */
2309                 ast_rtp_destroy(pvt->rtp);
2310                 pvt->rtp = NULL;
2311         }
2312         /* Free dsp used for in-band DTMF detection */
2313         if (pvt->vad) {
2314                 ast_dsp_free(pvt->vad);
2315                 pvt->vad = NULL;
2316         }
2317         cleanup_call_details(&pvt->cd);
2318         pvt->alreadygone = 1;
2319         /* Send hangup */
2320         if (pvt->owner) {
2321                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2322                 ast_queue_hangup(pvt->owner);
2323                 ast_channel_unlock(pvt->owner);
2324         }
2325         ast_mutex_unlock(&pvt->lock);
2326         if (h323debug)
2327                 ast_log(LOG_DEBUG, "Connection to %s cleaned\n", call_token);
2328         return;
2329 }
2330
2331 static void hangup_connection(unsigned int call_reference, const char *token, int cause)
2332 {
2333         struct oh323_pvt *pvt;
2334
2335         if (h323debug) {
2336                 ast_log(LOG_DEBUG, "Hanging up connection to %s with cause %d\n", token, cause);
2337         }
2338
2339         pvt = find_call_locked(call_reference, token);
2340         if (!pvt) {
2341                 if (h323debug) {
2342                         ast_log(LOG_DEBUG, "Connection to %s already cleared\n", token);
2343                 }
2344                 return;
2345         }
2346         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
2347                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2348                 pvt->owner->hangupcause = pvt->hangupcause = cause;
2349                 ast_queue_hangup(pvt->owner);
2350                 ast_channel_unlock(pvt->owner);
2351         }
2352         else {
2353                 pvt->needhangup = 1;
2354                 pvt->hangupcause = cause;
2355                 if (h323debug)
2356                         ast_log(LOG_DEBUG, "Hangup for %s is pending\n", token);
2357         }
2358         ast_mutex_unlock(&pvt->lock);
2359 }
2360
2361 static void set_dtmf_payload(unsigned call_reference, const char *token, int payload)
2362 {
2363         struct oh323_pvt *pvt;
2364
2365         if (h323debug)
2366                 ast_log(LOG_DEBUG, "Setting DTMF payload to %d on %s\n", payload, token);
2367
2368         pvt = find_call_locked(call_reference, token);
2369         if (!pvt) {
2370                 return;
2371         }
2372         if (pvt->rtp) {
2373                 ast_rtp_set_rtpmap_type(pvt->rtp, payload, "audio", "telephone-event", 0);
2374         }
2375         pvt->dtmf_pt = payload;
2376         ast_mutex_unlock(&pvt->lock);
2377         if (h323debug)
2378                 ast_log(LOG_DEBUG, "DTMF payload on %s set to %d\n", token, payload);
2379 }
2380
2381 static void set_peer_capabilities(unsigned call_reference, const char *token, int capabilities, struct ast_codec_pref *prefs)
2382 {
2383         struct oh323_pvt *pvt;
2384
2385         if (h323debug)
2386                 ast_log(LOG_DEBUG, "Got remote capabilities from connection %s\n", token);
2387
2388         pvt = find_call_locked(call_reference, token);
2389         if (!pvt)
2390                 return;
2391         pvt->peercapability = capabilities;
2392         pvt->jointcapability = pvt->options.capability & capabilities;
2393         if (prefs) {
2394                 memcpy(&pvt->peer_prefs, prefs, sizeof(pvt->peer_prefs));
2395                 if (h323debug) {
2396                         int i;
2397                         for (i = 0; i < 32; ++i) {
2398                                 ast_log(LOG_DEBUG, "prefs[%d]=%s:%d\n", i, (prefs->order[i] ? ast_getformatname(1 << (prefs->order[i]-1)) : "<none>"), prefs->framing[i]);
2399                         }
2400                 }
2401                 if (pvt->rtp)
2402                         ast_rtp_codec_setpref(pvt->rtp, &pvt->peer_prefs);
2403         }
2404         ast_mutex_unlock(&pvt->lock);
2405 }
2406
2407 static void set_local_capabilities(unsigned call_reference, const char *token)
2408 {
2409         struct oh323_pvt *pvt;
2410         int capability, dtmfmode, pref_codec;
2411         struct ast_codec_pref prefs;
2412
2413         if (h323debug)
2414                 ast_log(LOG_DEBUG, "Setting capabilities for connection %s\n", token);
2415
2416         pvt = find_call_locked(call_reference, token);
2417         if (!pvt)
2418                 return;
2419         capability = (pvt->jointcapability) ? pvt->jointcapability : pvt->options.capability;
2420         dtmfmode = pvt->options.dtmfmode;
2421         prefs = pvt->options.prefs;
2422         pref_codec = pvt->pref_codec;
2423         ast_mutex_unlock(&pvt->lock);
2424         h323_set_capabilities(token, capability, dtmfmode, &prefs, pref_codec);
2425
2426         if (h323debug)
2427                 ast_log(LOG_DEBUG, "Capabilities for connection %s is set\n", token);
2428 }
2429
2430 static void *do_monitor(void *data)
2431 {
2432         int res;
2433         int reloading;
2434         struct oh323_pvt *oh323 = NULL;
2435
2436         for(;;) {
2437                 /* Check for a reload request */
2438                 ast_mutex_lock(&h323_reload_lock);
2439                 reloading = h323_reloading;
2440                 h323_reloading = 0;
2441                 ast_mutex_unlock(&h323_reload_lock);
2442                 if (reloading) {
2443                         if (option_verbose > 0) {
2444                                 ast_verbose(VERBOSE_PREFIX_1 "Reloading H.323\n");
2445                         }
2446                         h323_do_reload();
2447                 }
2448                 /* Check for interfaces needing to be killed */
2449                 ast_mutex_lock(&iflock);
2450 #if 1
2451                 do {
2452                         for (oh323 = iflist; oh323; oh323 = oh323->next) {
2453                                 if (!ast_mutex_trylock(&oh323->lock)) {
2454                                         if (oh323->needdestroy) {
2455                                                 __oh323_destroy(oh323);
2456                                                 break;
2457                                         }
2458                                         ast_mutex_unlock(&oh323->lock);
2459                                 }
2460                         }
2461                 } while (/*oh323*/ 0);
2462 #else
2463 restartsearch:
2464                 oh323 = iflist;
2465                 while(oh323) {
2466                         if (!ast_mutex_trylock(&oh323->lock)) {
2467                                 if (oh323->needdestroy) {
2468                                         __oh323_destroy(oh323);
2469                                         goto restartsearch;
2470                                 }
2471                                 ast_mutex_unlock(&oh323->lock);
2472                                 oh323 = oh323->next;
2473                         }
2474                 }
2475 #endif
2476                 ast_mutex_unlock(&iflock);
2477                 pthread_testcancel();
2478                 /* Wait for sched or io */
2479                 res = ast_sched_wait(sched);
2480                 if ((res < 0) || (res > 1000)) {
2481                         res = 1000;
2482                 }
2483                 /* Do not wait if some channel(s) is destroyed, probably, more available too */
2484                 if (oh323)
2485                         res = 1;
2486                 res = ast_io_wait(io, res);
2487                 pthread_testcancel();
2488                 ast_mutex_lock(&monlock);
2489                 if (res >= 0) {
2490                         ast_sched_runq(sched);
2491                 }
2492                 ast_mutex_unlock(&monlock);
2493         }
2494         /* Never reached */
2495         return NULL;
2496 }
2497
2498 static int restart_monitor(void)
2499 {
2500         pthread_attr_t attr;
2501         /* If we're supposed to be stopped -- stay stopped */
2502         if (ast_mutex_lock(&monlock)) {
2503                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
2504                 return -1;
2505         }
2506         if (monitor_thread == AST_PTHREADT_STOP) {
2507                 ast_mutex_unlock(&monlock);
2508                 return 0;
2509         }
2510         if (monitor_thread == pthread_self()) {
2511                 ast_mutex_unlock(&monlock);
2512                 ast_log(LOG_WARNING, "Cannot kill myself\n");
2513                 return -1;
2514         }
2515         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
2516                 /* Wake up the thread */
2517                 pthread_kill(monitor_thread, SIGURG);
2518         } else {
2519                 pthread_attr_init(&attr);
2520                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2521                 /* Start a new monitor */
2522                 if (ast_pthread_create(&monitor_thread, &attr, do_monitor, NULL) < 0) {
2523                         monitor_thread = AST_PTHREADT_NULL;
2524                         ast_mutex_unlock(&monlock);
2525                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
2526                         return -1;
2527                 }
2528         }
2529         ast_mutex_unlock(&monlock);
2530         return 0;
2531 }
2532
2533 static int h323_do_trace(int fd, int argc, char *argv[])
2534 {
2535         if (argc != 3) {
2536                 return RESULT_SHOWUSAGE;
2537         }
2538         h323_debug(1, atoi(argv[2]));
2539         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
2540         return RESULT_SUCCESS;
2541 }
2542
2543 static int h323_no_trace(int fd, int argc, char *argv[])
2544 {
2545         if (argc != 3) {
2546                 return RESULT_SHOWUSAGE;
2547         }
2548         h323_debug(0,0);
2549         ast_cli(fd, "H.323 trace disabled\n");
2550         return RESULT_SUCCESS;
2551 }
2552
2553 static int h323_do_debug(int fd, int argc, char *argv[])
2554 {
2555         if (argc != 2) {
2556                 return RESULT_SHOWUSAGE;
2557         }
2558         h323debug = 1;
2559         ast_cli(fd, "H.323 debug enabled\n");
2560         return RESULT_SUCCESS;
2561 }
2562
2563 static int h323_no_debug(int fd, int argc, char *argv[])
2564 {
2565         if (argc != 3) {
2566                 return RESULT_SHOWUSAGE;
2567         }
2568         h323debug = 0;
2569         ast_cli(fd, "H.323 debug disabled\n");
2570         return RESULT_SUCCESS;
2571 }
2572
2573 static int h323_gk_cycle(int fd, int argc, char *argv[])
2574 {
2575         if (argc != 3) {
2576                 return RESULT_SHOWUSAGE;
2577         }
2578         h323_gk_urq();
2579
2580         /* Possibly register with a GK */
2581         if (!gatekeeper_disable) {
2582                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
2583                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
2584                 }
2585         }
2586         return RESULT_SUCCESS;
2587 }
2588
2589 static int h323_ep_hangup(int fd, int argc, char *argv[])
2590 {
2591         if (argc != 3) {
2592                 return RESULT_SHOWUSAGE;
2593         }
2594         if (h323_soft_hangup(argv[2])) {
2595                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
2596         } else {
2597                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
2598         }
2599         return RESULT_SUCCESS;
2600 }
2601
2602 static int h323_tokens_show(int fd, int argc, char *argv[])
2603 {
2604         if (argc != 3) {
2605                 return RESULT_SHOWUSAGE;
2606         }
2607         h323_show_tokens();
2608         return RESULT_SUCCESS;
2609 }
2610
2611 static char trace_usage[] =
2612 "Usage: h.323 trace <level num>\n"
2613 "       Enables H.323 stack tracing for debugging purposes\n";
2614
2615 static char no_trace_usage[] =
2616 "Usage: h.323 no trace\n"
2617 "       Disables H.323 stack tracing for debugging purposes\n";
2618
2619 static char debug_usage[] =
2620 "Usage: h.323 debug\n"
2621 "       Enables H.323 debug output\n";
2622
2623 static char no_debug_usage[] =
2624 "Usage: h.323 no debug\n"
2625 "       Disables H.323 debug output\n";
2626
2627 static char show_cycle_usage[] =
2628 "Usage: h.323 gk cycle\n"
2629 "       Manually re-register with the Gatekeper (Currently Disabled)\n";
2630
2631 static char show_hangup_usage[] =
2632 "Usage: h.323 hangup <token>\n"
2633 "       Manually try to hang up call identified by <token>\n";
2634
2635 static char show_tokens_usage[] =
2636 "Usage: h.323 show tokens\n"
2637 "       Print out all active call tokens\n";
2638
2639 static char h323_reload_usage[] =
2640 "Usage: h323 reload\n"
2641 "       Reloads H.323 configuration from h323.conf\n";
2642
2643 static struct ast_cli_entry cli_h323[] = {
2644         { { "h.323", "trace", NULL },
2645         h323_do_trace, "Enable H.323 Stack Tracing",
2646         trace_usage },
2647
2648         { { "h.323", "no", "trace", NULL },
2649         h323_no_trace, "Disable H.323 Stack Tracing",
2650         no_trace_usage },
2651
2652         { { "h.323", "debug", NULL },
2653         h323_do_debug, "Enable H.323 debug",
2654         debug_usage },
2655
2656         { { "h.323", "no", "debug", NULL },
2657         h323_no_debug, "Disable H.323 debug",
2658         no_debug_usage },
2659
2660         { { "h.323", "gk", "cycle", NULL },
2661         h323_gk_cycle, "Manually re-register with the Gatekeper",
2662         show_cycle_usage },
2663
2664         { { "h.323", "hangup", NULL },
2665         h323_ep_hangup, "Manually try to hang up a call",
2666         show_hangup_usage },
2667
2668         { { "h.323", "show", "tokens", NULL },
2669         h323_tokens_show, "Show all active call tokens",
2670         show_tokens_usage },
2671 };
2672
2673 static int reload_config(int is_reload)
2674 {
2675         int format;
2676         struct ast_config *cfg, *ucfg;
2677         struct ast_variable *v;
2678         struct oh323_peer *peer = NULL;
2679         struct oh323_user *user = NULL;
2680         struct oh323_alias *alias = NULL;
2681         struct ast_hostent ahp; struct hostent *hp;
2682         char *cat;
2683         char *utype;
2684         int is_user, is_peer, is_alias;
2685         char _gatekeeper[100];
2686         int gk_discover, gk_disable, gk_changed;
2687
2688         cfg = ast_config_load(config);
2689
2690         /* We *must* have a config file otherwise stop immediately */
2691         if (!cfg) {
2692                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
2693                 return 1;
2694         }
2695
2696         /* fire up the H.323 Endpoint */
2697         if (!h323_end_point_exist()) {
2698                 h323_end_point_create();
2699         }
2700         strncpy(_gatekeeper, gatekeeper, sizeof(_gatekeeper));
2701         gk_discover = gatekeeper_discover;
2702         gk_disable = gatekeeper_disable;
2703         memset(&bindaddr, 0, sizeof(bindaddr));
2704         memset(&global_options, 0, sizeof(global_options));
2705         global_options.fastStart = 1;
2706         global_options.h245Tunneling = 1;
2707         global_options.dtmfcodec = 101;
2708         global_options.dtmfmode = H323_DTMF_RFC2833;
2709         global_options.capability = GLOBAL_CAPABILITY;
2710         global_options.bridge = 1;              /* Do native bridging by default */
2711         strncpy(default_context, "default", sizeof(default_context) - 1);
2712         h323_signalling_port = 1720;
2713         gatekeeper_disable = 1;
2714         gatekeeper_discover = 0;
2715         gkroute = 0;
2716         userbyalias = 1;
2717         acceptAnonymous = 1;
2718         tos = 0;
2719
2720         /* Copy the default jb config over global_jbconf */
2721         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
2722
2723         /* Load configuration from users.conf */
2724         ucfg = ast_config_load("users.conf");
2725         if (ucfg) {
2726                 struct ast_variable *gen;
2727                 int genhas_h323;
2728                 char *has_h323;
2729
2730                 genhas_h323 = ast_true(ast_variable_retrieve(ucfg, "general", "hash323"));
2731                 gen = ast_variable_browse(ucfg, "general");
2732                 for (cat = ast_category_browse(ucfg, NULL); cat; cat = ast_category_browse(ucfg, cat)) {
2733                         if (strcasecmp(cat, "general")) {
2734                                 has_h323 = ast_variable_retrieve(ucfg, cat, "hash323");
2735                                 if (ast_true(has_h323) || (!has_h323 && genhas_h323)) {
2736                                         user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
2737                                         if (user) {
2738                                                 ASTOBJ_CONTAINER_LINK(&userl, user);
2739                                                 ASTOBJ_UNREF(user, oh323_destroy_user);
2740                                         }
2741                                 }
2742                         }
2743                 }
2744                 ast_config_destroy(ucfg);
2745         }
2746
2747         for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
2748                 /* handle jb conf */
2749                 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
2750                         continue;
2751                 /* Create the interface list */
2752                 if (!strcasecmp(v->name, "port")) {
2753                         h323_signalling_port = (int)strtol(v->value, NULL, 10);
2754                 } else if (!strcasecmp(v->name, "bindaddr")) {
2755                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
2756                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
2757                         } else {
2758                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
2759                         }
2760                 } else if (!strcasecmp(v->name, "tos")) {
2761                         if (sscanf(v->value, "%d", &format)) {
2762                                 tos = format & 0xff;
2763                         } else if (!strcasecmp(v->value, "lowdelay")) {
2764                                 tos = IPTOS_LOWDELAY;
2765                         } else if (!strcasecmp(v->value, "throughput")) {
2766                                 tos = IPTOS_THROUGHPUT;
2767                         } else if (!strcasecmp(v->value, "reliability")) {
2768                                 tos = IPTOS_RELIABILITY;
2769                         } else if (!strcasecmp(v->value, "mincost")) {
2770                                 tos = IPTOS_MINCOST;
2771                         } else if (!strcasecmp(v->value, "none")) {
2772                                 tos = 0;
2773                         } else {
2774                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
2775                         }
2776                 } else if (!strcasecmp(v->name, "gatekeeper")) {
2777                         if (!strcasecmp(v->value, "DISABLE")) {
2778                                 gatekeeper_disable = 1;
2779                         } else if (!strcasecmp(v->value, "DISCOVER")) {
2780                                 gatekeeper_disable = 0;
2781                                 gatekeeper_discover = 1;
2782                         } else {
2783                                 gatekeeper_disable = 0;
2784                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper) - 1);
2785                         }
2786                 } else if (!strcasecmp(v->name, "secret")) {
2787                         strncpy(secret, v->value, sizeof(secret) - 1);
2788                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
2789                         gkroute = ast_true(v->value);
2790                 } else if (!strcasecmp(v->name, "context")) {
2791                         strncpy(default_context, v->value, sizeof(default_context) - 1);
2792                         ast_verbose(VERBOSE_PREFIX_2 "Setting default context to %s\n", default_context);
2793                 } else if (!strcasecmp(v->name, "UserByAlias")) {
2794                         userbyalias = ast_true(v->value);
2795                 } else if (!strcasecmp(v->name, "AcceptAnonymous")) {
2796                         acceptAnonymous = ast_true(v->value);
2797                 } else if (!update_common_options(v, &global_options)) {
2798                         /* dummy */
2799                 }
2800         }
2801
2802         for (cat = ast_category_browse(cfg, NULL); cat; cat = ast_category_browse(cfg, cat)) {
2803                 if (strcasecmp(cat, "general")) {
2804                         utype = ast_variable_retrieve(cfg, cat, "type");
2805                         if (utype) {
2806                                 is_user = is_peer = is_alias = 0;
2807                                 if (!strcasecmp(utype, "user"))
2808                                         is_user = 1;
2809                                 else if (!strcasecmp(utype, "peer"))
2810                                         is_peer = 1;
2811                                 else if (!strcasecmp(utype, "friend"))
2812                                         is_user = is_peer = 1;
2813                                 else if (!strcasecmp(utype, "h323") || !strcasecmp(utype, "alias"))
2814                                         is_alias = 1;
2815                                 else {
2816                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
2817                                         continue;
2818                                 }
2819                                 if (is_user) {
2820                                         user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
2821                                         if (user) {
2822                                                 ASTOBJ_CONTAINER_LINK(&userl, user);
2823                                                 ASTOBJ_UNREF(user, oh323_destroy_user);
2824                                         }
2825                                 }
2826                                 if (is_peer) {
2827                                         peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
2828                                         if (peer) {
2829                                                 ASTOBJ_CONTAINER_LINK(&peerl, peer);
2830                                                 ASTOBJ_UNREF(peer, oh323_destroy_peer);
2831                                         }
2832                                 }
2833                                 if (is_alias) {
2834                                         alias = build_alias(cat, ast_variable_browse(cfg, cat), NULL, 0);
2835                                         if (alias) {
2836                                                 ASTOBJ_CONTAINER_LINK(&aliasl, alias);
2837                                                 ASTOBJ_UNREF(alias, oh323_destroy_alias);
2838                                         }
2839                                 }
2840                         } else {
2841                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
2842                         }
2843                 }
2844         }
2845         ast_config_destroy(cfg);
2846
2847         /* Register our H.323 aliases if any*/
2848         ASTOBJ_CONTAINER_WRLOCK(&aliasl);
2849         ASTOBJ_CONTAINER_TRAVERSE(&aliasl, 1, do {
2850                 ASTOBJ_RDLOCK(iterator);
2851                 if (h323_set_alias(iterator)) {
2852                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
2853                         ASTOBJ_UNLOCK(iterator);
2854                         continue;
2855                 }
2856                 ASTOBJ_UNLOCK(iterator);
2857         } while (0) );
2858         ASTOBJ_CONTAINER_UNLOCK(&aliasl);
2859
2860         /* Don't touch GK if nothing changed because URQ will drop all existing calls */
2861         gk_changed = 0;
2862         if (gatekeeper_disable != gk_disable)
2863                 gk_changed = is_reload;
2864         else if(!gatekeeper_disable && (gatekeeper_discover != gk_discover))
2865                 gk_changed = is_reload;
2866         else if(!gatekeeper_disable && (strncmp(_gatekeeper, gatekeeper, sizeof(_gatekeeper)) != 0))
2867                 gk_changed = is_reload;
2868         if (gk_changed) {
2869                 if(!gk_disable)
2870                         h323_gk_urq();
2871                 if (!gatekeeper_disable) {
2872                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
2873                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
2874                                 gatekeeper_disable = 1;
2875                         }
2876                 }
2877         }
2878         return 0;
2879 }
2880
2881 static void delete_users(void)
2882 {
2883         int pruned = 0;
2884
2885         /* Delete all users */
2886         ASTOBJ_CONTAINER_WRLOCK(&userl);
2887         ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
2888                 ASTOBJ_RDLOCK(iterator);
2889                 ASTOBJ_MARK(iterator);
2890                 ++pruned;
2891                 ASTOBJ_UNLOCK(iterator);
2892         } while (0) );
2893         if (pruned) {
2894                 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, oh323_destroy_user);
2895         }
2896         ASTOBJ_CONTAINER_UNLOCK(&userl);
2897
2898         ASTOBJ_CONTAINER_WRLOCK(&peerl);
2899         ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
2900                 ASTOBJ_RDLOCK(iterator);
2901                 ASTOBJ_MARK(iterator);
2902                 ASTOBJ_UNLOCK(iterator);
2903         } while (0) );
2904         ASTOBJ_CONTAINER_UNLOCK(&peerl);
2905 }
2906
2907 static void delete_aliases(void)
2908 {
2909         int pruned = 0;
2910
2911         /* Delete all aliases */
2912         ASTOBJ_CONTAINER_WRLOCK(&aliasl);
2913         ASTOBJ_CONTAINER_TRAVERSE(&aliasl, 1, do {
2914                 ASTOBJ_RDLOCK(iterator);
2915                 ASTOBJ_MARK(iterator);
2916                 ++pruned;
2917                 ASTOBJ_UNLOCK(iterator);
2918         } while (0) );
2919         if (pruned) {
2920                 ASTOBJ_CONTAINER_PRUNE_MARKED(&aliasl, oh323_destroy_alias);
2921         }
2922         ASTOBJ_CONTAINER_UNLOCK(&aliasl);
2923 }
2924
2925 static void prune_peers(void)
2926 {
2927         /* Prune peers who still are supposed to be deleted */
2928         ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, oh323_destroy_peer);
2929 }
2930
2931 static int h323_reload(int fd, int argc, char *argv[])
2932 {
2933         ast_mutex_lock(&h323_reload_lock);
2934         if (h323_reloading) {
2935                 ast_verbose("Previous H.323 reload not yet done\n");
2936         } else {
2937                 h323_reloading = 1;
2938         }
2939         ast_mutex_unlock(&h323_reload_lock);
2940         restart_monitor();
2941         return 0;
2942 }
2943
2944 static int h323_do_reload(void)
2945 {
2946         delete_users();
2947         delete_aliases();
2948         prune_peers();
2949         reload_config(1);
2950         return 0;
2951 }
2952
2953 static int reload(void)
2954 {
2955         return h323_reload(0, 0, NULL);
2956 }
2957
2958 static struct ast_cli_entry cli_h323_reload =
2959         { { "h.323", "reload", NULL },
2960         h323_reload, "Reload H.323 configuration",
2961         h323_reload_usage
2962 };
2963
2964 static enum ast_rtp_get_result oh323_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
2965 {
2966         struct oh323_pvt *pvt;
2967         enum ast_rtp_get_result res = AST_RTP_GET_FAILED;
2968
2969         if (!(pvt = (struct oh323_pvt *)chan->tech_pvt))
2970                 return res;
2971
2972         ast_mutex_lock(&pvt->lock);
2973         if (pvt->rtp && pvt->options.bridge) {
2974                 *rtp = pvt->rtp;
2975                 res = AST_RTP_TRY_NATIVE;
2976         }
2977         ast_mutex_unlock(&pvt->lock);
2978
2979         return res;
2980 }
2981
2982 static enum ast_rtp_get_result oh323_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
2983 {
2984         return AST_RTP_GET_FAILED;
2985 }
2986
2987 static char *convertcap(int cap)
2988 {
2989         switch (cap) {
2990         case AST_FORMAT_G723_1:
2991                 return "G.723";
2992         case AST_FORMAT_GSM:
2993                 return "GSM";
2994         case AST_FORMAT_ULAW:
2995                 return "ULAW";
2996         case AST_FORMAT_ALAW:
2997                 return "ALAW";
2998         case AST_FORMAT_ADPCM:
2999                 return "G.728";
3000         case AST_FORMAT_G729A:
3001                 return "G.729";
3002         case AST_FORMAT_SPEEX:
3003                 return "SPEEX";
3004         case AST_FORMAT_ILBC:
3005                 return "ILBC";
3006         default:
3007                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
3008                 return NULL;
3009         }
3010 }
3011
3012 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
3013 {
3014         /* XXX Deal with Video */
3015         struct oh323_pvt *pvt;
3016         struct sockaddr_in them;
3017         struct sockaddr_in us;
3018         char *mode;
3019
3020         if (!rtp) {
3021                 return 0;
3022         }
3023
3024         mode = convertcap(chan->writeformat);
3025         pvt = (struct oh323_pvt *) chan->tech_pvt;
3026         if (!pvt) {
3027                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
3028                 return -1;
3029         }
3030         ast_rtp_get_peer(rtp, &them);
3031         ast_rtp_get_us(rtp, &us);
3032 #if 0   /* Native bridge still isn't ready */
3033         h323_native_bridge(pvt->cd.call_token, ast_inet_ntoa(them.sin_addr), mode);
3034 #endif
3035         return 0;
3036 }
3037
3038 static struct ast_rtp_protocol oh323_rtp = {
3039         .type = "H323",
3040         .get_rtp_info = oh323_get_rtp_peer,
3041         .get_vrtp_info = oh323_get_vrtp_peer,
3042         .set_rtp_peer = oh323_set_rtp_peer,
3043 };
3044
3045 static enum ast_module_load_result load_module(void)
3046 {
3047         int res;
3048
3049         h323debug = 0;
3050         sched = sched_context_create();
3051         if (!sched) {
3052                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
3053                 return AST_MODULE_LOAD_FAILURE;
3054         }
3055         io = io_context_create();
3056         if (!io) {
3057                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
3058                 return AST_MODULE_LOAD_FAILURE;
3059         }
3060         ast_cli_register(&cli_h323_reload);
3061         ASTOBJ_CONTAINER_INIT(&userl);
3062         ASTOBJ_CONTAINER_INIT(&peerl);
3063         ASTOBJ_CONTAINER_INIT(&aliasl);
3064         res = reload_config(0);
3065         if (res) {
3066                 ast_cli_unregister(&cli_h323_reload);
3067                 io_context_destroy(io);
3068                 sched_context_destroy(sched);
3069                 ASTOBJ_CONTAINER_DESTROY(&userl);
3070                 ASTOBJ_CONTAINER_DESTROY(&peerl);
3071                 ASTOBJ_CONTAINER_DESTROY(&aliasl);
3072                 return /*AST_MODULE_LOAD_DECLINE*/AST_MODULE_LOAD_FAILURE;
3073         } else {
3074                 /* Make sure we can register our channel type */
3075                 if (ast_channel_register(&oh323_tech)) {
3076                         ast_log(LOG_ERROR, "Unable to register channel class 'H323'\n");
3077                         ast_cli_unregister(&cli_h323_reload);
3078                         h323_end_process();
3079                         io_context_destroy(io);
3080                         sched_context_destroy(sched);
3081
3082                         ASTOBJ_CONTAINER_DESTROYALL(&userl, oh323_destroy_user);
3083                         ASTOBJ_CONTAINER_DESTROY(&userl);
3084                         ASTOBJ_CONTAINER_DESTROYALL(&peerl, oh323_destroy_peer);
3085                         ASTOBJ_CONTAINER_DESTROY(&peerl);
3086                         ASTOBJ_CONTAINER_DESTROYALL(&aliasl, oh323_destroy_alias);
3087                         ASTOBJ_CONTAINER_DESTROY(&aliasl);
3088
3089                         return AST_MODULE_LOAD_FAILURE;
3090                 }
3091                 ast_cli_register_multiple(cli_h323, sizeof(cli_h323) / sizeof(struct ast_cli_entry));
3092
3093                 ast_rtp_proto_register(&oh323_rtp);
3094
3095                 /* Register our callback functions */
3096                 h323_callback_register(setup_incoming_call,
3097                                                 setup_outgoing_call,
3098                                                 external_rtp_create,
3099                                                 setup_rtp_connection,
3100                                                 cleanup_connection,
3101                                                 chan_ringing,
3102                                                 connection_made,
3103                                                 receive_digit,
3104                                                 answer_call,
3105                                                 progress,
3106                                                 set_dtmf_payload,
3107                                                 hangup_connection,
3108                                                 set_local_capabilities,
3109                                                 set_peer_capabilities);
3110                 /* start the h.323 listener */
3111                 if (h323_start_listener(h323_signalling_port, bindaddr)) {
3112                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
3113                         ast_rtp_proto_unregister(&oh323_rtp);
3114                         ast_cli_unregister_multiple(cli_h323, sizeof(cli_h323) / sizeof(struct ast_cli_entry));
3115                         ast_cli_unregister(&cli_h323_reload);
3116                         h323_end_process();
3117                         io_context_destroy(io);
3118                         sched_context_destroy(sched);
3119
3120                         ASTOBJ_CONTAINER_DESTROYALL(&userl, oh323_destroy_user);
3121                         ASTOBJ_CONTAINER_DESTROY(&userl);
3122                         ASTOBJ_CONTAINER_DESTROYALL(&peerl, oh323_destroy_peer);
3123                         ASTOBJ_CONTAINER_DESTROY(&peerl);
3124                         ASTOBJ_CONTAINER_DESTROYALL(&aliasl, oh323_destroy_alias);
3125                         ASTOBJ_CONTAINER_DESTROY(&aliasl);
3126
3127                         return AST_MODULE_LOAD_FAILURE;
3128                 }
3129                 /* Possibly register with a GK */
3130                 if (!gatekeeper_disable) {
3131                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
3132                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
3133                                 gatekeeper_disable = 1;
3134                                 res = AST_MODULE_LOAD_SUCCESS;
3135                         }
3136                 }
3137                 /* And start the monitor for the first time */
3138                 restart_monitor();
3139         }
3140         return res;
3141 }
3142
3143 static int unload_module(void)
3144 {
3145         struct oh323_pvt *p, *pl;
3146
3147         /* unregister commands */
3148         ast_cli_unregister_multiple(cli_h323, sizeof(cli_h323) / sizeof(struct ast_cli_entry));
3149         ast_cli_unregister(&cli_h323_reload);
3150
3151         ast_channel_unregister(&oh323_tech);
3152         ast_rtp_proto_unregister(&oh323_rtp);
3153
3154         if (!ast_mutex_lock(&iflock)) {
3155                 /* hangup all interfaces if they have an owner */
3156                 p = iflist;
3157                 while(p) {
3158                         if (p->owner) {
3159                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
3160                         }
3161                         p = p->next;
3162                 }
3163                 iflist = NULL;
3164                 ast_mutex_unlock(&iflock);
3165         } else {
3166                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
3167                 return -1;
3168         }
3169         if (!ast_mutex_lock(&monlock)) {
3170                 if ((monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
3171                         /* this causes a seg, anyone know why? */
3172                         if (monitor_thread != pthread_self())
3173                                 pthread_cancel(monitor_thread);
3174                         pthread_kill(monitor_thread, SIGURG);
3175                         pthread_join(monitor_thread, NULL);
3176                 }
3177                 monitor_thread = AST_PTHREADT_STOP;
3178                 ast_mutex_unlock(&monlock);
3179         } else {
3180                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
3181                 return -1;
3182         }
3183         if (!ast_mutex_lock(&iflock)) {
3184                 /* destroy all the interfaces and free their memory */
3185                 p = iflist;
3186                 while(p) {
3187                         pl = p;
3188                         p = p->next;
3189                         /* free associated memory */
3190                         ast_mutex_destroy(&pl->lock);
3191                         free(pl);
3192                 }
3193                 iflist = NULL;
3194                 ast_mutex_unlock(&iflock);
3195         } else {
3196                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
3197                 return -1;
3198         }
3199         if (!gatekeeper_disable)
3200                 h323_gk_urq();
3201         h323_end_process();
3202         io_context_destroy(io);
3203         sched_context_destroy(sched);
3204
3205         ASTOBJ_CONTAINER_DESTROYALL(&userl, oh323_destroy_user);
3206         ASTOBJ_CONTAINER_DESTROY(&userl);
3207         ASTOBJ_CONTAINER_DESTROYALL(&peerl, oh323_destroy_peer);
3208         ASTOBJ_CONTAINER_DESTROY(&peerl);
3209         ASTOBJ_CONTAINER_DESTROYALL(&aliasl, oh323_destroy_alias);
3210         ASTOBJ_CONTAINER_DESTROY(&aliasl);
3211
3212         return 0;
3213 }
3214
3215 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "The NuFone Network's OpenH323 Channel Driver",
3216                 .load = load_module,
3217                 .unload = unload_module,
3218                 .reload = reload,
3219 );