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