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