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