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