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