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