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