chan_unistim: Unlock mutex in rare OOM condition.
[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_assigned_ids *assignedids, 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, ast_channel_readformat(c));
359                 ast_set_write_format(c, ast_channel_writeformat(c));
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, ast_channel_readformat(pvt->owner));
800                                 ast_set_write_format(pvt->owner,ast_channel_writeformat(pvt->owner));
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),
867                                 ast_getformatname_multiple(tmp, sizeof(tmp), ast_channel_nativeformats(c)),
868                                 ast_getformatname(ast_channel_readformat(c)),
869                                 ast_getformatname(ast_channel_writeformat(c)));
870                         return 0;
871                 }
872         }
873         if (pvt) {
874                 ast_mutex_lock(&pvt->lock);
875                 if (pvt->rtp && !pvt->recvonly)
876                         res = ast_rtp_instance_write(pvt->rtp, frame);
877                 __oh323_update_info(c, pvt);
878                 ast_mutex_unlock(&pvt->lock);
879         }
880         return res;
881 }
882
883 static int oh323_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
884 {
885
886         struct oh323_pvt *pvt = (struct oh323_pvt *) ast_channel_tech_pvt(c);
887         char *token = (char *)NULL;
888         int res = -1;
889         int got_progress;
890
891         ast_mutex_lock(&pvt->lock);
892         token = (pvt->cd.call_token ? ast_strdup(pvt->cd.call_token) : NULL);
893         got_progress = pvt->got_progress;
894         if (condition == AST_CONTROL_PROGRESS)
895                 pvt->got_progress = 1;
896         else if ((condition == AST_CONTROL_BUSY) || (condition == AST_CONTROL_CONGESTION))
897                 pvt->alreadygone = 1;
898         ast_mutex_unlock(&pvt->lock);
899
900         if (h323debug)
901                 ast_debug(1, "OH323: Indicating %d on %s (%s)\n", condition, token, ast_channel_name(c));
902
903         switch(condition) {
904         case AST_CONTROL_RINGING:
905                 if (ast_channel_state(c) == AST_STATE_RING || ast_channel_state(c) == AST_STATE_RINGING) {
906                         h323_send_alerting(token);
907                         res = (got_progress ? 0 : -1);  /* Do not simulate any audio tones if we got PROGRESS message */
908                 }
909                 break;
910         case AST_CONTROL_PROGRESS:
911                 if (ast_channel_state(c) != AST_STATE_UP) {
912                         /* Do not send PROGRESS message more than once */
913                         if (!got_progress)
914                                 h323_send_progress(token);
915                         res = 0;
916                 }
917                 break;
918         case AST_CONTROL_BUSY:
919                 if (ast_channel_state(c) != AST_STATE_UP) {
920                         h323_answering_call(token, 1);
921                         ast_softhangup_nolock(c, AST_SOFTHANGUP_DEV);
922                         res = 0;
923                 }
924                 break;
925         case AST_CONTROL_INCOMPLETE:
926                 /* While h323 does support overlapped dialing, this channel driver does not
927                  * at this time.  Treat a response of Incomplete as if it were congestion.
928                  */
929         case AST_CONTROL_CONGESTION:
930                 if (ast_channel_state(c) != AST_STATE_UP) {
931                         h323_answering_call(token, 1);
932                         ast_softhangup_nolock(c, AST_SOFTHANGUP_DEV);
933                         res = 0;
934                 }
935                 break;
936         case AST_CONTROL_HOLD:
937                 h323_hold_call(token, 1);
938                 /* We should start MOH only if remote party isn't provide audio for us */
939                 ast_moh_start(c, data, NULL);
940                 res = 0;
941                 break;
942         case AST_CONTROL_UNHOLD:
943                 h323_hold_call(token, 0);
944                 ast_moh_stop(c);
945                 res = 0;
946                 break;
947         case AST_CONTROL_SRCUPDATE:
948                 ast_rtp_instance_update_source(pvt->rtp);
949                 res = 0;
950                 break;
951         case AST_CONTROL_SRCCHANGE:
952                 ast_rtp_instance_change_source(pvt->rtp);
953                 res = 0;
954                 break;
955         case AST_CONTROL_PROCEEDING:
956         case AST_CONTROL_PVT_CAUSE_CODE:
957         case -1:
958                 break;
959         default:
960                 ast_log(LOG_WARNING, "OH323: Don't know how to indicate condition %d on %s\n", condition, token);
961                 break;
962         }
963
964         if (h323debug)
965                 ast_debug(1, "OH323: Indicated %d on %s, res=%d\n", condition, token, res);
966         if (token)
967                 ast_free(token);
968         oh323_update_info(c);
969
970         return res;
971 }
972
973 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
974 {
975         struct oh323_pvt *pvt = (struct oh323_pvt *) ast_channel_tech_pvt(newchan);
976
977         ast_mutex_lock(&pvt->lock);
978         if (pvt->owner != oldchan) {
979                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, pvt->owner);
980                 return -1;
981         }
982         oh323_set_owner(pvt, newchan);
983         ast_mutex_unlock(&pvt->lock);
984         return 0;
985 }
986
987 static int __oh323_rtp_create(struct oh323_pvt *pvt)
988 {
989         struct ast_sockaddr our_addr;
990
991         if (pvt->rtp)
992                 return 0;
993
994         {
995                 struct ast_sockaddr tmp;
996
997                 ast_sockaddr_from_sin(&tmp, &bindaddr);
998                 if (ast_find_ourip(&our_addr, &tmp, AF_INET)) {
999                         ast_mutex_unlock(&pvt->lock);
1000                         ast_log(LOG_ERROR, "Unable to locate local IP address for RTP stream\n");
1001                         return -1;
1002                 }
1003         }
1004         our_addr.ss.ss_family = AF_INET;
1005         pvt->rtp = ast_rtp_instance_new("asterisk", sched, &our_addr, NULL);
1006         if (!pvt->rtp) {
1007                 ast_mutex_unlock(&pvt->lock);
1008                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1009                 return -1;
1010         }
1011         if (h323debug)
1012                 ast_debug(1, "Created RTP channel\n");
1013
1014         ast_rtp_instance_set_qos(pvt->rtp, tos, cos, "H323 RTP");
1015         ast_rtp_instance_set_channel_id(pvt->rtp, pvt->owner ? ast_channel_uniqueid(pvt->owner) : "");
1016
1017         if (h323debug)
1018                 ast_debug(1, "Setting NAT on RTP to %d\n", pvt->options.nat);
1019         ast_rtp_instance_set_prop(pvt->rtp, AST_RTP_PROPERTY_NAT, pvt->options.nat);
1020
1021         if (pvt->dtmf_pt[0] > 0)
1022                 ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(pvt->rtp), pvt->rtp, pvt->dtmf_pt[0], "audio", "telephone-event", 0);
1023         if (pvt->dtmf_pt[1] > 0)
1024                 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);
1025
1026         if (pvt->peercapability)
1027                 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(pvt->rtp), pvt->rtp, &pvt->peer_prefs);
1028
1029         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
1030                 ast_jb_configure(pvt->owner, &global_jbconf);
1031                 ast_channel_set_fd(pvt->owner, 0, ast_rtp_instance_fd(pvt->rtp, 0));
1032                 ast_channel_set_fd(pvt->owner, 1, ast_rtp_instance_fd(pvt->rtp, 1));
1033                 ast_queue_frame(pvt->owner, &ast_null_frame);   /* Tell Asterisk to apply changes */
1034                 ast_channel_unlock(pvt->owner);
1035         } else
1036                 pvt->update_rtp_info = 1;
1037
1038         return 0;
1039 }
1040
1041 /*! \brief Private structure should be locked on a call */
1042 static struct ast_channel *__oh323_new(struct oh323_pvt *pvt, int state, const char *host, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor)
1043 {
1044         struct ast_channel *ch;
1045         char *cid_num, *cid_name;
1046         h323_format fmt;
1047         struct ast_format tmpfmt;
1048
1049         if (!ast_strlen_zero(pvt->options.cid_num))
1050                 cid_num = pvt->options.cid_num;
1051         else
1052                 cid_num = pvt->cd.call_source_e164;
1053
1054         if (!ast_strlen_zero(pvt->options.cid_name))
1055                 cid_name = pvt->options.cid_name;
1056         else
1057                 cid_name = pvt->cd.call_source_name;
1058         
1059         /* Don't hold a oh323_pvt lock while we allocate a chanel */
1060         ast_mutex_unlock(&pvt->lock);
1061         ch = ast_channel_alloc(1, state, cid_num, cid_name, pvt->accountcode, pvt->exten, pvt->context, assignedids, requestor, pvt->amaflags, "H323/%s", host);
1062         /* Update usage counter */
1063         ast_module_ref(ast_module_info->self);
1064         ast_mutex_lock(&pvt->lock);
1065         if (ch) {
1066                 ast_channel_tech_set(ch, &oh323_tech);
1067                 if (!(fmt = pvt->jointcapability) && !(fmt = pvt->options.capability))
1068                         fmt = global_options.capability;
1069
1070                 ast_format_cap_from_old_bitfield(ast_channel_nativeformats(ch), fmt);
1071                 ast_codec_choose(&pvt->options.prefs, ast_channel_nativeformats(ch), 1, &tmpfmt)/* | (pvt->jointcapability & AST_FORMAT_VIDEO_MASK)*/;
1072
1073                 ast_format_cap_set(ast_channel_nativeformats(ch), &tmpfmt);
1074
1075                 pvt->nativeformats = ast_format_cap_to_old_bitfield(ast_channel_nativeformats(ch));
1076                 ast_best_codec(ast_channel_nativeformats(ch), &tmpfmt);
1077                 ast_format_copy(ast_channel_writeformat(ch), &tmpfmt);
1078                 ast_format_copy(ast_channel_rawwriteformat(ch), &tmpfmt);
1079                 ast_format_copy(ast_channel_readformat(ch), &tmpfmt);
1080                 ast_format_copy(ast_channel_rawreadformat(ch), &tmpfmt);
1081                 if (!pvt->rtp)
1082                         __oh323_rtp_create(pvt);
1083 #if 0
1084                 ast_channel_set_fd(ch, 0, ast_rtp_instance_fd(pvt->rtp, 0));
1085                 ast_channel_set_fd(ch, 1, ast_rtp_instance_fd(pvt->rtp, 1));
1086 #endif
1087 #ifdef VIDEO_SUPPORT
1088                 if (pvt->vrtp) {
1089                         ast_channel_set_fd(ch, 2, ast_rtp_instance_fd(pvt->vrtp, 0));
1090                         ast_channel_set_fd(ch, 3, ast_rtp_instance_fd(pvt->vrtp, 1));
1091                 }
1092 #endif
1093 #ifdef T38_SUPPORT
1094                 if (pvt->udptl) {
1095                         ast_channel_set_fd(ch, 4, ast_udptl_fd(pvt->udptl));
1096                 }
1097 #endif
1098                 if (state == AST_STATE_RING) {
1099                         ast_channel_rings_set(ch, 1);
1100                 }
1101                 /* Allocate dsp for in-band DTMF support */
1102                 if (pvt->options.dtmfmode & H323_DTMF_INBAND) {
1103                         pvt->vad = ast_dsp_new();
1104                         ast_dsp_set_features(pvt->vad, DSP_FEATURE_DIGIT_DETECT);
1105                 }
1106                 /* Register channel functions. */
1107                 ast_channel_tech_pvt_set(ch, pvt);
1108                 /* Set the owner of this channel */
1109                 oh323_set_owner(pvt, ch);
1110
1111                 ast_channel_context_set(ch, pvt->context);
1112                 ast_channel_exten_set(ch, pvt->exten);
1113                 ast_channel_priority_set(ch, 1);
1114                 if (!ast_strlen_zero(pvt->accountcode)) {
1115                         ast_channel_accountcode_set(ch, pvt->accountcode);
1116                 }
1117                 if (pvt->amaflags) {
1118                         ast_channel_amaflags_set(ch, pvt->amaflags);
1119                 }
1120
1121                 /* Don't use ast_set_callerid() here because it will
1122                  * generate a needless NewCallerID event */
1123                 if (!ast_strlen_zero(cid_num)) {
1124                         ast_channel_caller(ch)->ani.number.valid = 1;
1125                         ast_channel_caller(ch)->ani.number.str = ast_strdup(cid_num);
1126                 }
1127
1128                 if (pvt->cd.redirect_reason >= 0) {
1129                         ast_channel_redirecting(ch)->from.number.valid = 1;
1130                         ast_channel_redirecting(ch)->from.number.str = ast_strdup(pvt->cd.redirect_number);
1131                         pbx_builtin_setvar_helper(ch, "PRIREDIRECTREASON", redirectingreason2str(pvt->cd.redirect_reason));
1132                 }
1133                 ast_channel_caller(ch)->id.name.presentation = pvt->cd.presentation;
1134                 ast_channel_caller(ch)->id.number.presentation = pvt->cd.presentation;
1135                 ast_channel_caller(ch)->id.number.plan = pvt->cd.type_of_number;
1136
1137                 if (!ast_strlen_zero(pvt->exten) && strcmp(pvt->exten, "s")) {
1138                         ast_channel_dialed(ch)->number.str = ast_strdup(pvt->exten);
1139                 }
1140                 if (pvt->cd.transfer_capability >= 0)
1141                         ast_channel_transfercapability_set(ch, pvt->cd.transfer_capability);
1142                 ast_channel_unlock(ch);
1143                 if (state != AST_STATE_DOWN) {
1144                         if (ast_pbx_start(ch)) {
1145                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(ch));
1146                                 ast_hangup(ch);
1147                                 ch = NULL;
1148                         }
1149                 }
1150         } else {
1151                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1152         }
1153         return ch;
1154 }
1155
1156 static struct oh323_pvt *oh323_alloc(int callid)
1157 {
1158         struct oh323_pvt *pvt;
1159
1160         pvt = ast_calloc(1, sizeof(*pvt));
1161         if (!pvt) {
1162                 ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
1163                 return NULL;
1164         }
1165         pvt->cd.redirect_reason = -1;
1166         pvt->cd.transfer_capability = -1;
1167         /* Ensure the call token is allocated for outgoing call */
1168         if (!callid) {
1169                 if ((pvt->cd).call_token == NULL) {
1170                         (pvt->cd).call_token = ast_calloc(1, 128);
1171                 }
1172                 if (!pvt->cd.call_token) {
1173                         ast_log(LOG_ERROR, "Not enough memory to alocate call token\n");
1174                         ast_rtp_instance_destroy(pvt->rtp);
1175                         ast_free(pvt);
1176                         return NULL;
1177                 }
1178                 memset((char *)(pvt->cd).call_token, 0, 128);
1179                 pvt->cd.call_reference = callid;
1180         }
1181         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1182         pvt->jointcapability = pvt->options.capability;
1183         if (pvt->options.dtmfmode & (H323_DTMF_RFC2833 | H323_DTMF_CISCO)) {
1184                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1185         } else {
1186                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1187         }
1188         ast_copy_string(pvt->context, default_context, sizeof(pvt->context));
1189         pvt->newstate = pvt->newcontrol = pvt->newdigit = pvt->update_rtp_info = pvt->DTMFsched = -1;
1190         ast_mutex_init(&pvt->lock);
1191         /* Add to interface list */
1192         ast_mutex_lock(&iflock);
1193         pvt->next = iflist;
1194         iflist = pvt;
1195         ast_mutex_unlock(&iflock);
1196         return pvt;
1197 }
1198
1199 static void oh323_set_owner(struct oh323_pvt *pvt, struct ast_channel *chan)
1200 {
1201         pvt->owner = chan;
1202         if (pvt->rtp) {
1203                 ast_rtp_instance_set_channel_id(pvt->rtp, chan ? ast_channel_uniqueid(chan) : "");
1204         }
1205 }
1206
1207 static struct oh323_pvt *find_call_locked(int call_reference, const char *token)
1208 {
1209         struct oh323_pvt *pvt;
1210
1211         ast_mutex_lock(&iflock);
1212         pvt = iflist;
1213         while(pvt) {
1214                 if (!pvt->needdestroy && ((signed int)pvt->cd.call_reference == call_reference)) {
1215                         /* Found the call */
1216                         if ((token != NULL) && (pvt->cd.call_token != NULL) && (!strcmp(pvt->cd.call_token, token))) {
1217                                 ast_mutex_lock(&pvt->lock);
1218                                 ast_mutex_unlock(&iflock);
1219                                 return pvt;
1220                         } else if (token == NULL) {
1221                                 ast_log(LOG_WARNING, "Call Token is NULL\n");
1222                                 ast_mutex_lock(&pvt->lock);
1223                                 ast_mutex_unlock(&iflock);
1224                                 return pvt;
1225                         }
1226                 }
1227                 pvt = pvt->next;
1228         }
1229         ast_mutex_unlock(&iflock);
1230         return NULL;
1231 }
1232
1233 static int update_state(struct oh323_pvt *pvt, int state, int signal)
1234 {
1235         if (!pvt)
1236                 return 0;
1237         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
1238                 if (state >= 0)
1239                         ast_setstate(pvt->owner, state);
1240                 if (signal >= 0)
1241                         ast_queue_control(pvt->owner, signal);
1242                 ast_channel_unlock(pvt->owner);
1243                 return 1;
1244         }
1245         else {
1246                 if (state >= 0)
1247                         pvt->newstate = state;
1248                 if (signal >= 0)
1249                         pvt->newcontrol = signal;
1250                 return 0;
1251         }
1252 }
1253
1254 static struct oh323_alias *build_alias(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
1255 {
1256         struct oh323_alias *alias;
1257         int found = 0;
1258
1259         alias = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&aliasl, name, name, 0, 0, strcasecmp);
1260
1261         if (alias)
1262                 found++;
1263         else {
1264                 if (!(alias = ast_calloc(1, sizeof(*alias))))
1265                         return NULL;
1266                 ASTOBJ_INIT(alias);
1267         }
1268         if (!found && name)
1269                 ast_copy_string(alias->name, name, sizeof(alias->name));
1270         for (; v || ((v = alt) && !(alt = NULL)); v = v->next) {
1271                 if (!strcasecmp(v->name, "e164")) {
1272                         ast_copy_string(alias->e164, v->value, sizeof(alias->e164));
1273                 } else if (!strcasecmp(v->name, "prefix")) {
1274                         ast_copy_string(alias->prefix, v->value, sizeof(alias->prefix));
1275                 } else if (!strcasecmp(v->name, "context")) {
1276                         ast_copy_string(alias->context, v->value, sizeof(alias->context));
1277                 } else if (!strcasecmp(v->name, "secret")) {
1278                         ast_copy_string(alias->secret, v->value, sizeof(alias->secret));
1279                 } else {
1280                         if (strcasecmp(v->value, "h323")) {
1281                                 ast_log(LOG_WARNING, "Keyword %s does not make sense in type=h323\n", v->name);
1282                         }
1283                 }
1284         }
1285         ASTOBJ_UNMARK(alias);
1286         return alias;
1287 }
1288
1289 static struct oh323_alias *realtime_alias(const char *alias)
1290 {
1291         struct ast_variable *var, *tmp;
1292         struct oh323_alias *a;
1293
1294         var = ast_load_realtime("h323", "name", alias, SENTINEL);
1295
1296         if (!var)
1297                 return NULL;
1298
1299         for (tmp = var; tmp; tmp = tmp->next) {
1300                 if (!strcasecmp(tmp->name, "type") &&
1301                 !(!strcasecmp(tmp->value, "alias") || !strcasecmp(tmp->value, "h323"))) {
1302                         ast_variables_destroy(var);
1303                         return NULL;
1304                 }
1305         }
1306
1307         a = build_alias(alias, var, NULL, 1);
1308
1309         ast_variables_destroy(var);
1310
1311         return a;
1312 }
1313
1314 static int h323_parse_allow_disallow(struct ast_codec_pref *pref, h323_format *formats, const char *list, int allowing)
1315 {
1316         int res;
1317         struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
1318         if (!cap) {
1319                 return 1;
1320         }
1321
1322         ast_format_cap_from_old_bitfield(cap, *formats);
1323         res = ast_parse_allow_disallow(pref, cap, list, allowing);
1324         *formats = ast_format_cap_to_old_bitfield(cap);
1325         cap = ast_format_cap_destroy(cap);
1326         return res;
1327
1328 }
1329
1330 static int update_common_options(struct ast_variable *v, struct call_options *options)
1331 {
1332         int tmp = 0;
1333         char *val, *opt;
1334
1335         if (!strcasecmp(v->name, "allow")) {
1336                 h323_parse_allow_disallow(&options->prefs, &options->capability, v->value, 1);
1337         } else if (!strcasecmp(v->name, "autoframing")) {
1338                 options->autoframing = ast_true(v->value);
1339         } else if (!strcasecmp(v->name, "disallow")) {
1340                 h323_parse_allow_disallow(&options->prefs, &options->capability, v->value, 0);
1341         } else if (!strcasecmp(v->name, "dtmfmode")) {
1342                 val = ast_strdupa(v->value);
1343                 if ((opt = strchr(val, ':')) != (char *)NULL) {
1344                         *opt++ = '\0';
1345                         tmp = atoi(opt);
1346                 }
1347                 if (!strcasecmp(v->value, "inband")) {
1348                         options->dtmfmode |= H323_DTMF_INBAND;
1349                 } else if (!strcasecmp(val, "rfc2833")) {
1350                         options->dtmfmode |= H323_DTMF_RFC2833;
1351                         if (!opt) {
1352                                 options->dtmfcodec[0] = H323_DTMF_RFC2833_PT;
1353                         } else if ((tmp >= 96) && (tmp < 128)) {
1354                                 options->dtmfcodec[0] = tmp;
1355                         } else {
1356                                 options->dtmfcodec[0] = H323_DTMF_RFC2833_PT;
1357                                 ast_log(LOG_WARNING, "Unknown rfc2833 payload %s specified at line %d, using default %d\n", opt, v->lineno, options->dtmfcodec[0]);
1358                         }
1359                 } else if (!strcasecmp(val, "cisco")) {
1360                         options->dtmfmode |= H323_DTMF_CISCO;
1361                         if (!opt) {
1362                                 options->dtmfcodec[1] = H323_DTMF_CISCO_PT;
1363                         } else if ((tmp >= 96) && (tmp < 128)) {
1364                                 options->dtmfcodec[1] = tmp;
1365                         } else {
1366                                 options->dtmfcodec[1] = H323_DTMF_CISCO_PT;
1367                                 ast_log(LOG_WARNING, "Unknown Cisco DTMF payload %s specified at line %d, using default %d\n", opt, v->lineno, options->dtmfcodec[1]);
1368                         }
1369                 } else if (!strcasecmp(v->value, "h245-signal")) {
1370                         options->dtmfmode |= H323_DTMF_SIGNAL;
1371                 } else {
1372                         ast_log(LOG_WARNING, "Unknown dtmf mode '%s' at line %d\n", v->value, v->lineno);
1373                 }
1374         } else if (!strcasecmp(v->name, "dtmfcodec")) {
1375                 ast_log(LOG_NOTICE, "Option %s at line %d is deprecated. Use dtmfmode=rfc2833[:<payload>] instead.\n", v->name, v->lineno);
1376                 tmp = atoi(v->value);
1377                 if (tmp < 96)
1378                         ast_log(LOG_WARNING, "Invalid %s value %s at line %d\n", v->name, v->value, v->lineno);
1379                 else
1380                         options->dtmfcodec[0] = tmp;
1381         } else if (!strcasecmp(v->name, "bridge")) {
1382                 options->bridge = ast_true(v->value);
1383         } else if (!strcasecmp(v->name, "nat")) {
1384                 options->nat = ast_true(v->value);
1385         } else if (!strcasecmp(v->name, "fastStart")) {
1386                 options->fastStart = ast_true(v->value);
1387         } else if (!strcasecmp(v->name, "h245Tunneling")) {
1388                 options->h245Tunneling = ast_true(v->value);
1389         } else if (!strcasecmp(v->name, "silenceSuppression")) {
1390                 options->silenceSuppression = ast_true(v->value);
1391         } else if (!strcasecmp(v->name, "progress_setup")) {
1392                 tmp = atoi(v->value);
1393                 if ((tmp != 0) && (tmp != 1) && (tmp != 3) && (tmp != 8)) {
1394                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d, assuming 0\n", v->value, v->name, v->lineno);
1395                         tmp = 0;
1396                 }
1397                 options->progress_setup = tmp;
1398         } else if (!strcasecmp(v->name, "progress_alert")) {
1399                 tmp = atoi(v->value);
1400                 if ((tmp != 0) && (tmp != 1) && (tmp != 8)) {
1401                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d, assuming 0\n", v->value, v->name, v->lineno);
1402                         tmp = 0;
1403                 }
1404                 options->progress_alert = tmp;
1405         } else if (!strcasecmp(v->name, "progress_audio")) {
1406                 options->progress_audio = ast_true(v->value);
1407         } else if (!strcasecmp(v->name, "callerid")) {
1408                 ast_callerid_split(v->value, options->cid_name, sizeof(options->cid_name), options->cid_num, sizeof(options->cid_num));
1409         } else if (!strcasecmp(v->name, "fullname")) {
1410                 ast_copy_string(options->cid_name, v->value, sizeof(options->cid_name));
1411         } else if (!strcasecmp(v->name, "cid_number")) {
1412                 ast_copy_string(options->cid_num, v->value, sizeof(options->cid_num));
1413         } else if (!strcasecmp(v->name, "tunneling")) {
1414                 if (!strcasecmp(v->value, "none"))
1415                         options->tunnelOptions = 0;
1416                 else if (!strcasecmp(v->value, "cisco"))
1417                         options->tunnelOptions |= H323_TUNNEL_CISCO;
1418                 else if (!strcasecmp(v->value, "qsig"))
1419                         options->tunnelOptions |= H323_TUNNEL_QSIG;
1420                 else
1421                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d\n", v->value, v->name, v->lineno);
1422         } else if (!strcasecmp(v->name, "hold")) {
1423                 if (!strcasecmp(v->value, "none"))
1424                         options->holdHandling = ~0;
1425                 else if (!strcasecmp(v->value, "notify"))
1426                         options->holdHandling |= H323_HOLD_NOTIFY;
1427                 else if (!strcasecmp(v->value, "q931only"))
1428                         options->holdHandling |= H323_HOLD_NOTIFY | H323_HOLD_Q931ONLY;
1429                 else if (!strcasecmp(v->value, "h450"))
1430                         options->holdHandling |= H323_HOLD_H450;
1431                 else
1432                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d\n", v->value, v->name, v->lineno);
1433         } else
1434                 return 1;
1435
1436         return 0;
1437 }
1438
1439 static struct oh323_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
1440 {
1441         struct oh323_user *user;
1442         struct ast_ha *oldha;
1443         int found = 0;
1444         int format;
1445
1446         user = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&userl, name, name, 0, 0, strcmp);
1447
1448         if (user)
1449                 found++;
1450         else {
1451                 if (!(user = ast_calloc(1, sizeof(*user))))
1452                         return NULL;
1453                 ASTOBJ_INIT(user);
1454         }
1455         oldha = user->ha;
1456         user->ha = (struct ast_ha *)NULL;
1457         memcpy(&user->options, &global_options, sizeof(user->options));
1458         user->options.dtmfmode = 0;
1459         user->options.holdHandling = 0;
1460         /* Set default context */
1461         ast_copy_string(user->context, default_context, sizeof(user->context));
1462         if (!found) {
1463                 ast_copy_string(user->name, name, sizeof(user->name));
1464         }
1465
1466 #if 0 /* XXX Port channel variables functionality from chan_sip XXX */
1467         if (user->chanvars) {
1468                 ast_variables_destroy(user->chanvars);
1469                 user->chanvars = NULL;
1470         }
1471 #endif
1472
1473         for (; v || ((v = alt) && !(alt = NULL)); v = v->next) {
1474                 if (!update_common_options(v, &user->options))
1475                         continue;
1476                 if (!strcasecmp(v->name, "context")) {
1477                         ast_copy_string(user->context, v->value, sizeof(user->context));
1478                 } else if (!strcasecmp(v->name, "secret")) {
1479                         ast_copy_string(user->secret, v->value, sizeof(user->secret));
1480                 } else if (!strcasecmp(v->name, "accountcode")) {
1481                         ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
1482                 } else if (!strcasecmp(v->name, "host")) {
1483                         if (!strcasecmp(v->value, "dynamic")) {
1484                                 ast_log(LOG_ERROR, "A dynamic host on a type=user does not make any sense\n");
1485                                 ASTOBJ_UNREF(user, oh323_destroy_user);
1486                                 return NULL;
1487                         } else {
1488                                 struct ast_sockaddr tmp;
1489
1490                                 tmp.ss.ss_family = AF_INET;
1491                                 if (ast_get_ip(&tmp, v->value)) {
1492                                         ASTOBJ_UNREF(user, oh323_destroy_user);
1493                                         return NULL;
1494                                 }
1495                                 ast_sockaddr_to_sin(&tmp, &user->addr);
1496                         }
1497                         /* Let us know we need to use ip authentication */
1498                         user->host = 1;
1499                 } else if (!strcasecmp(v->name, "amaflags")) {
1500                         format = ast_channel_string2amaflag(v->value);
1501                         if (format < 0) {
1502                                 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
1503                         } else {
1504                                 user->amaflags = format;
1505                         }
1506                 } else if (!strcasecmp(v->name, "permit") ||
1507                                         !strcasecmp(v->name, "deny")) {
1508                         int ha_error = 0;
1509
1510                         user->ha = ast_append_ha(v->name, v->value, user->ha, &ha_error);
1511                         if (ha_error)
1512                                 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
1513                 }
1514         }
1515         if (!user->options.dtmfmode)
1516                 user->options.dtmfmode = global_options.dtmfmode;
1517         if (user->options.holdHandling == ~0)
1518                 user->options.holdHandling = 0;
1519         else if (!user->options.holdHandling)
1520                 user->options.holdHandling = global_options.holdHandling;
1521         ASTOBJ_UNMARK(user);
1522         ast_free_ha(oldha);
1523         return user;
1524 }
1525
1526 static struct oh323_user *realtime_user(const call_details_t *cd)
1527 {
1528         struct ast_variable *var, *tmp;
1529         struct oh323_user *user;
1530         const char *username;
1531
1532         if (userbyalias)
1533                 var = ast_load_realtime("h323", "name", username = cd->call_source_aliases, SENTINEL);
1534         else {
1535                 username = (char *)NULL;
1536                 var = ast_load_realtime("h323", "host", cd->sourceIp, SENTINEL);
1537         }
1538
1539         if (!var)
1540                 return NULL;
1541
1542         for (tmp = var; tmp; tmp = tmp->next) {
1543                 if (!strcasecmp(tmp->name, "type") &&
1544                 !(!strcasecmp(tmp->value, "user") || !strcasecmp(tmp->value, "friend"))) {
1545                         ast_variables_destroy(var);
1546                         return NULL;
1547                 } else if (!username && !strcasecmp(tmp->name, "name"))
1548                         username = tmp->value;
1549         }
1550
1551         if (!username) {
1552                 ast_log(LOG_WARNING, "Cannot determine user name for IP address %s\n", cd->sourceIp);
1553                 ast_variables_destroy(var);
1554                 return NULL;
1555         }
1556
1557         user = build_user(username, var, NULL, 1);
1558
1559         ast_variables_destroy(var);
1560
1561         return user;
1562 }
1563
1564 static struct oh323_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
1565 {
1566         struct oh323_peer *peer;
1567         struct ast_ha *oldha;
1568         int found = 0;
1569
1570         peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
1571
1572         if (peer)
1573                 found++;
1574         else {
1575                 if (!(peer = ast_calloc(1, sizeof(*peer))))
1576                         return NULL;
1577                 ASTOBJ_INIT(peer);
1578         }
1579         oldha = peer->ha;
1580         peer->ha = NULL;
1581         memcpy(&peer->options, &global_options, sizeof(peer->options));
1582         peer->options.dtmfmode = 0;
1583         peer->options.holdHandling = 0;
1584         peer->addr.sin_port = htons(h323_signalling_port);
1585         peer->addr.sin_family = AF_INET;
1586         if (!found && name)
1587                 ast_copy_string(peer->name, name, sizeof(peer->name));
1588
1589 #if 0 /* XXX Port channel variables functionality from chan_sip XXX */
1590         if (peer->chanvars) {
1591                 ast_variables_destroy(peer->chanvars);
1592                 peer->chanvars = NULL;
1593         }
1594 #endif
1595         /* Default settings for mailbox */
1596         peer->mailbox[0] = '\0';
1597
1598         for (; v || ((v = alt) && !(alt = NULL)); v = v->next) {
1599                 if (!update_common_options(v, &peer->options))
1600                         continue;
1601                 if (!strcasecmp(v->name, "host")) {
1602                         if (!strcasecmp(v->value, "dynamic")) {
1603                                 ast_log(LOG_ERROR, "Dynamic host configuration not implemented.\n");
1604                                 ASTOBJ_UNREF(peer, oh323_destroy_peer);
1605                                 return NULL;
1606                         }
1607                         {
1608                                 struct ast_sockaddr tmp;
1609
1610                                 tmp.ss.ss_family = AF_INET;
1611                                 if (ast_get_ip(&tmp, v->value)) {
1612                                         ast_log(LOG_ERROR, "Could not determine IP for %s\n", v->value);
1613                                         ASTOBJ_UNREF(peer, oh323_destroy_peer);
1614                                         return NULL;
1615                                 }
1616                                 ast_sockaddr_to_sin(&tmp, &peer->addr);
1617                         }
1618                 } else if (!strcasecmp(v->name, "port")) {
1619                         peer->addr.sin_port = htons(atoi(v->value));
1620                 } else if (!strcasecmp(v->name, "permit") ||
1621                                         !strcasecmp(v->name, "deny")) {
1622                         int ha_error = 0;
1623
1624                         peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
1625                         if (ha_error)
1626                                 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
1627                 } else if (!strcasecmp(v->name, "mailbox")) {
1628                         ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
1629                 } else if (!strcasecmp(v->name, "hasvoicemail")) {
1630                         if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
1631                                 /*
1632                                  * hasvoicemail is a users.conf legacy voicemail enable method.
1633                                  * hasvoicemail is only going to work for app_voicemail mailboxes.
1634                                  */
1635                                 if (strchr(name, '@')) {
1636                                         ast_copy_string(peer->mailbox, name, sizeof(peer->mailbox));
1637                                 } else {
1638                                         snprintf(peer->mailbox, sizeof(peer->mailbox), "%s@default", name);
1639                                 }
1640                         }
1641                 }
1642         }
1643         if (!peer->options.dtmfmode)
1644                 peer->options.dtmfmode = global_options.dtmfmode;
1645         if (peer->options.holdHandling == ~0)
1646                 peer->options.holdHandling = 0;
1647         else if (!peer->options.holdHandling)
1648                 peer->options.holdHandling = global_options.holdHandling;
1649         ASTOBJ_UNMARK(peer);
1650         ast_free_ha(oldha);
1651         return peer;
1652 }
1653
1654 static struct oh323_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1655 {
1656         struct oh323_peer *peer;
1657         struct ast_variable *var;
1658         struct ast_variable *tmp;
1659         const char *addr = NULL;
1660
1661         /* First check on peer name */
1662         if (peername)
1663                 var = ast_load_realtime("h323", "name", peername, SENTINEL);
1664         else if (sin) /* Then check on IP address for dynamic peers */
1665                 var = ast_load_realtime("h323", "host", addr = ast_inet_ntoa(sin->sin_addr), SENTINEL);
1666         else
1667                 return NULL;
1668
1669         if (!var)
1670                 return NULL;
1671
1672         for (tmp = var; tmp; tmp = tmp->next) {
1673                 /* If this is type=user, then skip this object. */
1674                 if (!strcasecmp(tmp->name, "type") &&
1675                                 !(!strcasecmp(tmp->value, "peer") || !strcasecmp(tmp->value, "friend"))) {
1676                         ast_variables_destroy(var);
1677                         return NULL;
1678                 } else if (!peername && !strcasecmp(tmp->name, "name")) {
1679                         peername = tmp->value;
1680                 }
1681         }
1682
1683         if (!peername) {        /* Did not find peer in realtime */
1684                 ast_log(LOG_WARNING, "Cannot determine peer name for IP address %s\n", addr);
1685                 ast_variables_destroy(var);
1686                 return NULL;
1687         }
1688
1689         /* Peer found in realtime, now build it in memory */
1690         peer = build_peer(peername, var, NULL, 1);
1691
1692         ast_variables_destroy(var);
1693
1694         return peer;
1695 }
1696
1697 static int oh323_addrcmp_str(struct in_addr inaddr, char *addr)
1698 {
1699         return strcmp(ast_inet_ntoa(inaddr), addr);
1700 }
1701
1702 static struct oh323_user *find_user(const call_details_t *cd, int realtime)
1703 {
1704         struct oh323_user *u;
1705
1706         if (userbyalias)
1707                 u = ASTOBJ_CONTAINER_FIND(&userl, cd->call_source_aliases);
1708         else
1709                 u = ASTOBJ_CONTAINER_FIND_FULL(&userl, cd->sourceIp, addr.sin_addr, 0, 0, oh323_addrcmp_str);
1710
1711         if (!u && realtime)
1712                 u = realtime_user(cd);
1713
1714         if (!u && h323debug)
1715                 ast_debug(1, "Could not find user by name %s or address %s\n", cd->call_source_aliases, cd->sourceIp);
1716
1717         return u;
1718 }
1719
1720 static int oh323_addrcmp(struct sockaddr_in addr, struct sockaddr_in *sin)
1721 {
1722         int res;
1723
1724         if (!sin)
1725                 res = -1;
1726         else
1727                 res = inaddrcmp(&addr , sin);
1728
1729         return res;
1730 }
1731
1732 static struct oh323_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1733 {
1734         struct oh323_peer *p;
1735
1736         if (peer)
1737                 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
1738         else
1739                 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, addr, 0, 0, oh323_addrcmp);
1740
1741         if (!p && realtime)
1742                 p = realtime_peer(peer, sin);
1743
1744         if (!p && h323debug)
1745                 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>"));
1746
1747         return p;
1748 }
1749
1750 static int create_addr(struct oh323_pvt *pvt, char *opeer)
1751 {
1752         struct hostent *hp;
1753         struct ast_hostent ahp;
1754         struct oh323_peer *p;
1755         int portno;
1756         int found = 0;
1757         char *port;
1758         char *hostn;
1759         char peer[256] = "";
1760
1761         ast_copy_string(peer, opeer, sizeof(peer));
1762         port = strchr(peer, ':');
1763         if (port) {
1764                 *port = '\0';
1765                 port++;
1766         }
1767         pvt->sa.sin_family = AF_INET;
1768         p = find_peer(peer, NULL, 1);
1769         if (p) {
1770                 found++;
1771                 memcpy(&pvt->options, &p->options, sizeof(pvt->options));
1772                 pvt->jointcapability = pvt->options.capability;
1773                 if (pvt->options.dtmfmode) {
1774                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1775                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1776                         } else {
1777                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1778                         }
1779                 }
1780                 if (p->addr.sin_addr.s_addr) {
1781                         pvt->sa.sin_addr = p->addr.sin_addr;
1782                         pvt->sa.sin_port = p->addr.sin_port;
1783                 }
1784                 ASTOBJ_UNREF(p, oh323_destroy_peer);
1785         }
1786         if (!p && !found) {
1787                 hostn = peer;
1788                 if (port) {
1789                         portno = atoi(port);
1790                 } else {
1791                         portno = h323_signalling_port;
1792                 }
1793                 hp = ast_gethostbyname(hostn, &ahp);
1794                 if (hp) {
1795                         memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
1796                         pvt->sa.sin_port = htons(portno);
1797                         /* Look peer by address */
1798                         p = find_peer(NULL, &pvt->sa, 1);
1799                         memcpy(&pvt->options, (p ? &p->options : &global_options), sizeof(pvt->options));
1800                         pvt->jointcapability = pvt->options.capability;
1801                         if (p) {
1802                                 ASTOBJ_UNREF(p, oh323_destroy_peer);
1803                         }
1804                         if (pvt->options.dtmfmode) {
1805                                 if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1806                                         pvt->nonCodecCapability |= AST_RTP_DTMF;
1807                                 } else {
1808                                         pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1809                                 }
1810                         }
1811                         return 0;
1812                 } else {
1813                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1814                         return -1;
1815                 }
1816         } else if (!found) {
1817                 return -1;
1818         } else {
1819                 return 0;
1820         }
1821 }
1822 static struct ast_channel *oh323_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *dest, int *cause)
1823 {
1824         struct oh323_pvt *pvt;
1825         struct ast_channel *tmpc = NULL;
1826         char *ext, *host;
1827         char *h323id = NULL;
1828         char tmp[256], tmp1[256];
1829
1830         if (h323debug)
1831                 ast_debug(1, "type=%s, format=%s, data=%s.\n", type, ast_getformatname_multiple(tmp, sizeof(tmp), cap), dest);
1832
1833         pvt = oh323_alloc(0);
1834         if (!pvt) {
1835                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", dest);
1836                 return NULL;
1837         }
1838         if (!(ast_format_cap_has_type(cap, AST_FORMAT_TYPE_AUDIO))) {
1839                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%s'\n", ast_getformatname_multiple(tmp, sizeof(tmp), cap));
1840                 oh323_destroy(pvt);
1841                 if (cause)
1842                         *cause = AST_CAUSE_INCOMPATIBLE_DESTINATION;
1843                 return NULL;
1844         }
1845         ast_copy_string(tmp, dest, sizeof(tmp));
1846         host = strchr(tmp, '@');
1847         if (host) {
1848                 *host = '\0';
1849                 host++;
1850                 ext = tmp;
1851         } else {
1852                 ext = strrchr(tmp, '/');
1853                 if (ext)
1854                         *ext++ = '\0';
1855                 host = tmp;
1856         }
1857         strtok_r(host, "/", &(h323id));
1858         if (!ast_strlen_zero(h323id)) {
1859                 h323_set_id(h323id);
1860         }
1861         if (ext) {
1862                 ast_copy_string(pvt->exten, ext, sizeof(pvt->exten));
1863         }
1864         if (h323debug)
1865                 ast_debug(1, "Extension: %s Host: %s\n", pvt->exten, host);
1866
1867         if (gatekeeper_disable) {
1868                 if (create_addr(pvt, host)) {
1869                         oh323_destroy(pvt);
1870                         if (cause)
1871                                 *cause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1872                         return NULL;
1873                 }
1874         }
1875         else {
1876                 memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1877                 pvt->jointcapability = pvt->options.capability;
1878                 if (pvt->options.dtmfmode) {
1879                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1880                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1881                         } else {
1882                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1883                         }
1884                 }
1885         }
1886
1887         ast_mutex_lock(&caplock);
1888         /* Generate unique channel identifier */
1889         snprintf(tmp1, sizeof(tmp1)-1, "%s-%u", host, ++unique);
1890         tmp1[sizeof(tmp1)-1] = '\0';
1891         ast_mutex_unlock(&caplock);
1892
1893         ast_mutex_lock(&pvt->lock);
1894         tmpc = __oh323_new(pvt, AST_STATE_DOWN, tmp1, assignedids, requestor);
1895         ast_mutex_unlock(&pvt->lock);
1896         if (!tmpc) {
1897                 oh323_destroy(pvt);
1898                 if (cause)
1899                         *cause = AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
1900         }
1901         ast_update_use_count();
1902         restart_monitor();
1903         return tmpc;
1904 }
1905
1906 /*! \brief Find a call by alias */
1907 static struct oh323_alias *find_alias(const char *source_aliases, int realtime)
1908 {
1909         struct oh323_alias *a;
1910
1911         a = ASTOBJ_CONTAINER_FIND(&aliasl, source_aliases);
1912
1913         if (!a && realtime)
1914                 a = realtime_alias(source_aliases);
1915
1916         return a;
1917 }
1918
1919 /*! \brief
1920   * Callback for sending digits from H.323 up to asterisk
1921   *
1922   */
1923 static int receive_digit(unsigned call_reference, char digit, const char *token, int duration)
1924 {
1925         struct oh323_pvt *pvt;
1926         int res;
1927
1928         pvt = find_call_locked(call_reference, token);
1929         if (!pvt) {
1930                 ast_log(LOG_ERROR, "Received digit '%c' (%u ms) for call %s without private structure\n", digit, duration, token);
1931                 return -1;
1932         }
1933         if (h323debug)
1934                 ast_log(LOG_DTMF, "Received %s digit '%c' (%u ms) for call %s\n", (digit == ' ' ? "update for" : "new"), (digit == ' ' ? pvt->curDTMF : digit), duration, token);
1935
1936         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
1937                 if (digit == '!')
1938                         res = ast_queue_control(pvt->owner, AST_CONTROL_FLASH);
1939                 else {
1940                         struct ast_frame f = {
1941                                 .frametype = AST_FRAME_DTMF_END,
1942                                 .subclass.integer = digit,
1943                                 .samples = duration * 8,
1944                                 .len = duration,
1945                                 .src = "SEND_DIGIT",
1946                         };
1947                         if (digit == ' ') {             /* signalUpdate message */
1948                                 f.subclass.integer = pvt->curDTMF;
1949                                 AST_SCHED_DEL(sched, pvt->DTMFsched);
1950                         } else {                                /* Regular input or signal message */
1951                                 if (pvt->DTMFsched >= 0) {
1952                                         /* We still don't send DTMF END from previous event, send it now */
1953                                         AST_SCHED_DEL(sched, pvt->DTMFsched);
1954                                         f.subclass.integer = pvt->curDTMF;
1955                                         f.samples = f.len = 0;
1956                                         ast_queue_frame(pvt->owner, &f);
1957                                         /* Restore values */
1958                                         f.subclass.integer = digit;
1959                                         f.samples = duration * 8;
1960                                         f.len = duration;
1961                                 }
1962                                 if (duration) {         /* This is a signal, signalUpdate follows */
1963                                         f.frametype = AST_FRAME_DTMF_BEGIN;
1964                                         pvt->DTMFsched = ast_sched_add(sched, duration, oh323_simulate_dtmf_end, pvt);
1965                                         if (h323debug)
1966                                                 ast_log(LOG_DTMF, "Scheduled DTMF END simulation for %d ms, id=%d\n", duration, pvt->DTMFsched);
1967                                 }
1968                                 pvt->curDTMF = digit;
1969                         }
1970                         res = ast_queue_frame(pvt->owner, &f);
1971                 }
1972                 ast_channel_unlock(pvt->owner);
1973         } else {
1974                 if (digit == '!')
1975                         pvt->newcontrol = AST_CONTROL_FLASH;
1976                 else {
1977                         pvt->newduration = duration;
1978                         pvt->newdigit = digit;
1979                 }
1980                 res = 0;
1981         }
1982         ast_mutex_unlock(&pvt->lock);
1983         return res;
1984 }
1985
1986 /*! \brief
1987   * Callback function used to inform the H.323 stack of the local rtp ip/port details
1988   *
1989   * \return Returns the local RTP information
1990   */
1991 static struct rtp_info *external_rtp_create(unsigned call_reference, const char * token)
1992 {
1993         struct oh323_pvt *pvt;
1994         struct sockaddr_in us;
1995         struct rtp_info *info;
1996
1997         info = ast_calloc(1, sizeof(*info));
1998         if (!info) {
1999                 ast_log(LOG_ERROR, "Unable to allocated info structure, this is very bad\n");
2000                 return NULL;
2001         }
2002         pvt = find_call_locked(call_reference, token);
2003         if (!pvt) {
2004                 ast_free(info);
2005                 ast_log(LOG_ERROR, "Unable to find call %s(%d)\n", token, call_reference);
2006                 return NULL;
2007         }
2008         if (!pvt->rtp)
2009                 __oh323_rtp_create(pvt);
2010         if (!pvt->rtp) {
2011                 ast_mutex_unlock(&pvt->lock);
2012                 ast_free(info);
2013                 ast_log(LOG_ERROR, "No RTP stream is available for call %s (%d)", token, call_reference);
2014                 return NULL;
2015         }
2016         /* figure out our local RTP port and tell the H.323 stack about it */
2017         {
2018                 struct ast_sockaddr tmp;
2019
2020                 ast_rtp_instance_get_local_address(pvt->rtp, &tmp);
2021                 ast_sockaddr_to_sin(&tmp, &us);
2022         }
2023         ast_mutex_unlock(&pvt->lock);
2024
2025         ast_copy_string(info->addr, ast_inet_ntoa(us.sin_addr), sizeof(info->addr));
2026         info->port = ntohs(us.sin_port);
2027         if (h323debug)
2028                 ast_debug(1, "Sending RTP 'US' %s:%d\n", info->addr, info->port);
2029         return info;
2030 }
2031
2032 /*! \brief
2033   * Call-back function passing remote ip/port information from H.323 to asterisk
2034   *
2035   * Returns nothing
2036   */
2037 static void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort, const char *token, int pt)
2038 {
2039         struct oh323_pvt *pvt;
2040         struct sockaddr_in them;
2041         int nativeformats_changed;
2042         enum { NEED_NONE, NEED_HOLD, NEED_UNHOLD } rtp_change = NEED_NONE;
2043
2044         if (h323debug)
2045                 ast_debug(1, "Setting up RTP connection for %s\n", token);
2046
2047         /* Find the call or allocate a private structure if call not found */
2048         pvt = find_call_locked(call_reference, token);
2049         if (!pvt) {
2050                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
2051                 return;
2052         }
2053         if (pvt->alreadygone) {
2054                 ast_mutex_unlock(&pvt->lock);
2055                 return;
2056         }
2057
2058         if (!pvt->rtp)
2059                 __oh323_rtp_create(pvt);
2060
2061         if ((pt == 2) && (pvt->jointcapability & AST_FORMAT_G726_AAL2)) {
2062                 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);
2063         }
2064
2065         them.sin_family = AF_INET;
2066         /* only works for IPv4 */
2067         them.sin_addr.s_addr = inet_addr(remoteIp);
2068         them.sin_port = htons(remotePort);
2069
2070         if (them.sin_addr.s_addr) {
2071                 {
2072                         struct ast_sockaddr tmp;
2073
2074                         ast_sockaddr_from_sin(&tmp, &them);
2075                         ast_rtp_instance_set_remote_address(pvt->rtp, &tmp);
2076                 }
2077                 if (pvt->recvonly) {
2078                         pvt->recvonly = 0;
2079                         rtp_change = NEED_UNHOLD;
2080                 }
2081         } else {
2082                 ast_rtp_instance_stop(pvt->rtp);
2083                 if (!pvt->recvonly) {
2084                         pvt->recvonly = 1;
2085                         rtp_change = NEED_HOLD;
2086                 }
2087         }
2088
2089         /* Change native format to reflect information taken from OLC/OLCAck */
2090         nativeformats_changed = 0;
2091         if (pt != 128 && pvt->rtp) {    /* Payload type is invalid, so try to use previously decided */
2092                 struct ast_rtp_payload_type rtptype = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(pvt->rtp), pt);
2093                 if (rtptype.asterisk_format) {
2094                         if (pvt->nativeformats != ast_format_to_old_bitfield(&rtptype.format)) {
2095                                 pvt->nativeformats = ast_format_to_old_bitfield(&rtptype.format);
2096                                 nativeformats_changed = 1;
2097                         }
2098                 }
2099         } else if (h323debug)
2100                 ast_log(LOG_NOTICE, "Payload type is unknown, formats isn't changed\n");
2101
2102         /* Don't try to lock the channel if nothing changed */
2103         if (nativeformats_changed || pvt->options.progress_audio || (rtp_change != NEED_NONE)) {
2104                 if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
2105                         struct ast_format_cap *pvt_native = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
2106                         ast_format_cap_from_old_bitfield(pvt_native, pvt->nativeformats);
2107
2108                         /* Re-build translation path only if native format(s) has been changed */
2109                         if (!(ast_format_cap_identical(ast_channel_nativeformats(pvt->owner), pvt_native))) {
2110                                 if (h323debug) {
2111                                         char tmp[256], tmp2[256];
2112                                         ast_debug(1, "Native format changed to '%s' from '%s', read format is %s, write format is %s\n",
2113                                                 ast_getformatname_multiple(tmp, sizeof(tmp), pvt_native),
2114                                                 ast_getformatname_multiple(tmp2, sizeof(tmp2), ast_channel_nativeformats(pvt->owner)),
2115                                                 ast_getformatname(ast_channel_readformat(pvt->owner)),
2116                                                 ast_getformatname(ast_channel_writeformat(pvt->owner)));
2117                                 }
2118                                 ast_format_cap_copy(ast_channel_nativeformats(pvt->owner), pvt_native);
2119                                 ast_set_read_format(pvt->owner, ast_channel_readformat(pvt->owner));
2120                                 ast_set_write_format(pvt->owner, ast_channel_writeformat(pvt->owner));
2121                         }
2122                         if (pvt->options.progress_audio)
2123                                 ast_queue_control(pvt->owner, AST_CONTROL_PROGRESS);
2124                         switch (rtp_change) {
2125                         case NEED_HOLD:
2126                                 ast_queue_hold(pvt->owner, NULL);
2127                                 break;
2128                         case NEED_UNHOLD:
2129                                 ast_queue_unhold(pvt->owner);
2130                                 break;
2131                         default:
2132                                 break;
2133                         }
2134                         ast_channel_unlock(pvt->owner);
2135                         pvt_native = ast_format_cap_destroy(pvt_native);
2136                 } else {
2137                         if (pvt->options.progress_audio)
2138                                 pvt->newcontrol = AST_CONTROL_PROGRESS;
2139                         else if (rtp_change == NEED_HOLD)
2140                                 pvt->newcontrol = AST_CONTROL_HOLD;
2141                         else if (rtp_change == NEED_UNHOLD)
2142                                 pvt->newcontrol = AST_CONTROL_UNHOLD;
2143                         if (h323debug)
2144                                 ast_debug(1, "RTP connection preparation for %s is pending...\n", token);
2145                 }
2146         }
2147         ast_mutex_unlock(&pvt->lock);
2148
2149         if (h323debug)
2150                 ast_debug(1, "RTP connection prepared for %s\n", token);
2151
2152         return;
2153 }
2154
2155 /*! \brief
2156   *     Call-back function to signal asterisk that the channel has been answered
2157   * Returns nothing
2158   */
2159 static void connection_made(unsigned call_reference, const char *token)
2160 {
2161         struct oh323_pvt *pvt;
2162
2163         if (h323debug)
2164                 ast_debug(1, "Call %s answered\n", token);
2165
2166         pvt = find_call_locked(call_reference, token);
2167         if (!pvt) {
2168                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
2169                 return;
2170         }
2171
2172         /* Inform asterisk about remote party connected only on outgoing calls */
2173         if (!pvt->outgoing) {
2174                 ast_mutex_unlock(&pvt->lock);
2175                 return;
2176         }
2177         /* Do not send ANSWER message more than once */
2178         if (!pvt->connection_established) {
2179                 pvt->connection_established = 1;
2180                 update_state(pvt, -1, AST_CONTROL_ANSWER);
2181         }
2182         ast_mutex_unlock(&pvt->lock);
2183         return;
2184 }
2185
2186 static int progress(unsigned call_reference, const char *token, int inband)
2187 {
2188         struct oh323_pvt *pvt;
2189
2190         if (h323debug)
2191                 ast_debug(1, "Received ALERT/PROGRESS message for %s tones\n", (inband ? "inband" : "self-generated"));
2192
2193         pvt = find_call_locked(call_reference, token);
2194         if (!pvt) {
2195                 ast_log(LOG_ERROR, "Private structure not found in progress.\n");
2196                 return -1;
2197         }
2198         if (!pvt->owner) {
2199                 ast_mutex_unlock(&pvt->lock);
2200                 ast_log(LOG_ERROR, "No Asterisk channel associated with private structure.\n");
2201                 return -1;
2202         }
2203         update_state(pvt, -1, (inband ? AST_CONTROL_PROGRESS : AST_CONTROL_RINGING));
2204         ast_mutex_unlock(&pvt->lock);
2205
2206         return 0;
2207 }
2208
2209 /*! \brief
2210  *  Call-back function for incoming calls
2211  *
2212  *  Returns 1 on success
2213  */
2214 static call_options_t *setup_incoming_call(call_details_t *cd)
2215 {
2216         struct oh323_pvt *pvt;
2217         struct oh323_user *user = NULL;
2218         struct oh323_alias *alias = NULL;
2219
2220         if (h323debug)
2221                 ast_debug(1, "Setting up incoming call for %s\n", cd->call_token);
2222
2223         /* allocate the call*/
2224         pvt = oh323_alloc(cd->call_reference);
2225
2226         if (!pvt) {
2227                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
2228                 cleanup_call_details(cd);
2229                 return NULL;
2230         }
2231
2232         /* Populate the call details in the private structure */
2233         memcpy(&pvt->cd, cd, sizeof(pvt->cd));
2234         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
2235         pvt->jointcapability = pvt->options.capability;
2236
2237         if (h323debug) {
2238                 ast_verb(3, "Setting up Call\n");
2239                 ast_verb(3, " \tCall token:  [%s]\n", pvt->cd.call_token);
2240                 ast_verb(3, " \tCalling party name:  [%s]\n", pvt->cd.call_source_name);
2241                 ast_verb(3, " \tCalling party number:  [%s]\n", pvt->cd.call_source_e164);
2242                 ast_verb(3, " \tCalled party name:  [%s]\n", pvt->cd.call_dest_alias);
2243                 ast_verb(3, " \tCalled party number:  [%s]\n", pvt->cd.call_dest_e164);
2244                 if (pvt->cd.redirect_reason >= 0)
2245                         ast_verb(3, " \tRedirecting party number:  [%s] (reason %d)\n", pvt->cd.redirect_number, pvt->cd.redirect_reason);
2246                 ast_verb(3, " \tCalling party IP:  [%s]\n", pvt->cd.sourceIp);
2247         }
2248
2249         /* Decide if we are allowing Gatekeeper routed calls*/
2250         if ((!strcasecmp(cd->sourceIp, gatekeeper)) && (gkroute == -1) && !gatekeeper_disable) {
2251                 if (!ast_strlen_zero(cd->call_dest_e164)) {
2252                         ast_copy_string(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten));
2253                         ast_copy_string(pvt->context, default_context, sizeof(pvt->context));
2254                 } else {
2255                         alias = find_alias(cd->call_dest_alias, 1);
2256                         if (!alias) {
2257                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd->call_dest_alias);
2258                                 oh323_destroy(pvt);
2259                                 return NULL;
2260                         }
2261                         ast_copy_string(pvt->exten, alias->name, sizeof(pvt->exten));
2262                         ast_copy_string(pvt->context, alias->context, sizeof(pvt->context));
2263                 }
2264         } else {
2265                 /* Either this call is not from the Gatekeeper
2266                    or we are not allowing gk routed calls */
2267                 user = find_user(cd, 1);
2268                 if (!user) {
2269                         if (!acceptAnonymous) {
2270                                 ast_log(LOG_NOTICE, "Anonymous call from '%s@%s' rejected\n", pvt->cd.call_source_aliases, pvt->cd.sourceIp);
2271                                 oh323_destroy(pvt);
2272                                 return NULL;
2273                         }
2274                         if (ast_strlen_zero(default_context)) {
2275                                 ast_log(LOG_ERROR, "Call from '%s@%s' rejected due to no default context\n", pvt->cd.call_source_aliases, pvt->cd.sourceIp);
2276                                 oh323_destroy(pvt);
2277                                 return NULL;
2278                         }
2279                         ast_copy_string(pvt->context, default_context, sizeof(pvt->context));
2280                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
2281                                 ast_copy_string(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten));
2282                         } else {
2283                                 ast_copy_string(pvt->exten, cd->call_dest_alias, sizeof(pvt->exten));
2284                         }
2285                         if (h323debug)
2286                                 ast_debug(1, "Sending %s@%s to context [%s] extension %s\n", cd->call_source_aliases, cd->sourceIp, pvt->context, pvt->exten);
2287                 } else {
2288                         if (user->host) {
2289                                 if (strcasecmp(cd->sourceIp, ast_inet_ntoa(user->addr.sin_addr))) {
2290                                         if (ast_strlen_zero(user->context)) {
2291                                                 if (ast_strlen_zero(default_context)) {
2292                                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s) and no default context\n", user->name, cd->sourceIp);
2293                                                         oh323_destroy(pvt);
2294                                                         ASTOBJ_UNREF(user, oh323_destroy_user);
2295                                                         return NULL;
2296                                                 }
2297                                                 ast_copy_string(pvt->context, default_context, sizeof(pvt->context));
2298                                         } else {
2299                                                 ast_copy_string(pvt->context, user->context, sizeof(pvt->context));
2300                                         }
2301                                         pvt->exten[0] = 'i';
2302                                         pvt->exten[1] = '\0';
2303                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s)s\n", user->name, cd->sourceIp);
2304                                         oh323_destroy(pvt);
2305                                         ASTOBJ_UNREF(user, oh323_destroy_user);
2306                                         return NULL;    /* XXX: Hmmm... Why to setup context if we drop connection immediately??? */
2307                                 }
2308                         }
2309                         ast_copy_string(pvt->context, user->context, sizeof(pvt->context));
2310                         memcpy(&pvt->options, &user->options, sizeof(pvt->options));
2311                         pvt->jointcapability = pvt->options.capability;
2312                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
2313                                 ast_copy_string(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten));
2314                         } else {
2315                                 ast_copy_string(pvt->exten, cd->call_dest_alias, sizeof(pvt->exten));
2316                         }
2317                         if (!ast_strlen_zero(user->accountcode)) {
2318                                 ast_copy_string(pvt->accountcode, user->accountcode, sizeof(pvt->accountcode));
2319                         }
2320                         if (user->amaflags) {
2321                                 pvt->amaflags = user->amaflags;
2322                         }
2323                         ASTOBJ_UNREF(user, oh323_destroy_user);
2324                 }
2325         }
2326         return &pvt->options;
2327 }
2328
2329 /*! \brief
2330  * Call-back function to start PBX when OpenH323 ready to serve incoming call
2331  *
2332  * Returns 1 on success
2333  */
2334 static int answer_call(unsigned call_reference, const char *token)
2335 {
2336         struct oh323_pvt *pvt;
2337         struct ast_channel *c = NULL;
2338         enum {ext_original, ext_s, ext_i, ext_notexists} try_exten;
2339         char tmp_exten[sizeof(pvt->exten)];
2340
2341         if (h323debug)
2342                 ast_debug(1, "Preparing Asterisk to answer for %s\n", token);
2343
2344         /* Find the call or allocate a private structure if call not found */
2345         pvt = find_call_locked(call_reference, token);
2346         if (!pvt) {
2347                 ast_log(LOG_ERROR, "Something is wrong: answer_call\n");
2348                 return 0;
2349         }
2350         /* Check if requested extension@context pair exists in the dialplan */
2351         ast_copy_string(tmp_exten, pvt->exten, sizeof(tmp_exten));
2352
2353         /* Try to find best extension in specified context */
2354         if ((tmp_exten[0] != '\0') && (tmp_exten[1] == '\0')) {
2355                 if (tmp_exten[0] == 's')
2356                         try_exten = ext_s;
2357                 else if (tmp_exten[0] == 'i')
2358                         try_exten = ext_i;
2359                 else
2360                         try_exten = ext_original;
2361         } else
2362                 try_exten = ext_original;
2363         do {
2364                 if (ast_exists_extension(NULL, pvt->context, tmp_exten, 1, NULL))
2365                         break;
2366                 switch (try_exten) {
2367                 case ext_original:
2368                         tmp_exten[0] = 's';
2369                         tmp_exten[1] = '\0';
2370                         try_exten = ext_s;
2371                         break;
2372                 case ext_s:
2373                         tmp_exten[0] = 'i';
2374                         try_exten = ext_i;
2375                         break;
2376                 case ext_i:
2377                         try_exten = ext_notexists;
2378                         break;
2379                 default:
2380                         break;
2381                 }
2382         } while (try_exten != ext_notexists);
2383
2384         /* Drop the call if we don't have <exten>, s and i extensions */
2385         if (try_exten == ext_notexists) {
2386                 ast_log(LOG_NOTICE, "Dropping call because extensions '%s', 's' and 'i' doesn't exists in context [%s]\n", pvt->exten, pvt->context);
2387                 ast_mutex_unlock(&pvt->lock);
2388                 h323_clear_call(token, AST_CAUSE_UNALLOCATED);
2389                 return 0;
2390         } else if ((try_exten != ext_original) && (strcmp(pvt->exten, tmp_exten) != 0)) {
2391                 if (h323debug)
2392                         ast_debug(1, "Going to extension %s@%s because %s@%s isn't exists\n", tmp_exten, pvt->context, pvt->exten, pvt->context);
2393                 ast_copy_string(pvt->exten, tmp_exten, sizeof(pvt->exten));
2394         }
2395
2396         /* allocate a channel and tell asterisk about it */
2397         c = __oh323_new(pvt, AST_STATE_RINGING, pvt->cd.call_token, NULL, NULL);
2398
2399         /* And release when done */
2400         ast_mutex_unlock(&pvt->lock);
2401         if (!c) {
2402                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
2403                 return 0;
2404         }
2405         return 1;
2406 }
2407
2408 /*! \brief
2409  * Call-back function to establish an outgoing H.323 call
2410  *
2411  * Returns 1 on success
2412  */
2413 static int setup_outgoing_call(call_details_t *cd)
2414 {
2415         /* Use argument here or free it immediately */
2416         cleanup_call_details(cd);
2417
2418         return 1;
2419 }
2420
2421 /*! \brief
2422   *  Call-back function to signal asterisk that the channel is ringing
2423   *  Returns nothing
2424   */
2425 static void chan_ringing(unsigned call_reference, const char *token)
2426 {
2427         struct oh323_pvt *pvt;
2428
2429         if (h323debug)
2430                 ast_debug(1, "Ringing on %s\n", token);
2431
2432         pvt = find_call_locked(call_reference, token);
2433         if (!pvt) {
2434                 ast_log(LOG_ERROR, "Something is wrong: ringing\n");
2435                 return;
2436         }
2437         if (!pvt->owner) {
2438                 ast_mutex_unlock(&pvt->lock);
2439                 ast_log(LOG_ERROR, "Channel has no owner\n");
2440                 return;
2441         }
2442         update_state(pvt, AST_STATE_RINGING, AST_CONTROL_RINGING);
2443         ast_mutex_unlock(&pvt->lock);
2444         return;
2445 }
2446
2447 /*! \brief
2448   * Call-back function to cleanup communication
2449   * Returns nothing,
2450   */
2451 static void cleanup_connection(unsigned call_reference, const char *call_token)
2452 {
2453         struct oh323_pvt *pvt;
2454
2455         if (h323debug)
2456                 ast_debug(1, "Cleaning connection to %s\n", call_token);
2457
2458         while (1) {
2459                 pvt = find_call_locked(call_reference, call_token);
2460                 if (!pvt) {
2461                         if (h323debug)
2462                                 ast_debug(1, "No connection for %s\n", call_token);
2463                         return;
2464                 }
2465                 if (!pvt->owner || !ast_channel_trylock(pvt->owner))
2466                         break;
2467 #if 1
2468                 ast_log(LOG_NOTICE, "Avoiding H.323 destory deadlock on %s\n", call_token);
2469 #ifdef DEBUG_THREADS
2470                 /* XXX to be completed
2471                  * If we want to print more info on who is holding the lock,
2472                  * implement the relevant code in lock.h and use the routines
2473                  * supplied there.
2474                  */
2475 #endif
2476 #endif
2477                 ast_mutex_unlock(&pvt->lock);
2478                 usleep(1);
2479         }
2480         if (pvt->rtp) {
2481                 /* Immediately stop RTP */
2482                 ast_rtp_instance_destroy(pvt->rtp);
2483                 pvt->rtp = NULL;
2484         }
2485         /* Free dsp used for in-band DTMF detection */
2486         if (pvt->vad) {
2487                 ast_dsp_free(pvt->vad);
2488                 pvt->vad = NULL;
2489         }
2490         cleanup_call_details(&pvt->cd);
2491         pvt->alreadygone = 1;
2492         /* Send hangup */
2493         if (pvt->owner) {
2494                 ast_channel_softhangup_internal_flag_add(pvt->owner, AST_SOFTHANGUP_DEV);
2495                 ast_queue_hangup(pvt->owner);
2496                 ast_channel_unlock(pvt->owner);
2497         }
2498         ast_mutex_unlock(&pvt->lock);
2499         if (h323debug)
2500                 ast_debug(1, "Connection to %s cleaned\n", call_token);
2501         return;
2502 }
2503
2504 static void hangup_connection(unsigned int call_reference, const char *token, int cause)
2505 {
2506         struct oh323_pvt *pvt;
2507
2508         if (h323debug)
2509                 ast_debug(1, "Hanging up connection to %s with cause %d\n", token, cause);
2510
2511         pvt = find_call_locked(call_reference, token);
2512         if (!pvt) {
2513                 if (h323debug)
2514                         ast_debug(1, "Connection to %s already cleared\n", token);
2515                 return;
2516         }
2517         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
2518                 ast_channel_softhangup_internal_flag_add(pvt->owner, AST_SOFTHANGUP_DEV);
2519                 ast_channel_hangupcause_set(pvt->owner, pvt->hangupcause = cause);
2520                 ast_queue_hangup_with_cause(pvt->owner, cause);
2521                 ast_channel_unlock(pvt->owner);
2522         }
2523         else {
2524                 pvt->needhangup = 1;
2525                 pvt->hangupcause = cause;
2526                 if (h323debug)
2527                         ast_debug(1, "Hangup for %s is pending\n", token);
2528         }
2529         ast_mutex_unlock(&pvt->lock);
2530 }
2531
2532 static void set_dtmf_payload(unsigned call_reference, const char *token, int payload, int is_cisco)
2533 {
2534         struct oh323_pvt *pvt;
2535
2536         if (h323debug)
2537                 ast_debug(1, "Setting %s DTMF payload to %d on %s\n", (is_cisco ? "Cisco" : "RFC2833"), payload, token);
2538
2539         pvt = find_call_locked(call_reference, token);
2540         if (!pvt) {
2541                 return;
2542         }
2543         if (pvt->rtp) {
2544                 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);
2545         }
2546         pvt->dtmf_pt[is_cisco ? 1 : 0] = payload;
2547         ast_mutex_unlock(&pvt->lock);
2548         if (h323debug)
2549                 ast_debug(1, "DTMF payload on %s set to %d\n", token, payload);
2550 }
2551
2552 static void set_peer_capabilities(unsigned call_reference, const char *token, int capabilities, struct ast_codec_pref *prefs)
2553 {
2554         struct oh323_pvt *pvt;
2555
2556         if (h323debug)
2557                 ast_debug(1, "Got remote capabilities from connection %s\n", token);
2558
2559         pvt = find_call_locked(call_reference, token);
2560         if (!pvt)
2561                 return;
2562         pvt->peercapability = capabilities;
2563         pvt->jointcapability = pvt->options.capability & capabilities;
2564         if (prefs) {
2565                 memcpy(&pvt->peer_prefs, prefs, sizeof(pvt->peer_prefs));
2566                 if (h323debug) {
2567                         int i;
2568                         for (i = 0; i < 32; ++i) {
2569                                 if (!prefs->order[i])
2570                                         break;
2571                                 ast_debug(1, "prefs[%d]=%s:%d\n", i, (prefs->order[i] ? ast_getformatname(&prefs->formats[i]) : "<none>"), prefs->framing[i]);
2572                         }
2573                 }
2574                 if (pvt->rtp) {
2575                         if (pvt->options.autoframing) {
2576                                 ast_debug(2, "Autoframing option set, using peer's packetization settings\n");
2577                                 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(pvt->rtp), pvt->rtp, &pvt->peer_prefs);
2578                         } else {
2579                                 ast_debug(2, "Autoframing option not set, ignoring peer's packetization settings\n");
2580                                 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(pvt->rtp), pvt->rtp, &pvt->options.prefs);
2581                         }
2582                 }
2583         }
2584         ast_mutex_unlock(&pvt->lock);
2585 }
2586
2587 static void set_local_capabilities(unsigned call_reference, const char *token)
2588 {
2589         struct oh323_pvt *pvt;
2590         int capability, dtmfmode, pref_codec;
2591         struct ast_codec_pref prefs;
2592
2593         if (h323debug)
2594                 ast_debug(1, "Setting capabilities for connection %s\n", token);
2595
2596         pvt = find_call_locked(call_reference, token);
2597         if (!pvt)
2598                 return;
2599         capability = (pvt->jointcapability) ? pvt->jointcapability : pvt->options.capability;
2600         dtmfmode = pvt->options.dtmfmode;
2601         prefs = pvt->options.prefs;
2602         pref_codec = pvt->pref_codec;
2603         ast_mutex_unlock(&pvt->lock);
2604         h323_set_capabilities(token, capability, dtmfmode, &prefs, pref_codec);
2605
2606         if (h323debug) {
2607                 int i;
2608                 for (i = 0; i < 32; i++) {
2609                         if (!prefs.order[i])
2610                                 break;
2611                         ast_debug(1, "local prefs[%d]=%s:%d\n", i, (prefs.order[i] ? ast_getformatname(&prefs.formats[i]) : "<none>"), prefs.framing[i]);
2612                 }
2613                 ast_debug(1, "Capabilities for connection %s is set\n", token);
2614         }
2615 }
2616
2617 static void remote_hold(unsigned call_reference, const char *token, int is_hold)
2618 {
2619         struct oh323_pvt *pvt;
2620
2621         if (h323debug)
2622                 ast_debug(1, "Setting %shold status for connection %s\n", (is_hold ? "" : "un"), token);
2623
2624         pvt = find_call_locked(call_reference, token);
2625         if (!pvt)
2626                 return;
2627         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
2628                 if (is_hold) {
2629                         ast_queue_hold(pvt->owner, NULL);
2630                 } else {
2631                         ast_queue_unhold(pvt->owner);
2632                 }
2633                 ast_channel_unlock(pvt->owner);
2634         }
2635         else {
2636                 if (is_hold)
2637                         pvt->newcontrol = AST_CONTROL_HOLD;
2638                 else
2639                         pvt->newcontrol = AST_CONTROL_UNHOLD;
2640         }
2641         ast_mutex_unlock(&pvt->lock);
2642 }
2643
2644 static void *do_monitor(void *data)
2645 {
2646         int res;
2647         int reloading;
2648         struct oh323_pvt *oh323 = NULL;
2649
2650         for(;;) {
2651                 /* Check for a reload request */
2652                 ast_mutex_lock(&h323_reload_lock);
2653                 reloading = h323_reloading;
2654                 h323_reloading = 0;
2655                 ast_mutex_unlock(&h323_reload_lock);
2656                 if (reloading) {
2657                         ast_verb(1, "Reloading H.323\n");
2658                         h323_do_reload();
2659                 }
2660                 /* Check for interfaces needing to be killed */
2661                 if (!ast_mutex_trylock(&iflock)) {
2662 #if 1
2663                         do {
2664                                 for (oh323 = iflist; oh323; oh323 = oh323->next) {
2665                                         if (!ast_mutex_trylock(&oh323->lock)) {
2666                                                 if (oh323->needdestroy) {
2667                                                         __oh323_destroy(oh323);
2668                                                         break;
2669                                                 }
2670                                                 ast_mutex_unlock(&oh323->lock);
2671                                         }
2672                                 }
2673                         } while (/*oh323*/ 0);
2674 #else
2675 restartsearch:
2676                         oh323 = iflist;
2677                         while(oh323) {
2678                                 if (!ast_mutex_trylock(&oh323->lock)) {
2679                                         if (oh323->needdestroy) {
2680                                                 __oh323_destroy(oh323);
2681                                                 goto restartsearch;
2682                                         }
2683                                         ast_mutex_unlock(&oh323->lock);
2684                                         oh323 = oh323->next;
2685                                 }
2686                         }
2687 #endif
2688                         ast_mutex_unlock(&iflock);
2689                 } else
2690                         oh323 = (struct oh323_pvt *)1;  /* Force fast loop */
2691                 pthread_testcancel();
2692                 /* Wait for sched or io */
2693                 res = ast_sched_wait(sched);
2694                 if ((res < 0) || (res > 1000)) {
2695                         res = 1000;
2696                 }
2697                 /* Do not wait if some channel(s) is destroyed, probably, more available too */
2698                 if (oh323)
2699                         res = 1;
2700                 res = ast_io_wait(io, res);
2701                 pthread_testcancel();
2702                 ast_mutex_lock(&monlock);
2703                 if (res >= 0) {
2704                         ast_sched_runq(sched);
2705                 }
2706                 ast_mutex_unlock(&monlock);
2707         }
2708         /* Never reached */
2709         return NULL;
2710 }
2711
2712 static int restart_monitor(void)
2713 {
2714         /* If we're supposed to be stopped -- stay stopped */
2715         if (ast_mutex_lock(&monlock)) {
2716                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
2717                 return -1;
2718         }
2719         if (monitor_thread == AST_PTHREADT_STOP) {
2720                 ast_mutex_unlock(&monlock);
2721                 return 0;
2722         }
2723         if (monitor_thread == pthread_self()) {
2724                 ast_mutex_unlock(&monlock);
2725                 ast_log(LOG_WARNING, "Cannot kill myself\n");
2726                 return -1;
2727         }
2728         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
2729                 /* Wake up the thread */
2730                 pthread_kill(monitor_thread, SIGURG);
2731         } else {
2732                 /* Start a new monitor */
2733                 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
2734                         monitor_thread = AST_PTHREADT_NULL;
2735                         ast_mutex_unlock(&monlock);
2736                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
2737                         return -1;
2738                 }
2739         }
2740         ast_mutex_unlock(&monlock);
2741         return 0;
2742 }
2743
2744 static char *handle_cli_h323_set_trace(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2745 {
2746         switch (cmd) {
2747         case CLI_INIT:
2748                 e->command = "h323 set trace [on|off]";
2749                 e->usage =
2750                         "Usage: h323 set trace (on|off|<trace level>)\n"
2751                         "       Enable/Disable H.323 stack tracing for debugging purposes\n";
2752                 return NULL;
2753         case CLI_GENERATE:
2754                 return NULL;
2755         }
2756
2757         if (a->argc != e->args)
2758                 return CLI_SHOWUSAGE;
2759         if (!strcasecmp(a->argv[3], "off")) {
2760                 h323_debug(0, 0);
2761                 ast_cli(a->fd, "H.323 Trace Disabled\n");
2762         } else if (!strcasecmp(a->argv[3], "on")) {
2763                 h323_debug(1, 1);
2764                 ast_cli(a->fd, "H.323 Trace Enabled\n");
2765         } else {
2766                 int tracelevel = atoi(a->argv[3]);
2767                 h323_debug(1, tracelevel);
2768                 ast_cli(a->fd, "H.323 Trace Enabled (Trace Level: %d)\n", tracelevel);
2769         }
2770         return CLI_SUCCESS;
2771 }
2772
2773 static char *handle_cli_h323_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2774 {
2775         switch (cmd) {
2776         case CLI_INIT:
2777                 e->command = "h323 set debug [on|off]";
2778                 e->usage =
2779                         "Usage: h323 set debug [on|off]\n"
2780                         "       Enable/Disable H.323 debugging output\n";
2781                 return NULL;
2782         case CLI_GENERATE:
2783                 return NULL;
2784         }
2785
2786         if (a->argc != e->args)
2787                 return CLI_SHOWUSAGE;
2788         if (strcasecmp(a->argv[3], "on") && strcasecmp(a->argv[3], "off"))
2789                 return CLI_SHOWUSAGE;
2790
2791         h323debug = (strcasecmp(a->argv[3], "on")) ? 0 : 1;
2792         ast_cli(a->fd, "H.323 Debugging %s\n", h323debug ? "Enabled" : "Disabled");
2793         return CLI_SUCCESS;
2794 }
2795
2796 static char *handle_cli_h323_cycle_gk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2797 {
2798         switch (cmd) {
2799         case CLI_INIT:
2800                 e->command = "h323 cycle gk";
2801                 e->usage =
2802                         "Usage: h323 cycle gk\n"
2803                         "       Manually re-register with the Gatekeper (Currently Disabled)\n";
2804                 return NULL;
2805         case CLI_GENERATE:
2806                 return NULL;
2807         }
2808
2809         if (a->argc != 3)
2810                 return CLI_SHOWUSAGE;
2811
2812         h323_gk_urq();
2813
2814         /* Possibly register with a GK */
2815         if (!gatekeeper_disable) {
2816                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
2817                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
2818                 }
2819         }
2820         return CLI_SUCCESS;
2821 }
2822
2823 static char *handle_cli_h323_hangup(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2824 {
2825         switch (cmd) {
2826         case CLI_INIT:
2827                 e->command = "h323 hangup";
2828                 e->usage =
2829                         "Usage: h323 hangup <token>\n"
2830                         "       Manually try to hang up the call identified by <token>\n";
2831                 return NULL;
2832         case CLI_GENERATE:
2833                 return NULL;
2834         }
2835
2836         if (a->argc != 3)
2837                 return CLI_SHOWUSAGE;
2838         if (h323_soft_hangup(a->argv[2])) {
2839                 ast_verb(3, "Hangup succeeded on %s\n", a->argv[2]);
2840         } else {
2841                 ast_verb(3, "Hangup failed for %s\n", a->argv[2]);
2842         }
2843         return CLI_SUCCESS;
2844 }
2845
2846 static char *handle_cli_h323_show_tokens(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2847 {
2848         switch (cmd) {
2849         case CLI_INIT:
2850                 e->command = "h323 show tokens";
2851                 e->usage =
2852                         "Usage: h323 show tokens\n"
2853                         "       Print out all active call tokens\n";
2854                 return NULL;
2855         case CLI_GENERATE:
2856                 return NULL;
2857         }
2858
2859         if (a->argc != 3)
2860                 return CLI_SHOWUSAGE;
2861
2862         h323_show_tokens();
2863
2864         return CLI_SUCCESS;
2865 }
2866
2867 static char *handle_cli_h323_show_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2868 {
2869         switch (cmd) {
2870         case CLI_INIT:
2871                 e->command = "h323 show version";
2872                 e->usage =
2873                         "Usage: h323 show version\n"
2874                         "               Show the version of the H.323 library in use\n";
2875                 return NULL;
2876         case CLI_GENERATE:
2877                 return NULL;
2878         }
2879
2880         if (a->argc != 3)
2881                 return CLI_SHOWUSAGE;
2882
2883         h323_show_version();
2884         
2885         return CLI_SUCCESS;
2886 }
2887
2888 static struct ast_cli_entry cli_h323[] = {
2889         AST_CLI_DEFINE(handle_cli_h323_set_trace,    "Enable/Disable H.323 Stack Tracing"),
2890         AST_CLI_DEFINE(handle_cli_h323_set_debug,    "Enable/Disable H.323 Debugging"),
2891         AST_CLI_DEFINE(handle_cli_h323_cycle_gk,     "Manually re-register with the Gatekeper"),
2892         AST_CLI_DEFINE(handle_cli_h323_hangup,       "Manually try to hang up a call"),
2893         AST_CLI_DEFINE(handle_cli_h323_show_tokens,  "Show all active call tokens"),
2894         AST_CLI_DEFINE(handle_cli_h323_show_version, "Show the version of the H.323 library in use"),
2895 };
2896
2897 static void delete_users(void)
2898 {
2899         int pruned = 0;
2900
2901         /* Delete all users */
2902         ASTOBJ_CONTAINER_WRLOCK(&userl);
2903         ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
2904                 ASTOBJ_RDLOCK(iterator);
2905                 ASTOBJ_MARK(iterator);
2906                 ++pruned;
2907                 ASTOBJ_UNLOCK(iterator);
2908         } while (0) );
2909         if (pruned) {
2910                 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, oh323_destroy_user);
2911         }
2912         ASTOBJ_CONTAINER_UNLOCK(&userl);
2913
2914         ASTOBJ_CONTAINER_WRLOCK(&peerl);
2915         ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
2916                 ASTOBJ_RDLOCK(iterator);
2917                 ASTOBJ_MARK(iterator);
2918                 ASTOBJ_UNLOCK(iterator);
2919         } while (0) );
2920         ASTOBJ_CONTAINER_UNLOCK(&peerl);
2921 }
2922
2923 static void delete_aliases(void)
2924 {
2925         int pruned = 0;
2926
2927         /* Delete all aliases */
2928         ASTOBJ_CONTAINER_WRLOCK(&aliasl);
2929         ASTOBJ_CONTAINER_TRAVERSE(&aliasl, 1, do {
2930                 ASTOBJ_RDLOCK(iterator);
2931                 ASTOBJ_MARK(iterator);
2932                 ++pruned;
2933                 ASTOBJ_UNLOCK(iterator);
2934         } while (0) );
2935         if (pruned) {
2936                 ASTOBJ_CONTAINER_PRUNE_MARKED(&aliasl, oh323_destroy_alias);
2937         }
2938         ASTOBJ_CONTAINER_UNLOCK(&aliasl);
2939 }
2940
2941 static void prune_peers(void)
2942 {
2943         /* Prune peers who still are supposed to be deleted */
2944         ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, oh323_destroy_peer);
2945 }
2946
2947 static int reload_config(int is_reload)
2948 {
2949         struct ast_config *cfg, *ucfg;
2950         struct ast_variable *v;
2951         struct oh323_peer *peer = NULL;
2952         struct oh323_user *user = NULL;
2953         struct oh323_alias *alias = NULL;
2954         struct ast_hostent ahp; struct hostent *hp;
2955         char *cat;
2956         const char *utype;
2957         int is_user, is_peer, is_alias;
2958         char _gatekeeper[100];
2959         int gk_discover, gk_disable, gk_changed;
2960         struct ast_flags config_flags = { is_reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
2961
2962         cfg = ast_config_load(config, config_flags);
2963
2964         /* We *must* have a config file otherwise stop immediately */
2965         if (!cfg) {
2966                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
2967                 return 1;
2968         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
2969                 ucfg = ast_config_load("users.conf", config_flags);
2970                 if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
2971                         return 0;
2972                 } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
2973                         ast_log(LOG_ERROR, "Config file users.conf is in an invalid format.  Aborting.\n");
2974                         return 0;
2975                 }
2976                 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
2977                 if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
2978                         ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", config);
2979                         ast_config_destroy(ucfg);
2980                         return 0;
2981                 }
2982         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2983                 ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", config);
2984                 return 0;
2985         } else {
2986                 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
2987                 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
2988                         ast_log(LOG_ERROR, "Config file users.conf is in an invalid format.  Aborting.\n");
2989                         ast_config_destroy(cfg);
2990                         return 0;
2991                 }
2992         }
2993
2994         if (is_reload) {
2995                 delete_users();
2996                 delete_aliases();
2997                 prune_peers();
2998         }
2999
3000         /* fire up the H.323 Endpoint */
3001         if (!h323_end_point_exist()) {
3002                 h323_end_point_create();
3003         }
3004         ast_copy_string(_gatekeeper, gatekeeper, sizeof(_gatekeeper));
3005         gk_discover = gatekeeper_discover;
3006         gk_disable = gatekeeper_disable;
3007         memset(&bindaddr, 0, sizeof(bindaddr));
3008         memset(&global_options, 0, sizeof(global_options));
3009         global_options.fastStart = 1;
3010         global_options.h245Tunneling = 1;
3011         global_options.dtmfcodec[0] = H323_DTMF_RFC2833_PT;
3012         global_options.dtmfcodec[1] = H323_DTMF_CISCO_PT;
3013         global_options.dtmfmode = 0;
3014         global_options.holdHandling = 0;
3015         global_options.capability = GLOBAL_CAPABILITY;
3016         global_options.bridge = 1;              /* Do native bridging by default */
3017         global_options.autoframing = 0;
3018         strcpy(default_context, "default");
3019         h323_signalling_port = 1720;
3020         gatekeeper_disable = 1;
3021         gatekeeper_discover = 0;
3022         gkroute = 0;
3023         userbyalias = 1;
3024         acceptAnonymous = 1;
3025         tos = 0;
3026         cos = 0;
3027
3028         /* Copy the default jb config over global_jbconf */
3029         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
3030
3031         if (ucfg) {
3032                 struct ast_variable *gen;
3033                 int genhas_h323;
3034                 const char *has_h323;
3035
3036                 genhas_h323 = ast_true(ast_variable_retrieve(ucfg, "general", "hash323"));
3037                 gen = ast_variable_browse(ucfg, "general");
3038                 for (cat = ast_category_browse(ucfg, NULL); cat; cat = ast_category_browse(ucfg, cat)) {
3039                         if (strcasecmp(cat, "general")) {
3040                                 has_h323 = ast_variable_retrieve(ucfg, cat, "hash323");
3041                                 if (ast_true(has_h323) || (!has_h323 && genhas_h323)) {
3042                                         user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
3043                                         if (user) {
3044                                                 ASTOBJ_CONTAINER_LINK(&userl, user);
3045                                                 ASTOBJ_UNREF(user, oh323_destroy_user);
3046                                         }
3047                                         peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
3048                                         if (peer) {
3049                                                 ASTOBJ_CONTAINER_LINK(&peerl, peer);
3050                                                 ASTOBJ_UNREF(peer, oh323_destroy_peer);
3051                                         }
3052                                 }
3053                         }
3054                 }
3055                 ast_config_destroy(ucfg);
3056         }
3057
3058         for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
3059                 /* handle jb conf */
3060                 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
3061                         continue;