DTMF mode is bitmask, not valued field
[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 static int update_common_options(struct ast_variable *v, struct call_options *options)
1248 {
1249         int tmp;
1250
1251         if (!strcasecmp(v->name, "allow")) {
1252                 ast_parse_allow_disallow(&options->prefs, &options->capability, v->value, 1);
1253         } else if (!strcasecmp(v->name, "disallow")) {
1254                 ast_parse_allow_disallow(&options->prefs, &options->capability, v->value, 0);
1255         } else if (!strcasecmp(v->name, "dtmfmode")) {
1256                 if (!strcasecmp(v->value, "inband")) {
1257                         options->dtmfmode |= H323_DTMF_INBAND;
1258                 } else if (!strcasecmp(v->value, "rfc2833")) {
1259                         options->dtmfmode |= H323_DTMF_RFC2833;
1260                 } else {
1261                         ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1262                         options->dtmfmode |= H323_DTMF_RFC2833;
1263                 }
1264         } else if (!strcasecmp(v->name, "dtmfcodec")) {
1265                 tmp = atoi(v->value);
1266                 if (tmp < 96)
1267                         ast_log(LOG_WARNING, "Invalid %s value %s at line %d\n", v->name, v->value, v->lineno);
1268                 else
1269                         options->dtmfcodec = tmp;
1270         } else if (!strcasecmp(v->name, "bridge")) {
1271                 options->bridge = ast_true(v->value);
1272         } else if (!strcasecmp(v->name, "nat")) {
1273                 options->nat = ast_true(v->value);
1274         } else if (!strcasecmp(v->name, "fastStart")) {
1275                 options->fastStart = ast_true(v->value);
1276         } else if (!strcasecmp(v->name, "h245Tunneling")) {
1277                 options->h245Tunneling = ast_true(v->value);
1278         } else if (!strcasecmp(v->name, "silenceSuppression")) {
1279                 options->silenceSuppression = ast_true(v->value);
1280         } else if (!strcasecmp(v->name, "progress_setup")) {
1281                 tmp = atoi(v->value);
1282                 if ((tmp != 0) && (tmp != 1) && (tmp != 3) && (tmp != 8)) {
1283                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d, assuming 0\n", v->value, v->name, v->lineno);
1284                         tmp = 0;
1285                 }
1286                 options->progress_setup = tmp;
1287         } else if (!strcasecmp(v->name, "progress_alert")) {
1288                 tmp = atoi(v->value);
1289                 if ((tmp != 0) && (tmp != 1) && (tmp != 8)) {
1290                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d, assuming 0\n", v->value, v->name, v->lineno);
1291                         tmp = 0;
1292                 }
1293                 options->progress_alert = tmp;
1294         } else if (!strcasecmp(v->name, "progress_audio")) {
1295                 options->progress_audio = ast_true(v->value);
1296         } else if (!strcasecmp(v->name, "callerid")) {
1297                 ast_callerid_split(v->value, options->cid_name, sizeof(options->cid_name), options->cid_num, sizeof(options->cid_num));
1298         } else if (!strcasecmp(v->name, "fullname")) {
1299                 ast_copy_string(options->cid_name, v->value, sizeof(options->cid_name));
1300         } else if (!strcasecmp(v->name, "cid_number")) {
1301                 ast_copy_string(options->cid_num, v->value, sizeof(options->cid_num));
1302         } else if (!strcasecmp(v->name, "tunneling")) {
1303                 if (!strcasecmp(v->value, "none"))
1304                         options->tunnelOptions = 0;
1305                 else if (!strcasecmp(v->value, "cisco"))
1306                         options->tunnelOptions |= H323_TUNNEL_CISCO;
1307                 else if (!strcasecmp(v->value, "qsig"))
1308                         options->tunnelOptions |= H323_TUNNEL_QSIG;
1309                 else
1310                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d\n", v->value, v->name, v->lineno);
1311         } else
1312                 return 1;
1313
1314         return 0;
1315 }
1316
1317 static struct oh323_user *build_user(char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
1318 {
1319         struct oh323_user *user;
1320         struct ast_ha *oldha;
1321         int found = 0;
1322         int format;
1323
1324         user = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&userl, name, name, 0, 0, strcmp);
1325
1326         if (user)
1327                 found++;
1328         else {
1329                 if (!(user = (struct oh323_user *)calloc(1, sizeof(*user))))
1330                         return NULL;
1331                 ASTOBJ_INIT(user);
1332         }
1333         oldha = user->ha;
1334         user->ha = (struct ast_ha *)NULL;
1335         memcpy(&user->options, &global_options, sizeof(user->options));
1336         user->options.dtmfmode = 0;
1337         /* Set default context */
1338         strncpy(user->context, default_context, sizeof(user->context) - 1);
1339         if (user && !found)
1340                 strncpy(user->name, name, sizeof(user->name) - 1);
1341
1342 #if 0 /* XXX Port channel variables functionality from chan_sip XXX */
1343         if (user->chanvars) {
1344                 ast_variables_destroy(user->chanvars);
1345                 user->chanvars = NULL;
1346         }
1347 #endif
1348
1349         for (; v || ((v = alt) && !(alt = NULL)); v = v->next) {
1350                 if (!update_common_options(v, &user->options))
1351                         continue;
1352                 if (!strcasecmp(v->name, "context")) {
1353                         strncpy(user->context, v->value, sizeof(user->context) - 1);
1354                 } else if (!strcasecmp(v->name, "secret")) {
1355                         strncpy(user->secret, v->value, sizeof(user->secret) - 1);
1356                 } else if (!strcasecmp(v->name, "accountcode")) {
1357                         strncpy(user->accountcode, v->value, sizeof(user->accountcode) - 1);
1358                 } else if (!strcasecmp(v->name, "host")) {
1359                         if (!strcasecmp(v->value, "dynamic")) {
1360                                 ast_log(LOG_ERROR, "A dynamic host on a type=user does not make any sense\n");
1361                                 ASTOBJ_UNREF(user, oh323_destroy_user);
1362                                 return NULL;
1363                         } else if (ast_get_ip(&user->addr, v->value)) {
1364                                 ASTOBJ_UNREF(user, oh323_destroy_user);
1365                                 return NULL;
1366                         }
1367                         /* Let us know we need to use ip authentication */
1368                         user->host = 1;
1369                 } else if (!strcasecmp(v->name, "amaflags")) {
1370                         format = ast_cdr_amaflags2int(v->value);
1371                         if (format < 0) {
1372                                 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
1373                         } else {
1374                                 user->amaflags = format;
1375                         }
1376                 } else if (!strcasecmp(v->name, "permit") ||
1377                                         !strcasecmp(v->name, "deny")) {
1378                         user->ha = ast_append_ha(v->name, v->value, user->ha);
1379                 }
1380         }
1381         if (!user->options.dtmfmode)
1382                 user->options.dtmfmode = global_options.dtmfmode;
1383         ASTOBJ_UNMARK(user);
1384         ast_free_ha(oldha);
1385         return user;
1386 }
1387
1388 static struct oh323_user *realtime_user(const call_details_t *cd)
1389 {
1390         struct ast_variable *var, *tmp;
1391         struct oh323_user *user;
1392         char *username;
1393
1394         if (userbyalias)
1395                 var = ast_load_realtime("h323", "name", username = cd->call_source_aliases, NULL);
1396         else {
1397                 username = (char *)NULL;
1398                 var = ast_load_realtime("h323", "host", cd->sourceIp, NULL);
1399         }
1400
1401         if (!var)
1402                 return NULL;
1403
1404         for (tmp = var; tmp; tmp = tmp->next) {
1405                 if (!strcasecmp(tmp->name, "type") &&
1406                 !(!strcasecmp(tmp->value, "user") || !strcasecmp(tmp->value, "friend"))) {
1407                         ast_variables_destroy(var);
1408                         return NULL;
1409                 } else if (!username && !strcasecmp(tmp->name, "name"))
1410                         username = tmp->value;
1411         }
1412
1413         if (!username) {
1414                 ast_log(LOG_WARNING, "Cannot determine user name for IP address %s\n", cd->sourceIp);
1415                 ast_variables_destroy(var);
1416                 return NULL;
1417         }
1418
1419         user = build_user(username, var, NULL, 1);
1420
1421         ast_variables_destroy(var);
1422
1423         return user;
1424 }
1425
1426 static struct oh323_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
1427 {
1428         struct oh323_peer *peer;
1429         struct ast_ha *oldha;
1430         int found = 0;
1431
1432         peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
1433
1434         if (peer)
1435                 found++;
1436         else {
1437                 if (!(peer = (struct oh323_peer*)calloc(1, sizeof(*peer))))
1438                         return NULL;
1439                 ASTOBJ_INIT(peer);
1440         }
1441         oldha = peer->ha;
1442         peer->ha = NULL;
1443         memcpy(&peer->options, &global_options, sizeof(peer->options));
1444         peer->options.dtmfmode = 0;
1445         peer->addr.sin_port = htons(h323_signalling_port);
1446         peer->addr.sin_family = AF_INET;
1447         if (!found && name)
1448                 strncpy(peer->name, name, sizeof(peer->name) - 1);
1449
1450 #if 0 /* XXX Port channel variables functionality from chan_sip XXX */
1451         if (peer->chanvars) {
1452                 ast_variables_destroy(peer->chanvars);
1453                 peer->chanvars = NULL;
1454         }
1455 #endif
1456         /* Default settings for mailbox */
1457         peer->mailbox[0] = '\0';
1458
1459         for (; v || ((v = alt) && !(alt = NULL)); v = v->next) {
1460                 if (!update_common_options(v, &peer->options))
1461                         continue;
1462                 if (!strcasecmp(v->name, "host")) {
1463                         if (!strcasecmp(v->value, "dynamic")) {
1464                                 ast_log(LOG_ERROR, "Dynamic host configuration not implemented.\n");
1465                                 ASTOBJ_UNREF(peer, oh323_destroy_peer);
1466                                 return NULL;
1467                         }
1468                         if (ast_get_ip(&peer->addr, v->value)) {
1469                                 ast_log(LOG_ERROR, "Could not determine IP for %s\n", v->value);
1470                                 ASTOBJ_UNREF(peer, oh323_destroy_peer);
1471                                 return NULL;
1472                         }
1473                 } else if (!strcasecmp(v->name, "port")) {
1474                         peer->addr.sin_port = htons(atoi(v->value));
1475                 } else if (!strcasecmp(v->name, "permit") ||
1476                                         !strcasecmp(v->name, "deny")) {
1477                         peer->ha = ast_append_ha(v->name, v->value, peer->ha);
1478                 } else if (!strcasecmp(v->name, "mailbox")) {
1479                         ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
1480                 }
1481         }
1482         if (!peer->options.dtmfmode)
1483                 peer->options.dtmfmode = global_options.dtmfmode;
1484         ASTOBJ_UNMARK(peer);
1485         ast_free_ha(oldha);
1486         return peer;
1487 }
1488
1489 static struct oh323_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1490 {
1491         struct oh323_peer *peer;
1492         struct ast_variable *var;
1493         struct ast_variable *tmp;
1494         const char *addr;
1495
1496         /* First check on peer name */
1497         if (peername)
1498                 var = ast_load_realtime("h323", "name", peername, addr = NULL);
1499         else if (sin) /* Then check on IP address for dynamic peers */
1500                 var = ast_load_realtime("h323", "host", addr = ast_inet_ntoa(sin->sin_addr), NULL);
1501         else
1502                 return NULL;
1503
1504         if (!var)
1505                 return NULL;
1506
1507         for (tmp = var; tmp; tmp = tmp->next) {
1508                 /* If this is type=user, then skip this object. */
1509                 if (!strcasecmp(tmp->name, "type") &&
1510                                 !(!strcasecmp(tmp->value, "peer") || !strcasecmp(tmp->value, "friend"))) {
1511                         ast_variables_destroy(var);
1512                         return NULL;
1513                 } else if (!peername && !strcasecmp(tmp->name, "name")) {
1514                         peername = tmp->value;
1515                 }
1516         }
1517
1518         if (!peername) {        /* Did not find peer in realtime */
1519                 ast_log(LOG_WARNING, "Cannot determine peer name for IP address %s\n", addr);
1520                 ast_variables_destroy(var);
1521                 return NULL;
1522         }
1523
1524         /* Peer found in realtime, now build it in memory */
1525         peer = build_peer(peername, var, NULL, 1);
1526
1527         ast_variables_destroy(var);
1528
1529         return peer;
1530 }
1531
1532 static int oh323_addrcmp_str(struct in_addr inaddr, char *addr)
1533 {
1534         return strcmp(ast_inet_ntoa(inaddr), addr);
1535 }
1536
1537 static struct oh323_user *find_user(const call_details_t *cd, int realtime)
1538 {
1539         struct oh323_user *u;
1540
1541         if (userbyalias)
1542                 u = ASTOBJ_CONTAINER_FIND(&userl, cd->call_source_aliases);
1543         else
1544                 u = ASTOBJ_CONTAINER_FIND_FULL(&userl, cd->sourceIp, addr.sin_addr, 0, 0, oh323_addrcmp_str);
1545
1546         if (!u && realtime)
1547                 u = realtime_user(cd);
1548
1549         if (!u && h323debug)
1550                 ast_log(LOG_DEBUG, "Could not find user by name %s or address %s\n", cd->call_source_aliases, cd->sourceIp);
1551
1552         return u;
1553 }
1554
1555 static int oh323_addrcmp(struct sockaddr_in addr, struct sockaddr_in *sin)
1556 {
1557         int res;
1558
1559         if (!sin)
1560                 res = -1;
1561         else
1562                 res = inaddrcmp(&addr , sin);
1563
1564         return res;
1565 }
1566
1567 static struct oh323_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1568 {
1569         struct oh323_peer *p;
1570
1571         if (peer)
1572                 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
1573         else
1574                 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, addr, 0, 0, oh323_addrcmp);
1575
1576         if (!p && realtime)
1577                 p = realtime_peer(peer, sin);
1578
1579         if (!p && h323debug)
1580                 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>"));
1581
1582         return p;
1583 }
1584
1585 static int create_addr(struct oh323_pvt *pvt, char *opeer)
1586 {
1587         struct hostent *hp;
1588         struct ast_hostent ahp;
1589         struct oh323_peer *p;
1590         int portno;
1591         int found = 0;
1592         char *port;
1593         char *hostn;
1594         char peer[256] = "";
1595
1596         strncpy(peer, opeer, sizeof(peer) - 1);
1597         port = strchr(peer, ':');
1598         if (port) {
1599                 *port = '\0';
1600                 port++;
1601         }
1602         pvt->sa.sin_family = AF_INET;
1603         p = find_peer(peer, NULL, 1);
1604         if (p) {
1605                 found++;
1606                 memcpy(&pvt->options, &p->options, sizeof(pvt->options));
1607                 pvt->jointcapability = pvt->options.capability;
1608                 if (pvt->options.dtmfmode) {
1609                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1610                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1611                         } else {
1612                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1613                         }
1614                 }
1615                 if (p->addr.sin_addr.s_addr) {
1616                         pvt->sa.sin_addr = p->addr.sin_addr;
1617                         pvt->sa.sin_port = p->addr.sin_port;
1618                 }
1619                 ASTOBJ_UNREF(p, oh323_destroy_peer);
1620         }
1621         if (!p && !found) {
1622                 hostn = peer;
1623                 if (port) {
1624                         portno = atoi(port);
1625                 } else {
1626                         portno = h323_signalling_port;
1627                 }
1628                 hp = ast_gethostbyname(hostn, &ahp);
1629                 if (hp) {
1630                         memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
1631                         pvt->sa.sin_port = htons(portno);
1632                         /* Look peer by address */
1633                         p = find_peer(NULL, &pvt->sa, 1);
1634                         memcpy(&pvt->options, (p ? &p->options : &global_options), sizeof(pvt->options));
1635                         pvt->jointcapability = pvt->options.capability;
1636                         if (p) {
1637                                 ASTOBJ_UNREF(p, oh323_destroy_peer);
1638                         }
1639                         if (pvt->options.dtmfmode) {
1640                                 if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1641                                         pvt->nonCodecCapability |= AST_RTP_DTMF;
1642                                 } else {
1643                                         pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1644                                 }
1645                         }
1646                         return 0;
1647                 } else {
1648                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1649                         return -1;
1650                 }
1651         } else if (!found) {
1652                 return -1;
1653         } else {
1654                 return 0;
1655         }
1656 }
1657 static struct ast_channel *oh323_request(const char *type, int format, void *data, int *cause)
1658 {
1659         int oldformat;
1660         struct oh323_pvt *pvt;
1661         struct ast_channel *tmpc = NULL;
1662         char *dest = (char *)data;
1663         char *ext, *host;
1664         char *h323id = NULL;
1665         char tmp[256], tmp1[256];
1666
1667         if (h323debug)
1668                 ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
1669
1670         pvt = oh323_alloc(0);
1671         if (!pvt) {
1672                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
1673                 return NULL;
1674         }
1675         oldformat = format;
1676         format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
1677         if (!format) {
1678                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
1679                 oh323_destroy(pvt);
1680                 if (cause)
1681                         *cause = AST_CAUSE_INCOMPATIBLE_DESTINATION;
1682                 return NULL;
1683         }
1684         strncpy(tmp, dest, sizeof(tmp) - 1);
1685         host = strchr(tmp, '@');
1686         if (host) {
1687                 *host = '\0';
1688                 host++;
1689                 ext = tmp;
1690         } else {
1691                 ext = strrchr(tmp, '/');
1692                 if (ext)
1693                         *ext++ = '\0';
1694                 host = tmp;
1695         }
1696         strtok_r(host, "/", &(h323id));
1697         if (!ast_strlen_zero(h323id)) {
1698                 h323_set_id(h323id);
1699         }
1700         if (ext) {
1701                 strncpy(pvt->exten, ext, sizeof(pvt->exten) - 1);
1702         }
1703         if (h323debug)
1704                 ast_log(LOG_DEBUG, "Extension: %s Host: %s\n", pvt->exten, host);
1705
1706         if (gatekeeper_disable) {
1707                 if (create_addr(pvt, host)) {
1708                         oh323_destroy(pvt);
1709                         if (cause)
1710                                 *cause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1711                         return NULL;
1712                 }
1713         }
1714         else {
1715                 memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1716                 pvt->jointcapability = pvt->options.capability;
1717                 if (pvt->options.dtmfmode) {
1718                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1719                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1720                         } else {
1721                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1722                         }
1723                 }
1724         }
1725
1726         ast_mutex_lock(&caplock);
1727         /* Generate unique channel identifier */
1728         snprintf(tmp1, sizeof(tmp1)-1, "%s-%u", host, ++unique);
1729         tmp1[sizeof(tmp1)-1] = '\0';
1730         ast_mutex_unlock(&caplock);
1731
1732         ast_mutex_lock(&pvt->lock);
1733         tmpc = __oh323_new(pvt, AST_STATE_DOWN, tmp1);
1734         ast_mutex_unlock(&pvt->lock);
1735         if (!tmpc) {
1736                 oh323_destroy(pvt);
1737                 if (cause)
1738                         *cause = AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
1739         }
1740         ast_update_use_count();
1741         restart_monitor();
1742         return tmpc;
1743 }
1744
1745 /** Find a call by alias */
1746 static struct oh323_alias *find_alias(const char *source_aliases, int realtime)
1747 {
1748         struct oh323_alias *a;
1749
1750         a = ASTOBJ_CONTAINER_FIND(&aliasl, source_aliases);
1751
1752         if (!a && realtime)
1753                 a = realtime_alias(source_aliases);
1754
1755         return a;
1756 }
1757
1758 /**
1759   * Callback for sending digits from H.323 up to asterisk
1760   *
1761   */
1762 static int receive_digit(unsigned call_reference, char digit, const char *token, int duration)
1763 {
1764         struct oh323_pvt *pvt;
1765         int res;
1766
1767         pvt = find_call_locked(call_reference, token);
1768         if (!pvt) {
1769                 ast_log(LOG_ERROR, "Received digit '%c' (%u ms) for call %s without private structure\n", digit, duration, token);
1770                 return -1;
1771         }
1772         if (h323debug)
1773                 ast_log(LOG_DTMF, "Received %s digit '%c' (%u ms) for call %s\n", (digit == ' ' ? "update for" : "new"), (digit == ' ' ? pvt->curDTMF : digit), duration, token);
1774
1775         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
1776                 if (digit == '!')
1777                         res = ast_queue_control(pvt->owner, AST_CONTROL_FLASH);
1778                 else {
1779                         struct ast_frame f = {
1780                                 .frametype = AST_FRAME_DTMF_END,
1781                                 .subclass = digit,
1782                                 .samples = duration * 8,
1783                                 .src = "SEND_DIGIT",
1784                         };
1785                         if (digit == ' ') {             /* signalUpdate message */
1786                                 f.subclass = pvt->curDTMF;
1787                                 if (pvt->DTMFsched >= 0) {
1788                                         ast_sched_del(sched, pvt->DTMFsched);
1789                                         pvt->DTMFsched = -1;
1790                                 }
1791                         } else {                                /* Regular input or signal message */
1792                                 if (duration) {         /* This is a signal, signalUpdate follows */
1793                                         f.frametype = AST_FRAME_DTMF_BEGIN;
1794                                         if (pvt->DTMFsched >= 0)
1795                                                 ast_sched_del(sched, pvt->DTMFsched);
1796                                         pvt->DTMFsched = ast_sched_add(sched, duration, oh323_simulate_dtmf_end, pvt);
1797                                         if (h323debug)
1798                                                 ast_log(LOG_DTMF, "Scheduled DTMF END simulation for %d ms, id=%d\n", duration, pvt->DTMFsched);
1799                                 }
1800                                 pvt->curDTMF = digit;
1801                         }
1802                         res = ast_queue_frame(pvt->owner, &f);
1803                 }
1804                 ast_channel_unlock(pvt->owner);
1805         } else {
1806                 if (digit == '!')
1807                         pvt->newcontrol = AST_CONTROL_FLASH;
1808                 else {
1809                         pvt->newduration = duration;
1810                         pvt->newdigit = digit;
1811                 }
1812                 res = 0;
1813         }
1814         ast_mutex_unlock(&pvt->lock);
1815         return res;
1816 }
1817
1818 /**
1819   * Callback function used to inform the H.323 stack of the local rtp ip/port details
1820   *
1821   * Returns the local RTP information
1822   */
1823 static struct rtp_info *external_rtp_create(unsigned call_reference, const char * token)
1824 {
1825         struct oh323_pvt *pvt;
1826         struct sockaddr_in us;
1827         struct rtp_info *info;
1828
1829         info = (struct rtp_info *)malloc(sizeof(struct rtp_info));
1830         if (!info) {
1831                 ast_log(LOG_ERROR, "Unable to allocated info structure, this is very bad\n");
1832                 return NULL;
1833         }
1834         pvt = find_call_locked(call_reference, token);
1835         if (!pvt) {
1836                 free(info);
1837                 ast_log(LOG_ERROR, "Unable to find call %s(%d)\n", token, call_reference);
1838                 return NULL;
1839         }
1840         if (!pvt->rtp)
1841                 __oh323_rtp_create(pvt);
1842         if (!pvt->rtp) {
1843                 ast_mutex_unlock(&pvt->lock);
1844                 free(info);
1845                 ast_log(LOG_ERROR, "No RTP stream is available for call %s (%d)", token, call_reference);
1846                 return NULL;
1847         }
1848         /* figure out our local RTP port and tell the H.323 stack about it */
1849         ast_rtp_get_us(pvt->rtp, &us);
1850         ast_mutex_unlock(&pvt->lock);
1851
1852         strncpy(info->addr, ast_inet_ntoa(us.sin_addr), sizeof(info->addr));
1853         info->addr[sizeof(info->addr)-1] = '\0';
1854         info->port = ntohs(us.sin_port);
1855         if (h323debug)
1856                 ast_log(LOG_DEBUG, "Sending RTP 'US' %s:%d\n", info->addr, info->port);
1857         return info;
1858 }
1859
1860 /**
1861  * Definition taken from rtp.c for rtpPayloadType because we need it here.
1862  */
1863 struct rtpPayloadType {
1864         int isAstFormat;        /* whether the following code is an AST_FORMAT */
1865         int code;
1866 };
1867
1868 /**
1869   * Call-back function passing remote ip/port information from H.323 to asterisk
1870   *
1871   * Returns nothing
1872   */
1873 static void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort, const char *token, int pt)
1874 {
1875         struct oh323_pvt *pvt;
1876         struct sockaddr_in them;
1877         struct rtpPayloadType rtptype;
1878         int nativeformats_changed;
1879         enum { NEED_NONE, NEED_HOLD, NEED_UNHOLD } rtp_change = NEED_NONE;
1880
1881         if (h323debug)
1882                 ast_log(LOG_DEBUG, "Setting up RTP connection for %s\n", token);
1883
1884         /* Find the call or allocate a private structure if call not found */
1885         pvt = find_call_locked(call_reference, token);
1886         if (!pvt) {
1887                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1888                 return;
1889         }
1890         if (pvt->alreadygone) {
1891                 ast_mutex_unlock(&pvt->lock);
1892                 return;
1893         }
1894
1895         if (!pvt->rtp)
1896                 __oh323_rtp_create(pvt);
1897
1898         if ((pt == 2) && (pvt->jointcapability & AST_FORMAT_G726_AAL2)) {
1899                 ast_rtp_set_rtpmap_type(pvt->rtp, pt, "audio", "G726-32", AST_RTP_OPT_G726_NONSTANDARD);
1900         }
1901
1902         them.sin_family = AF_INET;
1903         /* only works for IPv4 */
1904         them.sin_addr.s_addr = inet_addr(remoteIp);
1905         them.sin_port = htons(remotePort);
1906
1907         if (them.sin_addr.s_addr) {
1908                 ast_rtp_set_peer(pvt->rtp, &them);
1909                 if (pvt->recvonly) {
1910                         pvt->recvonly = 0;
1911                         rtp_change = NEED_UNHOLD;
1912                 }
1913         } else {
1914                 ast_rtp_stop(pvt->rtp);
1915                 if (!pvt->recvonly) {
1916                         pvt->recvonly = 1;
1917                         rtp_change = NEED_HOLD;
1918                 }
1919         }
1920
1921         /* Change native format to reflect information taken from OLC/OLCAck */
1922         nativeformats_changed = 0;
1923         if (pt != 128 && pvt->rtp) {    /* Payload type is invalid, so try to use previously decided */
1924                 rtptype = ast_rtp_lookup_pt(pvt->rtp, pt);
1925                 if (h323debug)
1926                         ast_log(LOG_DEBUG, "Native format is set to %d from %d by RTP payload type %d\n", rtptype.code, pvt->nativeformats, pt);
1927                 if (pvt->nativeformats != rtptype.code) {
1928                         pvt->nativeformats = rtptype.code;
1929                         nativeformats_changed = 1;
1930                 }
1931         } else if (h323debug)
1932                 ast_log(LOG_NOTICE, "Payload type is unknown, formats isn't changed\n");
1933
1934         /* Don't try to lock the channel if nothing changed */
1935         if (nativeformats_changed || pvt->options.progress_audio || (rtp_change != NEED_NONE)) {
1936                 if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
1937                         /* Re-build translation path only if native format(s) has been changed */
1938                         if (pvt->owner->nativeformats != pvt->nativeformats) {
1939                                 if (h323debug)
1940                                         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);
1941                                 pvt->owner->nativeformats = pvt->nativeformats;
1942                                 ast_set_read_format(pvt->owner, pvt->owner->readformat);
1943                                 ast_set_write_format(pvt->owner, pvt->owner->writeformat);
1944                         }
1945                         if (pvt->options.progress_audio)
1946                                 ast_queue_control(pvt->owner, AST_CONTROL_PROGRESS);
1947                         switch (rtp_change) {
1948                         case NEED_HOLD:
1949                                 ast_queue_control(pvt->owner, AST_CONTROL_HOLD);
1950                                 break;
1951                         case NEED_UNHOLD:
1952                                 ast_queue_control(pvt->owner, AST_CONTROL_UNHOLD);
1953                                 break;
1954                         default:
1955                                 break;
1956                         }
1957                         ast_channel_unlock(pvt->owner);
1958                 }
1959                 else {
1960                         if (pvt->options.progress_audio)
1961                                 pvt->newcontrol = AST_CONTROL_PROGRESS;
1962                         else if (rtp_change == NEED_HOLD)
1963                                 pvt->newcontrol = AST_CONTROL_HOLD;
1964                         else if (rtp_change == NEED_UNHOLD)
1965                                 pvt->newcontrol = AST_CONTROL_UNHOLD;
1966                         if (h323debug)
1967                                 ast_log(LOG_DEBUG, "RTP connection preparation for %s is pending...\n", token);
1968                 }
1969         }
1970         ast_mutex_unlock(&pvt->lock);
1971
1972         if (h323debug)
1973                 ast_log(LOG_DEBUG, "RTP connection prepared for %s\n", token);
1974
1975         return;
1976 }
1977
1978 /**
1979   *     Call-back function to signal asterisk that the channel has been answered
1980   * Returns nothing
1981   */
1982 static void connection_made(unsigned call_reference, const char *token)
1983 {
1984         struct oh323_pvt *pvt;
1985
1986         if (h323debug)
1987                 ast_log(LOG_DEBUG, "Call %s answered\n", token);
1988
1989         pvt = find_call_locked(call_reference, token);
1990         if (!pvt) {
1991                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1992                 return;
1993         }
1994
1995         /* Inform asterisk about remote party connected only on outgoing calls */
1996         if (!pvt->outgoing) {
1997                 ast_mutex_unlock(&pvt->lock);
1998                 return;
1999         }
2000         /* Do not send ANSWER message more than once */
2001         if (!pvt->connection_established) {
2002                 pvt->connection_established = 1;
2003                 update_state(pvt, -1, AST_CONTROL_ANSWER);
2004         }
2005         ast_mutex_unlock(&pvt->lock);
2006         return;
2007 }
2008
2009 static int progress(unsigned call_reference, const char *token, int inband)
2010 {
2011         struct oh323_pvt *pvt;
2012
2013         if (h323debug)
2014                 ast_log(LOG_DEBUG, "Received ALERT/PROGRESS message for %s tones\n", (inband ? "inband" : "self-generated"));
2015
2016         pvt = find_call_locked(call_reference, token);
2017         if (!pvt) {
2018                 ast_log(LOG_ERROR, "Private structure not found in progress.\n");
2019                 return -1;
2020         }
2021         if (!pvt->owner) {
2022                 ast_mutex_unlock(&pvt->lock);
2023                 ast_log(LOG_ERROR, "No Asterisk channel associated with private structure.\n");
2024                 return -1;
2025         }
2026         update_state(pvt, -1, (inband ? AST_CONTROL_PROGRESS : AST_CONTROL_RINGING));
2027         ast_mutex_unlock(&pvt->lock);
2028
2029         return 0;
2030 }
2031
2032 /**
2033  *  Call-back function for incoming calls
2034  *
2035  *  Returns 1 on success
2036  */
2037 static call_options_t *setup_incoming_call(call_details_t *cd)
2038 {
2039         struct oh323_pvt *pvt;
2040         struct oh323_user *user = NULL;
2041         struct oh323_alias *alias = NULL;
2042
2043         if (h323debug)
2044                 ast_log(LOG_DEBUG, "Setting up incoming call for %s\n", cd->call_token);
2045
2046         /* allocate the call*/
2047         pvt = oh323_alloc(cd->call_reference);
2048
2049         if (!pvt) {
2050                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
2051                 cleanup_call_details(cd);
2052                 return NULL;
2053         }
2054
2055         /* Populate the call details in the private structure */
2056         memcpy(&pvt->cd, cd, sizeof(pvt->cd));
2057         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
2058         pvt->jointcapability = pvt->options.capability;
2059
2060         if (h323debug) {
2061                 ast_verbose(VERBOSE_PREFIX_3 "Setting up Call\n");
2062                 ast_verbose(VERBOSE_PREFIX_3 " \tCall token:  [%s]\n", pvt->cd.call_token);
2063                 ast_verbose(VERBOSE_PREFIX_3 " \tCalling party name:  [%s]\n", pvt->cd.call_source_name);
2064                 ast_verbose(VERBOSE_PREFIX_3 " \tCalling party number:  [%s]\n", pvt->cd.call_source_e164);
2065                 ast_verbose(VERBOSE_PREFIX_3 " \tCalled party name:  [%s]\n", pvt->cd.call_dest_alias);
2066                 ast_verbose(VERBOSE_PREFIX_3 " \tCalled party number:  [%s]\n", pvt->cd.call_dest_e164);
2067                 if (pvt->cd.redirect_reason >= 0)
2068                         ast_verbose(VERBOSE_PREFIX_3 " \tRedirecting party number:  [%s] (reason %d)\n", pvt->cd.redirect_number, pvt->cd.redirect_reason);
2069                 ast_verbose(VERBOSE_PREFIX_3 " \tCalling party IP:  [%s]\n", pvt->cd.sourceIp);
2070         }
2071
2072         /* Decide if we are allowing Gatekeeper routed calls*/
2073         if ((!strcasecmp(cd->sourceIp, gatekeeper)) && (gkroute == -1) && !gatekeeper_disable) {
2074                 if (!ast_strlen_zero(cd->call_dest_e164)) {
2075                         strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
2076                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
2077                 } else {
2078                         alias = find_alias(cd->call_dest_alias, 1);
2079                         if (!alias) {
2080                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd->call_dest_alias);
2081                                 oh323_destroy(pvt);
2082                                 return NULL;
2083                         }
2084                         strncpy(pvt->exten, alias->name, sizeof(pvt->exten) - 1);
2085                         strncpy(pvt->context, alias->context, sizeof(pvt->context) - 1);
2086                 }
2087         } else {
2088                 /* Either this call is not from the Gatekeeper
2089                    or we are not allowing gk routed calls */
2090                 user = find_user(cd, 1);
2091                 if (!user) {
2092                         if (!acceptAnonymous) {
2093                                 ast_log(LOG_NOTICE, "Anonymous call from '%s@%s' rejected\n", pvt->cd.call_source_aliases, pvt->cd.sourceIp);
2094                                 oh323_destroy(pvt);
2095                                 return NULL;
2096                         }
2097                         if (ast_strlen_zero(default_context)) {
2098                                 ast_log(LOG_ERROR, "Call from '%s@%s' rejected due to no default context\n", pvt->cd.call_source_aliases, pvt->cd.sourceIp);
2099                                 oh323_destroy(pvt);
2100                                 return NULL;
2101                         }
2102                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
2103                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
2104                                 strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
2105                         } else {
2106                                 strncpy(pvt->exten, cd->call_dest_alias, sizeof(pvt->exten) - 1);
2107                         }
2108                         if (h323debug)
2109                                 ast_log(LOG_DEBUG, "Sending %s@%s to context [%s] extension %s\n", cd->call_source_aliases, cd->sourceIp, pvt->context, pvt->exten);
2110                 } else {
2111                         if (user->host) {
2112                                 if (strcasecmp(cd->sourceIp, ast_inet_ntoa(user->addr.sin_addr))) {
2113                                         if (ast_strlen_zero(user->context)) {
2114                                                 if (ast_strlen_zero(default_context)) {
2115                                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s) and no default context\n", user->name, cd->sourceIp);
2116                                                         oh323_destroy(pvt);
2117                                                         ASTOBJ_UNREF(user, oh323_destroy_user);
2118                                                         return NULL;
2119                                                 }
2120                                                 strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
2121                                         } else {
2122                                                 strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
2123                                         }
2124                                         pvt->exten[0] = 'i';
2125                                         pvt->exten[1] = '\0';
2126                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s)s\n", user->name, cd->sourceIp);
2127                                         oh323_destroy(pvt);
2128                                         ASTOBJ_UNREF(user, oh323_destroy_user);
2129                                         return NULL;    /* XXX: Hmmm... Why to setup context if we drop connection immediately??? */
2130                                 }
2131                         }
2132                         strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
2133                         memcpy(&pvt->options, &user->options, sizeof(pvt->options));
2134                         pvt->jointcapability = pvt->options.capability;
2135                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
2136                                 strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
2137                         } else {
2138                                 strncpy(pvt->exten, cd->call_dest_alias, sizeof(pvt->exten) - 1);
2139                         }
2140                         if (!ast_strlen_zero(user->accountcode)) {
2141                                 strncpy(pvt->accountcode, user->accountcode, sizeof(pvt->accountcode) - 1);
2142                         }
2143                         if (user->amaflags) {
2144                                 pvt->amaflags = user->amaflags;
2145                         }
2146                         ASTOBJ_UNREF(user, oh323_destroy_user);
2147                 }
2148         }
2149         return &pvt->options;
2150 }
2151
2152 /**
2153  * Call-back function to start PBX when OpenH323 ready to serve incoming call
2154  *
2155  * Returns 1 on success
2156  */
2157 static int answer_call(unsigned call_reference, const char *token)
2158 {
2159         struct oh323_pvt *pvt;
2160         struct ast_channel *c = NULL;
2161         enum {ext_original, ext_s, ext_i, ext_notexists} try_exten;
2162         char tmp_exten[sizeof(pvt->exten)];
2163
2164         if (h323debug)
2165                 ast_log(LOG_DEBUG, "Preparing Asterisk to answer for %s\n", token);
2166
2167         /* Find the call or allocate a private structure if call not found */
2168         pvt = find_call_locked(call_reference, token);
2169         if (!pvt) {
2170                 ast_log(LOG_ERROR, "Something is wrong: answer_call\n");
2171                 return 0;
2172         }
2173         /* Check if requested extension@context pair exists in the dialplan */
2174         strncpy(tmp_exten, pvt->exten, sizeof(tmp_exten));
2175
2176         /* Try to find best extension in specified context */
2177         if ((tmp_exten[0] != '\0') && (tmp_exten[1] == '\0')) {
2178                 if (tmp_exten[0] == 's')
2179                         try_exten = ext_s;
2180                 else if (tmp_exten[0] == 'i')
2181                         try_exten = ext_i;
2182                 else
2183                         try_exten = ext_original;
2184         } else
2185                 try_exten = ext_original;
2186         do {
2187                 if (ast_exists_extension(NULL, pvt->context, tmp_exten, 1, NULL))
2188                         break;
2189                 switch (try_exten) {
2190                 case ext_original:
2191                         tmp_exten[0] = 's';
2192                         tmp_exten[1] = '\0';
2193                         try_exten = ext_s;
2194                         break;
2195                 case ext_s:
2196                         tmp_exten[0] = 'i';
2197                         try_exten = ext_i;
2198                         break;
2199                 case ext_i:
2200                         try_exten = ext_notexists;
2201                         break;
2202                 default:
2203                         break;
2204                 }
2205         } while (try_exten != ext_notexists);
2206
2207         /* Drop the call if we don't have <exten>, s and i extensions */
2208         if (try_exten == ext_notexists) {
2209                 ast_log(LOG_NOTICE, "Dropping call because extensions '%s', 's' and 'i' doesn't exists in context [%s]\n", pvt->exten, pvt->context);
2210                 ast_mutex_unlock(&pvt->lock);
2211                 h323_clear_call(token, AST_CAUSE_UNALLOCATED);
2212                 return 0;
2213         } else if ((try_exten != ext_original) && (strcmp(pvt->exten, tmp_exten) != 0)) {
2214                 if (h323debug)
2215                         ast_log(LOG_DEBUG, "Going to extension %s@%s because %s@%s isn't exists\n", tmp_exten, pvt->context, pvt->exten, pvt->context);
2216                 strncpy(pvt->exten, tmp_exten, sizeof(pvt->exten));
2217         }
2218
2219         /* allocate a channel and tell asterisk about it */
2220         c = __oh323_new(pvt, AST_STATE_RINGING, pvt->cd.call_token);
2221
2222         /* And release when done */
2223         ast_mutex_unlock(&pvt->lock);
2224         if (!c) {
2225                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
2226                 return 0;
2227         }
2228         return 1;
2229 }
2230
2231 /**
2232  * Call-back function to establish an outgoing H.323 call
2233  *
2234  * Returns 1 on success
2235  */
2236 static int setup_outgoing_call(call_details_t *cd)
2237 {
2238         /* Use argument here or free it immediately */
2239         cleanup_call_details(cd);
2240
2241         return 1;
2242 }
2243
2244 /**
2245   *  Call-back function to signal asterisk that the channel is ringing
2246   *  Returns nothing
2247   */
2248 static void chan_ringing(unsigned call_reference, const char *token)
2249 {
2250         struct oh323_pvt *pvt;
2251
2252         if (h323debug)
2253                 ast_log(LOG_DEBUG, "Ringing on %s\n", token);
2254
2255         pvt = find_call_locked(call_reference, token);
2256         if (!pvt) {
2257                 ast_log(LOG_ERROR, "Something is wrong: ringing\n");
2258                 return;
2259         }
2260         if (!pvt->owner) {
2261                 ast_mutex_unlock(&pvt->lock);
2262                 ast_log(LOG_ERROR, "Channel has no owner\n");
2263                 return;
2264         }
2265         update_state(pvt, AST_STATE_RINGING, AST_CONTROL_RINGING);
2266         ast_mutex_unlock(&pvt->lock);
2267         return;
2268 }
2269
2270 /**
2271   * Call-back function to cleanup communication
2272   * Returns nothing,
2273   */
2274 static void cleanup_connection(unsigned call_reference, const char *call_token)
2275 {
2276         struct oh323_pvt *pvt;
2277
2278         if (h323debug)
2279                 ast_log(LOG_DEBUG, "Cleaning connection to %s\n", call_token);
2280
2281         while (1) {
2282                 pvt = find_call_locked(call_reference, call_token);
2283                 if (!pvt) {
2284                         if (h323debug)
2285                                 ast_log(LOG_DEBUG, "No connection for %s\n", call_token);
2286                         return;
2287                 }
2288                 if (!pvt->owner || !ast_channel_trylock(pvt->owner))
2289                         break;
2290 #if 1
2291 #ifdef DEBUG_THREADS
2292                 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]);
2293 #else
2294                 ast_log(LOG_NOTICE, "Avoiding H.323 destory deadlock on %s\n", call_token);
2295 #endif
2296 #endif
2297                 ast_mutex_unlock(&pvt->lock);
2298                 usleep(1);
2299         }
2300         if (pvt->rtp) {
2301                 /* Immediately stop RTP */
2302                 ast_rtp_destroy(pvt->rtp);
2303                 pvt->rtp = NULL;
2304         }
2305         /* Free dsp used for in-band DTMF detection */
2306         if (pvt->vad) {
2307                 ast_dsp_free(pvt->vad);
2308                 pvt->vad = NULL;
2309         }
2310         cleanup_call_details(&pvt->cd);
2311         pvt->alreadygone = 1;
2312         /* Send hangup */
2313         if (pvt->owner) {
2314                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2315                 ast_queue_hangup(pvt->owner);
2316                 ast_channel_unlock(pvt->owner);
2317         }
2318         ast_mutex_unlock(&pvt->lock);
2319         if (h323debug)
2320                 ast_log(LOG_DEBUG, "Connection to %s cleaned\n", call_token);
2321         return;
2322 }
2323
2324 static void hangup_connection(unsigned int call_reference, const char *token, int cause)
2325 {
2326         struct oh323_pvt *pvt;
2327
2328         if (h323debug) {
2329                 ast_log(LOG_DEBUG, "Hanging up connection to %s with cause %d\n", token, cause);
2330         }
2331
2332         pvt = find_call_locked(call_reference, token);
2333         if (!pvt) {
2334                 if (h323debug) {
2335                         ast_log(LOG_DEBUG, "Connection to %s already cleared\n", token);
2336                 }
2337                 return;
2338         }
2339         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
2340                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2341                 pvt->owner->hangupcause = pvt->hangupcause = cause;
2342                 ast_queue_hangup(pvt->owner);
2343                 ast_channel_unlock(pvt->owner);
2344         }
2345         else {
2346                 pvt->needhangup = 1;
2347                 pvt->hangupcause = cause;
2348                 if (h323debug)
2349                         ast_log(LOG_DEBUG, "Hangup for %s is pending\n", token);
2350         }
2351         ast_mutex_unlock(&pvt->lock);
2352 }
2353
2354 static void set_dtmf_payload(unsigned call_reference, const char *token, int payload)
2355 {
2356         struct oh323_pvt *pvt;
2357
2358         if (h323debug)
2359                 ast_log(LOG_DEBUG, "Setting DTMF payload to %d on %s\n", payload, token);
2360
2361         pvt = find_call_locked(call_reference, token);
2362         if (!pvt) {
2363                 return;
2364         }
2365         if (pvt->rtp) {
2366                 ast_rtp_set_rtpmap_type(pvt->rtp, payload, "audio", "telephone-event", 0);
2367         }
2368         pvt->dtmf_pt = payload;
2369         ast_mutex_unlock(&pvt->lock);
2370         if (h323debug)
2371                 ast_log(LOG_DEBUG, "DTMF payload on %s set to %d\n", token, payload);
2372 }
2373
2374 static void set_peer_capabilities(unsigned call_reference, const char *token, int capabilities, struct ast_codec_pref *prefs)
2375 {
2376         struct oh323_pvt *pvt;
2377
2378         if (h323debug)
2379                 ast_log(LOG_DEBUG, "Got remote capabilities from connection %s\n", token);
2380
2381         pvt = find_call_locked(call_reference, token);
2382         if (!pvt)
2383                 return;
2384         pvt->peercapability = capabilities;
2385         pvt->jointcapability = pvt->options.capability & capabilities;
2386         if (prefs) {
2387                 memcpy(&pvt->peer_prefs, prefs, sizeof(pvt->peer_prefs));
2388                 if (h323debug) {
2389                         int i;
2390                         for (i = 0; i < 32; ++i) {
2391                                 ast_log(LOG_DEBUG, "prefs[%d]=%s:%d\n", i, (prefs->order[i] ? ast_getformatname(1 << (prefs->order[i]-1)) : "<none>"), prefs->framing[i]);
2392                         }
2393                 }
2394                 if (pvt->rtp)
2395                         ast_rtp_codec_setpref(pvt->rtp, &pvt->peer_prefs);
2396         }
2397         ast_mutex_unlock(&pvt->lock);
2398 }
2399
2400 static void set_local_capabilities(unsigned call_reference, const char *token)
2401 {
2402         struct oh323_pvt *pvt;
2403         int capability, dtmfmode, pref_codec;
2404         struct ast_codec_pref prefs;
2405
2406         if (h323debug)
2407                 ast_log(LOG_DEBUG, "Setting capabilities for connection %s\n", token);
2408
2409         pvt = find_call_locked(call_reference, token);
2410         if (!pvt)
2411                 return;
2412         capability = (pvt->jointcapability) ? pvt->jointcapability : pvt->options.capability;
2413         dtmfmode = pvt->options.dtmfmode;
2414         prefs = pvt->options.prefs;
2415         pref_codec = pvt->pref_codec;
2416         ast_mutex_unlock(&pvt->lock);
2417         h323_set_capabilities(token, capability, dtmfmode, &prefs, pref_codec);
2418
2419         if (h323debug)
2420                 ast_log(LOG_DEBUG, "Capabilities for connection %s is set\n", token);
2421 }
2422
2423 static void *do_monitor(void *data)
2424 {
2425         int res;
2426         int reloading;
2427         struct oh323_pvt *oh323 = NULL;
2428
2429         for(;;) {
2430                 /* Check for a reload request */
2431                 ast_mutex_lock(&h323_reload_lock);
2432                 reloading = h323_reloading;
2433                 h323_reloading = 0;
2434                 ast_mutex_unlock(&h323_reload_lock);
2435                 if (reloading) {
2436                         if (option_verbose > 0) {
2437                                 ast_verbose(VERBOSE_PREFIX_1 "Reloading H.323\n");
2438                         }
2439                         h323_do_reload();
2440                 }
2441                 /* Check for interfaces needing to be killed */
2442                 if (!ast_mutex_trylock(&iflock)) {
2443 #if 1
2444                         do {
2445                                 for (oh323 = iflist; oh323; oh323 = oh323->next) {
2446                                         if (!ast_mutex_trylock(&oh323->lock)) {
2447                                                 if (oh323->needdestroy) {
2448                                                         __oh323_destroy(oh323);
2449                                                         break;
2450                                                 }
2451                                                 ast_mutex_unlock(&oh323->lock);
2452                                         }
2453                                 }
2454                         } while (/*oh323*/ 0);
2455 #else
2456 restartsearch:
2457                         oh323 = iflist;
2458                         while(oh323) {
2459                                 if (!ast_mutex_trylock(&oh323->lock)) {
2460                                         if (oh323->needdestroy) {
2461                                                 __oh323_destroy(oh323);
2462                                                 goto restartsearch;
2463                                         }
2464                                         ast_mutex_unlock(&oh323->lock);
2465                                         oh323 = oh323->next;
2466                                 }
2467                         }
2468 #endif
2469                         ast_mutex_unlock(&iflock);
2470                 } else
2471                         oh323 = (struct oh323_pvt *)1;  /* Force fast loop */
2472                 pthread_testcancel();
2473                 /* Wait for sched or io */
2474                 res = ast_sched_wait(sched);
2475                 if ((res < 0) || (res > 1000)) {
2476                         res = 1000;
2477                 }
2478                 /* Do not wait if some channel(s) is destroyed, probably, more available too */
2479                 if (oh323)
2480                         res = 1;
2481                 res = ast_io_wait(io, res);
2482                 pthread_testcancel();
2483                 ast_mutex_lock(&monlock);
2484                 if (res >= 0) {
2485                         ast_sched_runq(sched);
2486                 }
2487                 ast_mutex_unlock(&monlock);
2488         }
2489         /* Never reached */
2490         return NULL;
2491 }
2492
2493 static int restart_monitor(void)
2494 {
2495         pthread_attr_t attr;
2496         /* If we're supposed to be stopped -- stay stopped */
2497         if (ast_mutex_lock(&monlock)) {
2498                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
2499                 return -1;
2500         }
2501         if (monitor_thread == AST_PTHREADT_STOP) {
2502                 ast_mutex_unlock(&monlock);
2503                 return 0;
2504         }
2505         if (monitor_thread == pthread_self()) {
2506                 ast_mutex_unlock(&monlock);
2507                 ast_log(LOG_WARNING, "Cannot kill myself\n");
2508                 return -1;
2509         }
2510         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
2511                 /* Wake up the thread */
2512                 pthread_kill(monitor_thread, SIGURG);
2513         } else {
2514                 pthread_attr_init(&attr);
2515                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2516                 /* Start a new monitor */
2517                 if (ast_pthread_create(&monitor_thread, &attr, do_monitor, NULL) < 0) {
2518                         monitor_thread = AST_PTHREADT_NULL;
2519                         ast_mutex_unlock(&monlock);
2520                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
2521                         return -1;
2522                 }
2523         }
2524         ast_mutex_unlock(&monlock);
2525         return 0;
2526 }
2527
2528 static int h323_do_trace(int fd, int argc, char *argv[])
2529 {
2530         if (argc != 3) {
2531                 return RESULT_SHOWUSAGE;
2532         }
2533         h323_debug(1, atoi(argv[2]));
2534         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
2535         return RESULT_SUCCESS;
2536 }
2537
2538 static int h323_no_trace(int fd, int argc, char *argv[])
2539 {
2540         if (argc != 3) {
2541                 return RESULT_SHOWUSAGE;
2542         }
2543         h323_debug(0,0);
2544         ast_cli(fd, "H.323 trace disabled\n");
2545         return RESULT_SUCCESS;
2546 }
2547
2548 static int h323_do_debug(int fd, int argc, char *argv[])
2549 {
2550         if (argc != 2) {
2551                 return RESULT_SHOWUSAGE;
2552         }
2553         h323debug = 1;
2554         ast_cli(fd, "H.323 debug enabled\n");
2555         return RESULT_SUCCESS;
2556 }
2557
2558 static int h323_no_debug(int fd, int argc, char *argv[])
2559 {
2560         if (argc != 3) {
2561                 return RESULT_SHOWUSAGE;
2562         }
2563         h323debug = 0;
2564         ast_cli(fd, "H.323 debug disabled\n");
2565         return RESULT_SUCCESS;
2566 }
2567
2568 static int h323_gk_cycle(int fd, int argc, char *argv[])
2569 {
2570         if (argc != 3) {
2571                 return RESULT_SHOWUSAGE;
2572         }
2573         h323_gk_urq();
2574
2575         /* Possibly register with a GK */
2576         if (!gatekeeper_disable) {
2577                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
2578                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
2579                 }
2580         }
2581         return RESULT_SUCCESS;
2582 }
2583
2584 static int h323_ep_hangup(int fd, int argc, char *argv[])
2585 {
2586         if (argc != 3) {
2587                 return RESULT_SHOWUSAGE;
2588         }
2589         if (h323_soft_hangup(argv[2])) {
2590                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
2591         } else {
2592                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
2593         }
2594         return RESULT_SUCCESS;
2595 }
2596
2597 static int h323_tokens_show(int fd, int argc, char *argv[])
2598 {
2599         if (argc != 3) {
2600                 return RESULT_SHOWUSAGE;
2601         }
2602         h323_show_tokens();
2603         return RESULT_SUCCESS;
2604 }
2605
2606 static char trace_usage[] =
2607 "Usage: h323 trace <level num>\n"
2608 "       Enables H.323 stack tracing for debugging purposes\n";
2609
2610 static char no_trace_usage[] =
2611 "Usage: h323 no trace\n"
2612 "       Disables H.323 stack tracing for debugging purposes\n";
2613
2614 static char debug_usage[] =
2615 "Usage: h323 debug\n"
2616 "       Enables H.323 debug output\n";
2617
2618 static char no_debug_usage[] =
2619 "Usage: h323 no debug\n"
2620 "       Disables H.323 debug output\n";
2621
2622 static char show_cycle_usage[] =
2623 "Usage: h323 gk cycle\n"
2624 "       Manually re-register with the Gatekeper (Currently Disabled)\n";
2625
2626 static char show_hangup_usage[] =
2627 "Usage: h323 hangup <token>\n"
2628 "       Manually try to hang up call identified by <token>\n";
2629
2630 static char show_tokens_usage[] =
2631 "Usage: h323 show tokens\n"
2632 "       Print out all active call tokens\n";
2633
2634 static char h323_reload_usage[] =
2635 "Usage: h323 reload\n"
2636 "       Reloads H.323 configuration from h323.conf\n";
2637
2638 static struct ast_cli_entry cli_h323_trace_deprecated =
2639         { { "h.323", "trace", NULL },
2640         h323_do_trace, "Enable H.323 Stack Tracing",
2641         trace_usage };
2642
2643 static struct ast_cli_entry cli_h323_no_trace_deprecated =
2644         { { "h.323", "no", "trace", NULL },
2645         h323_no_trace, "Disable H.323 Stack Tracing",
2646         no_trace_usage };
2647
2648 static struct ast_cli_entry cli_h323_debug_deprecated =
2649         { { "h.323", "debug", NULL },
2650         h323_do_debug, "Enable H.323 debug",
2651         debug_usage };
2652
2653 static struct ast_cli_entry cli_h323_no_debug_deprecated =
2654         { { "h.323", "no", "debug", NULL },
2655         h323_no_debug, "Disable H.323 debug",
2656         no_debug_usage };
2657
2658 static struct ast_cli_entry cli_h323_gk_cycle_deprecated =
2659         { { "h.323", "gk", "cycle", NULL },
2660         h323_gk_cycle, "Manually re-register with the Gatekeper",
2661         show_cycle_usage };
2662
2663 static struct ast_cli_entry cli_h323_hangup_deprecated =
2664         { { "h.323", "hangup", NULL },
2665         h323_ep_hangup, "Manually try to hang up a call",
2666         show_hangup_usage };
2667
2668 static struct ast_cli_entry cli_h323_show_tokens_deprecated =
2669         { { "h.323", "show", "tokens", NULL },
2670         h323_tokens_show, "Show all active call tokens",
2671         show_tokens_usage };
2672
2673 static struct ast_cli_entry cli_h323[] = {
2674         { { "h323", "trace", NULL },
2675         h323_do_trace, "Enable H.323 Stack Tracing",
2676         trace_usage, NULL, &cli_h323_trace_deprecated },
2677
2678         { { "h323", "no", "trace", NULL },
2679         h323_no_trace, "Disable H.323 Stack Tracing",
2680         no_trace_usage, NULL, &cli_h323_no_trace_deprecated },
2681
2682         { { "h323", "debug", NULL },
2683         h323_do_debug, "Enable H.323 debug",
2684         debug_usage, NULL, &cli_h323_debug_deprecated },
2685
2686         { { "h323", "no", "debug", NULL },
2687         h323_no_debug, "Disable H.323 debug",
2688         no_debug_usage, NULL, &cli_h323_no_debug_deprecated },
2689
2690         { { "h323", "gk", "cycle", NULL },
2691         h323_gk_cycle, "Manually re-register with the Gatekeper",
2692         show_cycle_usage, NULL, &cli_h323_gk_cycle_deprecated },
2693
2694         { { "h323", "hangup", NULL },
2695         h323_ep_hangup, "Manually try to hang up a call",
2696         show_hangup_usage, NULL, &cli_h323_hangup_deprecated },
2697
2698         { { "h323", "show", "tokens", NULL },
2699         h323_tokens_show, "Show all active call tokens",
2700         show_tokens_usage, NULL, &cli_h323_show_tokens_deprecated },
2701 };
2702
2703 static int reload_config(int is_reload)
2704 {
2705         int format;
2706         struct ast_config *cfg, *ucfg;
2707         struct ast_variable *v;
2708         struct oh323_peer *peer = NULL;
2709         struct oh323_user *user = NULL;
2710         struct oh323_alias *alias = NULL;
2711         struct ast_hostent ahp; struct hostent *hp;
2712         char *cat;
2713         const char *utype;
2714         int is_user, is_peer, is_alias;
2715         char _gatekeeper[100];
2716         int gk_discover, gk_disable, gk_changed;
2717
2718         cfg = ast_config_load(config);
2719
2720         /* We *must* have a config file otherwise stop immediately */
2721         if (!cfg) {
2722                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
2723                 return 1;
2724         }
2725
2726         /* fire up the H.323 Endpoint */
2727         if (!h323_end_point_exist()) {
2728                 h323_end_point_create();
2729         }
2730         strncpy(_gatekeeper, gatekeeper, sizeof(_gatekeeper));
2731         gk_discover = gatekeeper_discover;
2732         gk_disable = gatekeeper_disable;
2733         memset(&bindaddr, 0, sizeof(bindaddr));
2734         memset(&global_options, 0, sizeof(global_options));
2735         global_options.fastStart = 1;
2736         global_options.h245Tunneling = 1;
2737         global_options.dtmfcodec = H323_DTMF_RFC2833_PT;
2738         global_options.dtmfmode = 0;
2739         global_options.capability = GLOBAL_CAPABILITY;
2740         global_options.bridge = 1;              /* Do native bridging by default */
2741         strncpy(default_context, "default", sizeof(default_context) - 1);
2742         h323_signalling_port = 1720;
2743         gatekeeper_disable = 1;
2744         gatekeeper_discover = 0;
2745         gkroute = 0;
2746         userbyalias = 1;
2747         acceptAnonymous = 1;
2748         tos = 0;
2749
2750         /* Copy the default jb config over global_jbconf */
2751         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
2752
2753         /* Load configuration from users.conf */
2754         ucfg = ast_config_load("users.conf");
2755         if (ucfg) {
2756                 struct ast_variable *gen;
2757                 int genhas_h323;
2758                 const char *has_h323;
2759
2760                 genhas_h323 = ast_true(ast_variable_retrieve(ucfg, "general", "hash323"));
2761                 gen = ast_variable_browse(ucfg, "general");
2762                 for (cat = ast_category_browse(ucfg, NULL); cat; cat = ast_category_browse(ucfg, cat)) {
2763                         if (strcasecmp(cat, "general")) {
2764                                 has_h323 = ast_variable_retrieve(ucfg, cat, "hash323");
2765                                 if (ast_true(has_h323) || (!has_h323 && genhas_h323)) {
2766                                         user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
2767                                         if (user) {
2768                                                 ASTOBJ_CONTAINER_LINK(&userl, user);
2769                                                 ASTOBJ_UNREF(user, oh323_destroy_user);
2770                                         }
2771                                 }
2772                         }
2773                 }
2774                 ast_config_destroy(ucfg);
2775         }
2776
2777         for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
2778                 /* handle jb conf */
2779                 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
2780                         continue;
2781                 /* Create the interface list */
2782                 if (!strcasecmp(v->name, "port")) {
2783                         h323_signalling_port = (int)strtol(v->value, NULL, 10);
2784                 } else if (!strcasecmp(v->name, "bindaddr")) {
2785                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
2786                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
2787                         } else {
2788                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
2789                         }
2790                 } else if (!strcasecmp(v->name, "tos")) {
2791                         if (sscanf(v->value, "%d", &format)) {
2792                                 tos = format & 0xff;
2793                         } else if (!strcasecmp(v->value, "lowdelay")) {
2794                                 tos = IPTOS_LOWDELAY;
2795                         } else if (!strcasecmp(v->value, "throughput")) {
2796                                 tos = IPTOS_THROUGHPUT;
2797                         } else if (!strcasecmp(v->value, "reliability")) {
2798                                 tos = IPTOS_RELIABILITY;
2799                         } else if (!strcasecmp(v->value, "mincost")) {
2800                                 tos = IPTOS_MINCOST;
2801                         } else if (!strcasecmp(v->value, "none")) {
2802                                 tos = 0;
2803                         } else {
2804                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
2805                         }
2806                 } else if (!strcasecmp(v->name, "gatekeeper")) {
2807                         if (!strcasecmp(v->value, "DISABLE")) {
2808                                 gatekeeper_disable = 1;
2809                         } else if (!strcasecmp(v->value, "DISCOVER")) {
2810                                 gatekeeper_disable = 0;
2811                                 gatekeeper_discover = 1;
2812                         } else {
2813                                 gatekeeper_disable = 0;
2814                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper) - 1);
2815                         }
2816                 } else if (!strcasecmp(v->name, "secret")) {
2817                         strncpy(secret, v->value, sizeof(secret) - 1);
2818                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
2819                         gkroute = ast_true(v->value);
2820                 } else if (!strcasecmp(v->name, "context")) {
2821                         strncpy(default_context, v->value, sizeof(default_context) - 1);
2822                         ast_verbose(VERBOSE_PREFIX_2 "Setting default context to %s\n", default_context);
2823                 } else if (!strcasecmp(v->name, "UserByAlias")) {
2824                         userbyalias = ast_true(v->value);
2825                 } else if (!strcasecmp(v->name, "AcceptAnonymous")) {
2826                         acceptAnonymous = ast_true(v->value);
2827                 } else if (!update_common_options(v, &global_options)) {
2828                         /* dummy */
2829                 }
2830         }
2831         if (!global_options.dtmfmode)
2832                 global_options.dtmfmode = H323_DTMF_RFC2833;
2833
2834         for (cat = ast_category_browse(cfg, NULL); cat; cat = ast_category_browse(cfg, cat)) {
2835                 if (strcasecmp(cat, "general")) {
2836                         utype = ast_variable_retrieve(cfg, cat, "type");
2837                         if (utype) {
2838                                 is_user = is_peer = is_alias = 0;
2839                                 if (!strcasecmp(utype, "user"))
2840                                         is_user = 1;
2841                                 else if (!strcasecmp(utype, "peer"))
2842                                         is_peer = 1;
2843                                 else if (!strcasecmp(utype, "friend"))
2844                                         is_user = is_peer = 1;
2845                                 else if (!strcasecmp(utype, "h323") || !strcasecmp(utype, "alias"))
2846                                         is_alias = 1;
2847                                 else {
2848                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
2849                                         continue;
2850                                 }
2851                                 if (is_user) {
2852                                         user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
2853                                         if (user) {
2854                                                 ASTOBJ_CONTAINER_LINK(&userl, user);
2855                                                 ASTOBJ_UNREF(user, oh323_destroy_user);
2856                                         }
2857                                 }
2858                                 if (is_peer) {
2859                                         peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
2860                                         if (peer) {
2861                                                 ASTOBJ_CONTAINER_LINK(&peerl, peer);
2862                                                 ASTOBJ_UNREF(peer, oh323_destroy_peer);
2863                                         }
2864                                 }
2865                                 if (is_alias) {
2866                                         alias = build_alias(cat, ast_variable_browse(cfg, cat), NULL, 0);
2867                                         if (alias) {
2868                                                 ASTOBJ_CONTAINER_LINK(&aliasl, alias);
2869                                                 ASTOBJ_UNREF(alias, oh323_destroy_alias);
2870                                         }
2871                                 }
2872                         } else {
2873                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
2874                         }
2875                 }
2876         }
2877         ast_config_destroy(cfg);
2878
2879         /* Register our H.323 aliases if any*/
2880         ASTOBJ_CONTAINER_WRLOCK(&aliasl);
2881         ASTOBJ_CONTAINER_TRAVERSE(&aliasl, 1, do {
2882                 ASTOBJ_RDLOCK(iterator);
2883                 if (h323_set_alias(iterator)) {
2884                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
2885                         ASTOBJ_UNLOCK(iterator);
2886                         continue;
2887                 }
2888                 ASTOBJ_UNLOCK(iterator);
2889         } while (0) );
2890         ASTOBJ_CONTAINER_UNLOCK(&aliasl);
2891
2892         /* Don't touch GK if nothing changed because URQ will drop all existing calls */
2893         gk_changed = 0;
2894         if (gatekeeper_disable != gk_disable)
2895                 gk_changed = is_reload;
2896         else if(!gatekeeper_disable && (gatekeeper_discover != gk_discover))
2897                 gk_changed = is_reload;
2898         else if(!gatekeeper_disable && (strncmp(_gatekeeper, gatekeeper, sizeof(_gatekeeper)) != 0))
2899                 gk_changed = is_reload;
2900         if (gk_changed) {
2901                 if(!gk_disable)
2902                         h323_gk_urq();
2903                 if (!gatekeeper_disable) {
2904                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
2905                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
2906                                 gatekeeper_disable = 1;
2907                         }
2908                 }
2909         }
2910         return 0;
2911 }
2912
2913 static void delete_users(void)
2914 {
2915         int pruned = 0;
2916
2917         /* Delete all users */
2918         ASTOBJ_CONTAINER_WRLOCK(&userl);
2919         ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
2920                 ASTOBJ_RDLOCK(iterator);
2921                 ASTOBJ_MARK(iterator);
2922                 ++pruned;
2923                 ASTOBJ_UNLOCK(iterator);
2924         } while (0) );
2925         if (pruned) {
2926                 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, oh323_destroy_user);
2927         }
2928         ASTOBJ_CONTAINER_UNLOCK(&userl);
2929
2930         ASTOBJ_CONTAINER_WRLOCK(&peerl);
2931         ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
2932                 ASTOBJ_RDLOCK(iterator);
2933                 ASTOBJ_MARK(iterator);
2934                 ASTOBJ_UNLOCK(iterator);
2935         } while (0) );
2936         ASTOBJ_CONTAINER_UNLOCK(&peerl);
2937 }
2938
2939 static void delete_aliases(void)
2940 {
2941         int pruned = 0;
2942
2943         /* Delete all aliases */
2944         ASTOBJ_CONTAINER_WRLOCK(&aliasl);
2945         ASTOBJ_CONTAINER_TRAVERSE(&aliasl, 1, do {
2946                 ASTOBJ_RDLOCK(iterator);
2947                 ASTOBJ_MARK(iterator);
2948                 ++pruned;
2949                 ASTOBJ_UNLOCK(iterator);
2950         } while (0) );
2951         if (pruned) {
2952                 ASTOBJ_CONTAINER_PRUNE_MARKED(&aliasl, oh323_destroy_alias);
2953         }
2954         ASTOBJ_CONTAINER_UNLOCK(&aliasl);
2955 }
2956
2957 static void prune_peers(void)
2958 {
2959         /* Prune peers who still are supposed to be deleted */
2960         ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, oh323_destroy_peer);
2961 }
2962
2963 static int h323_reload(int fd, int argc, char *argv[])
2964 {
2965         ast_mutex_lock(&h323_reload_lock);
2966         if (h323_reloading) {
2967                 ast_verbose("Previous H.323 reload not yet done\n");
2968         } else {
2969                 h323_reloading = 1;
2970         }
2971         ast_mutex_unlock(&h323_reload_lock);
2972         restart_monitor();
2973         return 0;
2974 }
2975
2976 static int h323_do_reload(void)
2977 {
2978         delete_users();
2979         delete_aliases();
2980         prune_peers();
2981         reload_config(1);
2982         return 0;
2983 }
2984
2985 static int reload(void)
2986 {
2987         return h323_reload(0, 0, NULL);
2988 }
2989
2990 static struct ast_cli_entry cli_h323_reload_deprecated =
2991         { { "h.323", "reload", NULL },
2992         h323_reload, "Reload H.323 configuration",
2993         h323_reload_usage
2994 };
2995
2996 static struct ast_cli_entry cli_h323_reload =
2997         { { "h323", "reload", NULL },
2998         h323_reload, "Reload H.323 configuration",
2999         h323_reload_usage, NULL, &cli_h323_reload_deprecated
3000 };
3001
3002 static enum ast_rtp_get_result oh323_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
3003 {
3004         struct oh323_pvt *pvt;
3005         enum ast_rtp_get_result res = AST_RTP_GET_FAILED;
3006
3007         if (!(pvt = (struct oh323_pvt *)chan->tech_pvt))
3008                 return res;
3009
3010         ast_mutex_lock(&pvt->lock);
3011         if (pvt->rtp && pvt->options.bridge) {
3012                 *rtp = pvt->rtp;
3013                 res = AST_RTP_TRY_NATIVE;
3014         }
3015         ast_mutex_unlock(&pvt->lock);
3016
3017         return res;
3018 }
3019
3020 static enum ast_rtp_get_result oh323_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
3021 {
3022         return AST_RTP_GET_FAILED;
3023 }
3024
3025 static char *convertcap(int cap)
3026 {
3027         switch (cap) {
3028         case AST_FORMAT_G723_1:
3029                 return "G.723";
3030         case AST_FORMAT_GSM:
3031                 return "GSM";
3032         case AST_FORMAT_ULAW:
3033                 return "ULAW";
3034         case AST_FORMAT_ALAW:
3035                 return "ALAW";
3036         case AST_FORMAT_ADPCM:
3037                 return "G.728";
3038         case AST_FORMAT_G729A:
3039                 return "G.729";
3040         case AST_FORMAT_SPEEX:
3041                 return "SPEEX";
3042         case AST_FORMAT_ILBC:
3043                 return "ILBC";
3044         default:
3045                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
3046                 return NULL;
3047         }
3048 }
3049
3050 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
3051 {
3052         /* XXX Deal with Video */
3053         struct oh323_pvt *pvt;
3054         struct sockaddr_in them;
3055         struct sockaddr_in us;
3056         char *mode;
3057
3058         if (!rtp) {
3059                 return 0;
3060         }
3061
3062         mode = convertcap(chan->writeformat);
3063         pvt = (struct oh323_pvt *) chan->tech_pvt;
3064         if (!pvt) {
3065                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
3066                 return -1;
3067         }
3068         ast_rtp_get_peer(rtp, &them);
3069         ast_rtp_get_us(rtp, &us);
3070 #if 0   /* Native bridge still isn't ready */
3071         h323_native_bridge(pvt->cd.call_token, ast_inet_ntoa(them.sin_addr), mode);
3072 #endif
3073         return 0;
3074 }
3075
3076 static struct ast_rtp_protocol oh323_rtp = {
3077         .type = "H323",
3078         .get_rtp_info = oh323_get_rtp_peer,
3079         .get_vrtp_info = oh323_get_vrtp_peer,
3080         .set_rtp_peer = oh323_set_rtp_peer,
3081 };
3082
3083 static enum ast_module_load_result load_module(void)
3084 {
3085         int res;
3086
3087         h323debug = 0;
3088         sched = sched_context_create();
3089         if (!sched) {
3090                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
3091                 return AST_MODULE_LOAD_FAILURE;
3092         }
3093         io = io_context_create();
3094         if (!io) {
3095                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
3096                 return AST_MODULE_LOAD_FAILURE;
3097         }
3098         ast_cli_register(&cli_h323_reload);
3099         ASTOBJ_CONTAINER_INIT(&userl);
3100         ASTOBJ_CONTAINER_INIT(&peerl);
3101         ASTOBJ_CONTAINER_INIT(&aliasl);
3102         res = reload_config(0);
3103         if (res) {
3104                 ast_cli_unregister(&cli_h323_reload);
3105                 io_context_destroy(io);
3106                 sched_context_destroy(sched);
3107                 ASTOBJ_CONTAINER_DESTROY(&userl);
3108                 ASTOBJ_CONTAINER_DESTROY(&peerl);
3109                 ASTOBJ_CONTAINER_DESTROY(&aliasl);
3110                 return /*AST_MODULE_LOAD_DECLINE*/AST_MODULE_LOAD_FAILURE;
3111         } else {
3112                 /* Make sure we can register our channel type */
3113                 if (ast_channel_register(&oh323_tech)) {
3114                         ast_log(LOG_ERROR, "Unable to register channel class 'H323'\n");
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                 ast_cli_register_multiple(cli_h323, sizeof(cli_h323) / sizeof(struct ast_cli_entry));
3130
3131                 ast_rtp_proto_register(&oh323_rtp);
3132
3133                 /* Register our callback functions */
3134                 h323_callback_register(setup_incoming_call,
3135                                                 setup_outgoing_call,
3136                                                 external_rtp_create,
3137                                                 setup_rtp_connection,
3138                                                 cleanup_connection,
3139                                                 chan_ringing,
3140                                                 connection_made,
3141                                                 receive_digit,
3142                                                 answer_call,
3143                                                 progress,
3144                                                 set_dtmf_payload,
3145                                                 hangup_connection,
3146                                                 set_local_capabilities,
3147                                                 set_peer_capabilities);
3148                 /* start the h.323 listener */
3149                 if (h323_start_listener(h323_signalling_port, bindaddr)) {
3150                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
3151                         ast_rtp_proto_unregister(&oh323_rtp);
3152                         ast_cli_unregister_multiple(cli_h323, sizeof(cli_h323) / sizeof(struct ast_cli_entry));
3153                         ast_cli_unregister(&cli_h323_reload);
3154                         h323_end_process();
3155                         io_context_destroy(io);
3156                         sched_context_destroy(sched);
3157
3158                         ASTOBJ_CONTAINER_DESTROYALL(&userl, oh323_destroy_user);
3159                         ASTOBJ_CONTAINER_DESTROY(&userl);
3160                         ASTOBJ_CONTAINER_DESTROYALL(&peerl, oh323_destroy_peer);
3161                         ASTOBJ_CONTAINER_DESTROY(&peerl);
3162                         ASTOBJ_CONTAINER_DESTROYALL(&aliasl, oh323_destroy_alias);
3163                         ASTOBJ_CONTAINER_DESTROY(&aliasl);
3164
3165                         return AST_MODULE_LOAD_FAILURE;
3166                 }
3167                 /* Possibly register with a GK */
3168                 if (!gatekeeper_disable) {
3169                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
3170                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
3171                                 gatekeeper_disable = 1;
3172                                 res = AST_MODULE_LOAD_SUCCESS;
3173                         }
3174                 }
3175                 /* And start the monitor for the first time */
3176                 restart_monitor();
3177         }
3178         return res;
3179 }
3180
3181 static int unload_module(void)
3182 {
3183         struct oh323_pvt *p, *pl;
3184
3185         /* unregister commands */
3186         ast_cli_unregister_multiple(cli_h323, sizeof(cli_h323) / sizeof(struct ast_cli_entry));
3187         ast_cli_unregister(&cli_h323_reload);
3188
3189         ast_channel_unregister(&oh323_tech);
3190         ast_rtp_proto_unregister(&oh323_rtp);
3191
3192         if (!ast_mutex_lock(&iflock)) {
3193                 /* hangup all interfaces if they have an owner */
3194                 p = iflist;
3195                 while(p) {
3196                         if (p->owner) {
3197                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
3198                         }
3199                         p = p->next;
3200                 }
3201                 iflist = NULL;
3202                 ast_mutex_unlock(&iflock);
3203         } else {
3204                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
3205                 return -1;
3206         }
3207         if (!ast_mutex_lock(&monlock)) {
3208                 if ((monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
3209                         /* this causes a seg, anyone know why? */
3210                         if (monitor_thread != pthread_self())
3211                                 pthread_cancel(monitor_thread);
3212                         pthread_kill(monitor_thread, SIGURG);
3213                         pthread_join(monitor_thread, NULL);
3214                 }
3215                 monitor_thread = AST_PTHREADT_STOP;
3216                 ast_mutex_unlock(&monlock);
3217         } else {
3218                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
3219                 return -1;
3220         }
3221         if (!ast_mutex_lock(&iflock)) {
3222                 /* destroy all the interfaces and free their memory */
3223                 p = iflist;
3224                 while(p) {
3225                         pl = p;
3226                         p = p->next;
3227                         /* free associated memory */
3228                         ast_mutex_destroy(&pl->lock);
3229                         free(pl);
3230                 }
3231                 iflist = NULL;
3232                 ast_mutex_unlock(&iflock);
3233         } else {
3234                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
3235                 return -1;
3236         }
3237         if (!gatekeeper_disable)
3238                 h323_gk_urq();
3239         h323_end_process();
3240         io_context_destroy(io);
3241         sched_context_destroy(sched);
3242
3243         ASTOBJ_CONTAINER_DESTROYALL(&userl, oh323_destroy_user);
3244         ASTOBJ_CONTAINER_DESTROY(&userl);
3245         ASTOBJ_CONTAINER_DESTROYALL(&peerl, oh323_destroy_peer);
3246         ASTOBJ_CONTAINER_DESTROY(&peerl);
3247         ASTOBJ_CONTAINER_DESTROYALL(&aliasl, oh323_destroy_alias);
3248         ASTOBJ_CONTAINER_DESTROY(&aliasl);
3249
3250         return 0;
3251 }
3252
3253 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "The NuFone Network's OpenH323 Channel Driver",
3254                 .load = load_module,
3255                 .unload = unload_module,
3256                 .reload = reload,
3257 );