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