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