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