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