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