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