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