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