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