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