Change URL to OpenH323 (thanks, Tzafrir!)
[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 int tos = 0;
153 static char secret[50];
154 static unsigned int unique = 0;
155
156 static call_options_t global_options;
157
158 /*! \brief Private structure of a OpenH323 channel */
159 struct oh323_pvt {
160         ast_mutex_t lock;                       /*!< Channel private lock */
161         call_options_t options;                 /*!<!< Options to be used during call setup */
162         int alreadygone;                        /*!< Whether or not we've already been destroyed by our peer */
163         int needdestroy;                        /*!< if we need to be destroyed */
164         call_details_t cd;                      /*!< Call details */
165         struct ast_channel *owner;              /*!< Who owns us */
166         struct sockaddr_in sa;                  /*!< Our peer */
167         struct sockaddr_in redirip;             /*!< Where our RTP should be going if not to us */
168         int nonCodecCapability;                 /*!< non-audio capability */
169         int outgoing;                           /*!< Outgoing or incoming call? */
170         char exten[AST_MAX_EXTENSION];          /*!< Requested extension */
171         char context[AST_MAX_CONTEXT];          /*!< Context where to start */
172         char accountcode[256];                  /*!< Account code */
173         char rdnis[80];                         /*!< Referring DNIS, if available */
174         int amaflags;                           /*!< AMA Flags */
175         struct ast_rtp *rtp;                    /*!< RTP Session */
176         struct ast_dsp *vad;                    /*!< Used for in-band DTMF detection */
177         int nativeformats;                      /*!< Codec formats supported by a channel */
178         int needhangup;                         /*!< Send hangup when Asterisk is ready */
179         int hangupcause;                        /*!< Hangup cause from OpenH323 layer */
180         int newstate;                           /*!< Pending state change */
181         int newcontrol;                         /*!< Pending control to send */
182         int newdigit;                           /*!< Pending DTMF digit to send */
183         int newduration;                        /*!< Pending DTMF digit duration to send */
184         int pref_codec;                         /*!< Preferred codec */
185         int peercapability;                     /*!< Capabilities learned from peer */
186         int jointcapability;                    /*!< Common capabilities for local and remote side */
187         struct ast_codec_pref peer_prefs;       /*!< Preferenced list of codecs which remote side supports */
188         int dtmf_pt[2];                         /*!< Payload code used for RFC2833/CISCO messages */
189         int curDTMF;                            /*!< DTMF tone being generated to Asterisk side */
190         int DTMFsched;                          /*!< Scheduler descriptor for DTMF */
191         int update_rtp_info;                    /*!< Configuration of fd's array is pending */
192         int recvonly;                           /*!< Peer isn't wish to receive our voice stream */
193         int txDtmfDigit;                        /*!< DTMF digit being to send to H.323 side */
194         int noInbandDtmf;                       /*!< Inband DTMF processing by DSP isn't available */
195         int connection_established;             /*!< Call got CONNECT message */
196         int got_progress;                       /*!< Call got PROGRESS message, pass inband audio */
197         struct oh323_pvt *next;                 /*!< Next channel in list */
198 } *iflist = NULL;
199
200 /*! \brief H323 User list */
201 static struct h323_user_list {
202         ASTOBJ_CONTAINER_COMPONENTS(struct oh323_user);
203 } userl;
204
205 /*! \brief H323 peer list */
206 static struct h323_peer_list {
207         ASTOBJ_CONTAINER_COMPONENTS(struct oh323_peer);
208 } peerl;
209
210 /*! \brief H323 alias list */
211 static struct h323_alias_list {
212         ASTOBJ_CONTAINER_COMPONENTS(struct oh323_alias);
213 } aliasl;
214
215 /* Asterisk RTP stuff */
216 static struct sched_context *sched;
217 static struct io_context *io;
218
219 AST_MUTEX_DEFINE_STATIC(iflock);        /*!< Protect the interface list (oh323_pvt) */
220
221 /*! \brief  Protect the H.323 monitoring thread, so only one process can kill or start it, and not
222    when it's doing something critical. */
223 AST_MUTEX_DEFINE_STATIC(monlock);
224
225 /*! \brief Protect the H.323 capabilities list, to avoid more than one channel to set the capabilities simultaneaously in the h323 stack. */
226 AST_MUTEX_DEFINE_STATIC(caplock);
227
228 /*! \brief Protect the reload process */
229 AST_MUTEX_DEFINE_STATIC(h323_reload_lock);
230 static int h323_reloading = 0;
231
232 /*! \brief This is the thread for the monitor which checks for input on the channels
233    which are not currently in use. */
234 static pthread_t monitor_thread = AST_PTHREADT_NULL;
235 static int restart_monitor(void);
236 static int h323_do_reload(void);
237
238 static struct ast_channel *oh323_request(const char *type, int format, void *data, int *cause);
239 static int oh323_digit_begin(struct ast_channel *c, char digit);
240 static int oh323_digit_end(struct ast_channel *c, char digit, unsigned int duration);
241 static int oh323_call(struct ast_channel *c, char *dest, int timeout);
242 static int oh323_hangup(struct ast_channel *c);
243 static int oh323_answer(struct ast_channel *c);
244 static struct ast_frame *oh323_read(struct ast_channel *c);
245 static int oh323_write(struct ast_channel *c, struct ast_frame *frame);
246 static int oh323_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
247 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
248
249 static const struct ast_channel_tech oh323_tech = {
250         .type = "H323",
251         .description = tdesc,
252         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
253         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
254         .requester = oh323_request,
255         .send_digit_begin = oh323_digit_begin,
256         .send_digit_end = oh323_digit_end,
257         .call = oh323_call,
258         .hangup = oh323_hangup,
259         .answer = oh323_answer,
260         .read = oh323_read,
261         .write = oh323_write,
262         .indicate = oh323_indicate,
263         .fixup = oh323_fixup,
264         /* disable, for now */
265 #if 0
266         .bridge = ast_rtp_bridge,
267 #endif
268 };
269
270 static const char* redirectingreason2str(int redirectingreason)
271 {
272         switch (redirectingreason) {
273         case 0:
274                 return "UNKNOWN";
275         case 1:
276                 return "BUSY";
277         case 2:
278                 return "NO_REPLY";
279         case 0xF:
280                 return "UNCONDITIONAL";
281         default:
282                 return "NOREDIRECT";
283         }
284 }
285
286 static void oh323_destroy_alias(struct oh323_alias *alias)
287 {
288         if (h323debug)
289                 ast_log(LOG_DEBUG, "Destroying alias '%s'\n", alias->name);
290         free(alias);
291 }
292
293 static void oh323_destroy_user(struct oh323_user *user)
294 {
295         if (h323debug)
296                 ast_log(LOG_DEBUG, "Destroying user '%s'\n", user->name);
297         ast_free_ha(user->ha);
298         free(user);
299 }
300
301 static void oh323_destroy_peer(struct oh323_peer *peer)
302 {
303         if (h323debug)
304                 ast_log(LOG_DEBUG, "Destroying peer '%s'\n", peer->name);
305         ast_free_ha(peer->ha);
306         free(peer);
307 }
308
309 static int oh323_simulate_dtmf_end(void *data)
310 {
311         struct oh323_pvt *pvt = data;
312
313         if (pvt) {
314                 ast_mutex_lock(&pvt->lock);
315                 /* Don't hold pvt lock while trying to lock the channel */
316                 while(pvt->owner && ast_channel_trylock(pvt->owner)) {
317                         ast_mutex_unlock(&pvt->lock);
318                         usleep(1);
319                         ast_mutex_lock(&pvt->lock);
320                 }
321
322                 if (pvt->owner) {
323                         struct ast_frame f = {
324                                 .frametype = AST_FRAME_DTMF_END,
325                                 .subclass = pvt->curDTMF,
326                                 .samples = 0,
327                                 .src = "SIMULATE_DTMF_END",
328                         };
329                         ast_queue_frame(pvt->owner, &f);
330                         ast_channel_unlock(pvt->owner);
331                 }
332
333                 pvt->DTMFsched = -1;
334                 ast_mutex_unlock(&pvt->lock);
335         }
336
337         return 0;
338 }
339
340 /*! \brief Channel and private structures should be already locked */
341 static void __oh323_update_info(struct ast_channel *c, struct oh323_pvt *pvt)
342 {
343         if (c->nativeformats != pvt->nativeformats) {
344                 if (h323debug)
345                         ast_log(LOG_DEBUG, "Preparing %s for new native format\n", c->name);
346                 c->nativeformats = pvt->nativeformats;
347                 ast_set_read_format(c, c->readformat);
348                 ast_set_write_format(c, c->writeformat);
349         }
350         if (pvt->needhangup) {
351                 if (h323debug)
352                         ast_log(LOG_DEBUG, "Process pending hangup for %s\n", c->name);
353                 c->_softhangup |= AST_SOFTHANGUP_DEV;
354                 c->hangupcause = pvt->hangupcause;
355                 ast_queue_hangup(c);
356                 pvt->needhangup = 0;
357                 pvt->newstate = pvt->newcontrol = pvt->newdigit = pvt->DTMFsched = -1;
358         }
359         if (pvt->newstate >= 0) {
360                 ast_setstate(c, pvt->newstate);
361                 pvt->newstate = -1;
362         }
363         if (pvt->newcontrol >= 0) {
364                 ast_queue_control(c, pvt->newcontrol);
365                 pvt->newcontrol = -1;
366         }
367         if (pvt->newdigit >= 0) {
368                 struct ast_frame f = {
369                         .frametype = AST_FRAME_DTMF_END,
370                         .subclass = pvt->newdigit,
371                         .samples = pvt->newduration * 8,
372                         .len = pvt->newduration,
373                         .src = "UPDATE_INFO",
374                 };
375                 if (pvt->newdigit == ' ') {             /* signalUpdate message */
376                         f.subclass = pvt->curDTMF;
377                         if (pvt->DTMFsched >= 0) {
378                                 ast_sched_del(sched, pvt->DTMFsched);
379                                 pvt->DTMFsched = -1;
380                         }
381                 } else {                                                /* Regular input or signal message */
382                         if (pvt->newduration) {         /* This is a signal, signalUpdate follows */
383                                 f.frametype = AST_FRAME_DTMF_BEGIN;
384                                 if (pvt->DTMFsched >= 0)
385                                         ast_sched_del(sched, pvt->DTMFsched);
386                                 pvt->DTMFsched = ast_sched_add(sched, pvt->newduration, oh323_simulate_dtmf_end, pvt);
387                                 if (h323debug)
388                                         ast_log(LOG_DTMF, "Scheduled DTMF END simulation for %d ms, id=%d\n", pvt->newduration, pvt->DTMFsched);
389                         }
390                         pvt->curDTMF = pvt->newdigit;
391                 }
392                 ast_queue_frame(c, &f);
393                 pvt->newdigit = -1;
394         }
395         if (pvt->update_rtp_info > 0) {
396                 if (pvt->rtp) {
397                         ast_jb_configure(c, &global_jbconf);
398                         c->fds[0] = ast_rtp_fd(pvt->rtp);
399                         c->fds[1] = ast_rtcp_fd(pvt->rtp);
400                         ast_queue_frame(pvt->owner, &ast_null_frame);   /* Tell Asterisk to apply changes */
401                 }
402                 pvt->update_rtp_info = -1;
403         }
404 }
405
406 /*! \brief Only channel structure should be locked */
407 static void oh323_update_info(struct ast_channel *c)
408 {
409         struct oh323_pvt *pvt = c->tech_pvt;
410
411         if (pvt) {
412                 ast_mutex_lock(&pvt->lock);
413                 __oh323_update_info(c, pvt);
414                 ast_mutex_unlock(&pvt->lock);
415         }
416 }
417
418 static void cleanup_call_details(call_details_t *cd)
419 {
420         if (cd->call_token) {
421                 free(cd->call_token);
422                 cd->call_token = NULL;
423         }
424         if (cd->call_source_aliases) {
425                 free(cd->call_source_aliases);
426                 cd->call_source_aliases = NULL;
427         }
428         if (cd->call_dest_alias) {
429                 free(cd->call_dest_alias);
430                 cd->call_dest_alias = NULL;
431         }
432         if (cd->call_source_name) {
433                 free(cd->call_source_name);
434                 cd->call_source_name = NULL;
435         }
436         if (cd->call_source_e164) {
437                 free(cd->call_source_e164);
438                 cd->call_source_e164 = NULL;
439         }
440         if (cd->call_dest_e164) {
441                 free(cd->call_dest_e164);
442                 cd->call_dest_e164 = NULL;
443         }
444         if (cd->sourceIp) {
445                 free(cd->sourceIp);
446                 cd->sourceIp = NULL;
447         }
448         if (cd->redirect_number) {
449                 free(cd->redirect_number);
450                 cd->redirect_number = NULL;
451         }
452 }
453
454 static void __oh323_destroy(struct oh323_pvt *pvt)
455 {
456         struct oh323_pvt *cur, *prev = NULL;
457
458         if (pvt->DTMFsched >= 0) {
459                 ast_sched_del(sched, pvt->DTMFsched);
460                 pvt->DTMFsched = -1;
461         }
462
463         if (pvt->rtp) {
464                 ast_rtp_destroy(pvt->rtp);
465         }
466
467         /* Free dsp used for in-band DTMF detection */
468         if (pvt->vad) {
469                 ast_dsp_free(pvt->vad);
470         }
471         cleanup_call_details(&pvt->cd);
472
473         /* Unlink us from the owner if we have one */
474         if (pvt->owner) {
475                 ast_channel_lock(pvt->owner);
476                 if (h323debug)
477                         ast_log(LOG_DEBUG, "Detaching from %s\n", pvt->owner->name);
478                 pvt->owner->tech_pvt = NULL;
479                 ast_channel_unlock(pvt->owner);
480         }
481         cur = iflist;
482         while(cur) {
483                 if (cur == pvt) {
484                         if (prev)
485                                 prev->next = cur->next;
486                         else
487                                 iflist = cur->next;
488                         break;
489                 }
490                 prev = cur;
491                 cur = cur->next;
492         }
493         if (!cur) {
494                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
495         } else {
496                 ast_mutex_unlock(&pvt->lock);
497                 ast_mutex_destroy(&pvt->lock);
498                 free(pvt);
499         }
500 }
501
502 static void oh323_destroy(struct oh323_pvt *pvt)
503 {
504         if (h323debug) {
505                 ast_log(LOG_DEBUG, "Destroying channel %s\n", (pvt->owner ? pvt->owner->name : "<unknown>"));
506         }
507         ast_mutex_lock(&iflock);
508         ast_mutex_lock(&pvt->lock);
509         __oh323_destroy(pvt);
510         ast_mutex_unlock(&iflock);
511 }
512
513 static int oh323_digit_begin(struct ast_channel *c, char digit)
514 {
515         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
516         char *token;
517
518         if (!pvt) {
519                 ast_log(LOG_ERROR, "No private structure?! This is bad\n");
520                 return -1;
521         }
522         ast_mutex_lock(&pvt->lock);
523         if (pvt->rtp &&
524                 (((pvt->options.dtmfmode & H323_DTMF_RFC2833) && pvt->dtmf_pt[0])
525                  /*|| ((pvt->options.dtmfmode & H323_DTMF_CISCO) && pvt->dtmf_pt[1]))*/)) {
526                 /* out-of-band DTMF */
527                 if (h323debug) {
528                         ast_log(LOG_DTMF, "Begin sending out-of-band digit %c on %s\n", digit, c->name);
529                 }
530                 ast_rtp_senddigit_begin(pvt->rtp, digit);
531                 ast_mutex_unlock(&pvt->lock);
532         } else if (pvt->txDtmfDigit != digit) {
533                 /* in-band DTMF */
534                 if (h323debug) {
535                         ast_log(LOG_DTMF, "Begin sending inband digit %c on %s\n", digit, c->name);
536                 }
537                 pvt->txDtmfDigit = digit;
538                 token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
539                 ast_mutex_unlock(&pvt->lock);
540                 h323_send_tone(token, digit);
541                 if (token) {
542                         free(token);
543                 }
544         } else
545                 ast_mutex_unlock(&pvt->lock);
546         oh323_update_info(c);
547         return 0;
548 }
549
550 /*! \brief
551  * Send (play) the specified digit to the channel.
552  *
553  */
554 static int oh323_digit_end(struct ast_channel *c, char digit, unsigned int duration)
555 {
556         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
557         char *token;
558
559         if (!pvt) {
560                 ast_log(LOG_ERROR, "No private structure?! This is bad\n");
561                 return -1;
562         }
563         ast_mutex_lock(&pvt->lock);
564         if (pvt->rtp && (pvt->options.dtmfmode & H323_DTMF_RFC2833) && ((pvt->dtmf_pt[0] > 0) || (pvt->dtmf_pt[0] > 0))) {
565                 /* out-of-band DTMF */
566                 if (h323debug) {
567                         ast_log(LOG_DTMF, "End sending out-of-band digit %c on %s, duration %d\n", digit, c->name, duration);
568                 }
569                 ast_rtp_senddigit_end(pvt->rtp, digit);
570                 ast_mutex_unlock(&pvt->lock);
571         } else {
572                 /* in-band DTMF */
573                 if (h323debug) {
574                         ast_log(LOG_DTMF, "End sending inband digit %c on %s, duration %d\n", digit, c->name, duration);
575                 }
576                 pvt->txDtmfDigit = ' ';
577                 token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
578                 ast_mutex_unlock(&pvt->lock);
579                 h323_send_tone(token, ' ');
580                 if (token) {
581                         free(token);
582                 }
583         }
584         oh323_update_info(c);
585         return 0;
586 }
587
588 /*! \brief
589  * Make a call over the specified channel to the specified
590  * destination.
591  * Returns -1 on error, 0 on success.
592  */
593 static int oh323_call(struct ast_channel *c, char *dest, int timeout)
594 {
595         int res = 0;
596         struct oh323_pvt *pvt = (struct oh323_pvt *)c->tech_pvt;
597         const char *addr;
598         char called_addr[1024];
599
600         if (h323debug) {
601                 ast_log(LOG_DEBUG, "Calling to %s on %s\n", dest, c->name);
602         }
603         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
604                 ast_log(LOG_WARNING, "Line is already in use (%s)\n", c->name);
605                 return -1;
606         }
607         ast_mutex_lock(&pvt->lock);
608         if (!gatekeeper_disable) {
609                 if (ast_strlen_zero(pvt->exten)) {
610                         ast_copy_string(called_addr, dest, sizeof(called_addr));
611                 } else {
612                         snprintf(called_addr, sizeof(called_addr), "%s@%s", pvt->exten, dest);
613                 }
614         } else {
615                 res = htons(pvt->sa.sin_port);
616                 addr = ast_inet_ntoa(pvt->sa.sin_addr);
617                 if (ast_strlen_zero(pvt->exten)) {
618                         snprintf(called_addr, sizeof(called_addr), "%s:%d", addr, res);
619                 } else {
620                         snprintf(called_addr, sizeof(called_addr), "%s@%s:%d", pvt->exten, addr, res);
621                 }
622         }
623         /* make sure null terminated */
624         called_addr[sizeof(called_addr) - 1] = '\0';
625
626         if (c->cid.cid_num)
627                 ast_copy_string(pvt->options.cid_num, c->cid.cid_num, sizeof(pvt->options.cid_num));
628
629         if (c->cid.cid_name)
630                 ast_copy_string(pvt->options.cid_name, c->cid.cid_name, sizeof(pvt->options.cid_name));
631
632         if (c->cid.cid_rdnis) {
633                 ast_copy_string(pvt->options.cid_rdnis, c->cid.cid_rdnis, sizeof(pvt->options.cid_rdnis));
634         }
635
636         pvt->options.presentation = c->cid.cid_pres;
637         pvt->options.type_of_number = c->cid.cid_ton;
638
639         if ((addr = pbx_builtin_getvar_helper(c, "PRIREDIRECTREASON"))) {
640                 if (!strcasecmp(addr, "UNKNOWN"))
641                         pvt->options.redirect_reason = 0;
642                 else if (!strcasecmp(addr, "BUSY"))
643                         pvt->options.redirect_reason = 1;
644                 else if (!strcasecmp(addr, "NO_REPLY"))
645                         pvt->options.redirect_reason = 2;
646                 else if (!strcasecmp(addr, "UNCONDITIONAL"))
647                         pvt->options.redirect_reason = 15;
648                 else
649                         pvt->options.redirect_reason = -1;
650         } else
651                 pvt->options.redirect_reason = -1;
652
653         pvt->options.transfer_capability = c->transfercapability;
654
655         /* indicate that this is an outgoing call */
656         pvt->outgoing = 1;
657
658         if (option_verbose > 2)
659                 ast_verbose(VERBOSE_PREFIX_3 "Requested transfer capability: 0x%.2x - %s\n", c->transfercapability, ast_transfercapability2str(c->transfercapability));
660         if (h323debug)
661                 ast_log(LOG_DEBUG, "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_log(LOG_DEBUG, "Answering on %s\n", c->name);
680
681         ast_mutex_lock(&pvt->lock);
682         token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
683         ast_mutex_unlock(&pvt->lock);
684         res = h323_answering_call(token, 0);
685         if (token)
686                 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_log(LOG_DEBUG, "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 ? 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                         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_log(LOG_DEBUG, "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 ? 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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "OH323: Indicated %d on %s, res=%d\n", condition, token, res);
940         if (token)
941                 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_log(LOG_DEBUG, "Created RTP channel\n");
981
982         ast_rtp_settos(pvt->rtp, tos);
983
984         if (h323debug)
985                 ast_log(LOG_DEBUG, "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, "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 = 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 = (struct oh323_pvt *) malloc(sizeof(struct oh323_pvt));
1116         if (!pvt) {
1117                 ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
1118                 return NULL;
1119         }
1120         memset(pvt, 0, sizeof(struct oh323_pvt));
1121         pvt->cd.redirect_reason = -1;
1122         pvt->cd.transfer_capability = -1;
1123         /* Ensure the call token is allocated for outgoing call */
1124         if (!callid) {
1125                 if ((pvt->cd).call_token == NULL) {
1126                         (pvt->cd).call_token = (char *)malloc(128);
1127                 }
1128                 if (!pvt->cd.call_token) {
1129                         ast_log(LOG_ERROR, "Not enough memory to alocate call token\n");
1130                         ast_rtp_destroy(pvt->rtp);
1131                         free(pvt);
1132                         return NULL;
1133                 }
1134                 memset((char *)(pvt->cd).call_token, 0, 128);
1135                 pvt->cd.call_reference = callid;
1136         }
1137         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1138         pvt->jointcapability = pvt->options.capability;
1139         if (pvt->options.dtmfmode & (H323_DTMF_RFC2833 | H323_DTMF_CISCO)) {
1140                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1141         } else {
1142                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1143         }
1144         ast_copy_string(pvt->context, default_context, sizeof(pvt->context));
1145         pvt->newstate = pvt->newcontrol = pvt->newdigit = pvt->update_rtp_info = pvt->DTMFsched = -1;
1146         ast_mutex_init(&pvt->lock);
1147         /* Add to interface list */
1148         ast_mutex_lock(&iflock);
1149         pvt->next = iflist;
1150         iflist = pvt;
1151         ast_mutex_unlock(&iflock);
1152         return pvt;
1153 }
1154
1155 static struct oh323_pvt *find_call_locked(int call_reference, const char *token)
1156 {
1157         struct oh323_pvt *pvt;
1158
1159         ast_mutex_lock(&iflock);
1160         pvt = iflist;
1161         while(pvt) {
1162                 if (!pvt->needdestroy && ((signed int)pvt->cd.call_reference == call_reference)) {
1163                         /* Found the call */
1164                         if ((token != NULL) && (!strcmp(pvt->cd.call_token, token))) {
1165                                 ast_mutex_lock(&pvt->lock);
1166                                 ast_mutex_unlock(&iflock);
1167                                 return pvt;
1168                         } else if (token == NULL) {
1169                                 ast_log(LOG_WARNING, "Call Token is NULL\n");
1170                                 ast_mutex_lock(&pvt->lock);
1171                                 ast_mutex_unlock(&iflock);
1172                                 return pvt;
1173                         }
1174                 }
1175                 pvt = pvt->next;
1176         }
1177         ast_mutex_unlock(&iflock);
1178         return NULL;
1179 }
1180
1181 static int update_state(struct oh323_pvt *pvt, int state, int signal)
1182 {
1183         if (!pvt)
1184                 return 0;
1185         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
1186                 if (state >= 0)
1187                         ast_setstate(pvt->owner, state);
1188                 if (signal >= 0)
1189                         ast_queue_control(pvt->owner, signal);
1190                 ast_channel_unlock(pvt->owner);
1191                 return 1;
1192         }
1193         else {
1194                 if (state >= 0)
1195                         pvt->newstate = state;
1196                 if (signal >= 0)
1197                         pvt->newcontrol = signal;
1198                 return 0;
1199         }
1200 }
1201
1202 static struct oh323_alias *build_alias(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
1203 {
1204         struct oh323_alias *alias;
1205         int found = 0;
1206
1207         alias = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&aliasl, name, name, 0, 0, strcasecmp);
1208
1209         if (alias)
1210                 found++;
1211         else {
1212                 if (!(alias = (struct oh323_alias *)calloc(1, sizeof(*alias))))
1213                         return NULL;
1214                 ASTOBJ_INIT(alias);
1215         }
1216         if (!found && name)
1217                 ast_copy_string(alias->name, name, sizeof(alias->name));
1218         for (; v || ((v = alt) && !(alt = NULL)); v = v->next) {
1219                 if (!strcasecmp(v->name, "e164")) {
1220                         ast_copy_string(alias->e164, v->value, sizeof(alias->e164));
1221                 } else if (!strcasecmp(v->name, "prefix")) {
1222                         ast_copy_string(alias->prefix, v->value, sizeof(alias->prefix));
1223                 } else if (!strcasecmp(v->name, "context")) {
1224                         ast_copy_string(alias->context, v->value, sizeof(alias->context));
1225                 } else if (!strcasecmp(v->name, "secret")) {
1226                         ast_copy_string(alias->secret, v->value, sizeof(alias->secret));
1227                 } else {
1228                         if (strcasecmp(v->value, "h323")) {
1229                                 ast_log(LOG_WARNING, "Keyword %s does not make sense in type=h323\n", v->name);
1230                         }
1231                 }
1232         }
1233         ASTOBJ_UNMARK(alias);
1234         return alias;
1235 }
1236
1237 static struct oh323_alias *realtime_alias(const char *alias)
1238 {
1239         struct ast_variable *var, *tmp;
1240         struct oh323_alias *a;
1241
1242         var = ast_load_realtime("h323", "name", alias, NULL);
1243
1244         if (!var)
1245                 return NULL;
1246
1247         for (tmp = var; tmp; tmp = tmp->next) {
1248                 if (!strcasecmp(tmp->name, "type") &&
1249                 !(!strcasecmp(tmp->value, "alias") || !strcasecmp(tmp->value, "h323"))) {
1250                         ast_variables_destroy(var);
1251                         return NULL;
1252                 }
1253         }
1254
1255         a = build_alias(alias, var, NULL, 1);
1256
1257         ast_variables_destroy(var);
1258
1259         return a;
1260 }
1261
1262 static int update_common_options(struct ast_variable *v, struct call_options *options)
1263 {
1264         int tmp;
1265         char *val, *opt;
1266
1267         if (!strcasecmp(v->name, "allow")) {
1268                 ast_parse_allow_disallow(&options->prefs, &options->capability, v->value, 1);
1269         } else if (!strcasecmp(v->name, "disallow")) {
1270                 ast_parse_allow_disallow(&options->prefs, &options->capability, v->value, 0);
1271         } else if (!strcasecmp(v->name, "dtmfmode")) {
1272                 val = ast_strdupa(v->value);
1273                 if ((opt = strchr(val, ':')) != (char *)NULL) {
1274                         *opt++ = '\0';
1275                         tmp = atoi(opt);
1276                 }
1277                 if (!strcasecmp(v->value, "inband")) {
1278                         options->dtmfmode |= H323_DTMF_INBAND;
1279                 } else if (!strcasecmp(val, "rfc2833")) {
1280                         options->dtmfmode |= H323_DTMF_RFC2833;
1281                         if (!opt) {
1282                                 options->dtmfcodec[0] = H323_DTMF_RFC2833_PT;
1283                         } else if ((tmp >= 96) && (tmp < 128)) {
1284                                 options->dtmfcodec[0] = tmp;
1285                         } else {
1286                                 options->dtmfcodec[0] = H323_DTMF_RFC2833_PT;
1287                                 ast_log(LOG_WARNING, "Unknown rfc2833 payload %s specified at line %d, using default %d\n", opt, v->lineno, options->dtmfcodec[0]);
1288                         }
1289                 } else if (!strcasecmp(val, "cisco")) {
1290                         options->dtmfmode |= H323_DTMF_CISCO;
1291                         if (!opt) {
1292                                 options->dtmfcodec[1] = H323_DTMF_CISCO_PT;
1293                         } else if ((tmp >= 96) && (tmp < 128)) {
1294                                 options->dtmfcodec[1] = tmp;
1295                         } else {
1296                                 options->dtmfcodec[1] = H323_DTMF_CISCO_PT;
1297                                 ast_log(LOG_WARNING, "Unknown Cisco DTMF payload %s specified at line %d, using default %d\n", opt, v->lineno, options->dtmfcodec[1]);
1298                         }
1299                 } else if (!strcasecmp(v->value, "h245-signal")) {
1300                         options->dtmfmode |= H323_DTMF_SIGNAL;
1301                 } else {
1302                         ast_log(LOG_WARNING, "Unknown dtmf mode '%s' at line %d\n", v->value, v->lineno);
1303                 }
1304         } else if (!strcasecmp(v->name, "dtmfcodec")) {
1305                 ast_log(LOG_NOTICE, "Option %s at line %d is deprecated. Use dtmfmode=rfc2833[:<payload>] instead.\n", v->name, v->lineno);
1306                 tmp = atoi(v->value);
1307                 if (tmp < 96)
1308                         ast_log(LOG_WARNING, "Invalid %s value %s at line %d\n", v->name, v->value, v->lineno);
1309                 else
1310                         options->dtmfcodec[0] = tmp;
1311         } else if (!strcasecmp(v->name, "bridge")) {
1312                 options->bridge = ast_true(v->value);
1313         } else if (!strcasecmp(v->name, "nat")) {
1314                 options->nat = ast_true(v->value);
1315         } else if (!strcasecmp(v->name, "fastStart")) {
1316                 options->fastStart = ast_true(v->value);
1317         } else if (!strcasecmp(v->name, "h245Tunneling")) {
1318                 options->h245Tunneling = ast_true(v->value);
1319         } else if (!strcasecmp(v->name, "silenceSuppression")) {
1320                 options->silenceSuppression = ast_true(v->value);
1321         } else if (!strcasecmp(v->name, "progress_setup")) {
1322                 tmp = atoi(v->value);
1323                 if ((tmp != 0) && (tmp != 1) && (tmp != 3) && (tmp != 8)) {
1324                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d, assuming 0\n", v->value, v->name, v->lineno);
1325                         tmp = 0;
1326                 }
1327                 options->progress_setup = tmp;
1328         } else if (!strcasecmp(v->name, "progress_alert")) {
1329                 tmp = atoi(v->value);
1330                 if ((tmp != 0) && (tmp != 1) && (tmp != 8)) {
1331                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d, assuming 0\n", v->value, v->name, v->lineno);
1332                         tmp = 0;
1333                 }
1334                 options->progress_alert = tmp;
1335         } else if (!strcasecmp(v->name, "progress_audio")) {
1336                 options->progress_audio = ast_true(v->value);
1337         } else if (!strcasecmp(v->name, "callerid")) {
1338                 ast_callerid_split(v->value, options->cid_name, sizeof(options->cid_name), options->cid_num, sizeof(options->cid_num));
1339         } else if (!strcasecmp(v->name, "fullname")) {
1340                 ast_copy_string(options->cid_name, v->value, sizeof(options->cid_name));
1341         } else if (!strcasecmp(v->name, "cid_number")) {
1342                 ast_copy_string(options->cid_num, v->value, sizeof(options->cid_num));
1343         } else if (!strcasecmp(v->name, "tunneling")) {
1344                 if (!strcasecmp(v->value, "none"))
1345                         options->tunnelOptions = 0;
1346                 else if (!strcasecmp(v->value, "cisco"))
1347                         options->tunnelOptions |= H323_TUNNEL_CISCO;
1348                 else if (!strcasecmp(v->value, "qsig"))
1349                         options->tunnelOptions |= H323_TUNNEL_QSIG;
1350                 else
1351                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d\n", v->value, v->name, v->lineno);
1352         } else if (!strcasecmp(v->name, "hold")) {
1353                 if (!strcasecmp(v->value, "none"))
1354                         options->holdHandling = ~0;
1355                 else if (!strcasecmp(v->value, "notify"))
1356                         options->holdHandling |= H323_HOLD_NOTIFY;
1357                 else if (!strcasecmp(v->value, "q931only"))
1358                         options->holdHandling |= H323_HOLD_NOTIFY | H323_HOLD_Q931ONLY;
1359                 else if (!strcasecmp(v->value, "h450"))
1360                         options->holdHandling |= H323_HOLD_H450;
1361                 else
1362                         ast_log(LOG_WARNING, "Invalid value %s for %s at line %d\n", v->value, v->name, v->lineno);
1363         } else
1364                 return 1;
1365
1366         return 0;
1367 }
1368
1369 static struct oh323_user *build_user(char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
1370 {
1371         struct oh323_user *user;
1372         struct ast_ha *oldha;
1373         int found = 0;
1374         int format;
1375
1376         user = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&userl, name, name, 0, 0, strcmp);
1377
1378         if (user)
1379                 found++;
1380         else {
1381                 if (!(user = (struct oh323_user *)calloc(1, sizeof(*user))))
1382                         return NULL;
1383                 ASTOBJ_INIT(user);
1384         }
1385         oldha = user->ha;
1386         user->ha = (struct ast_ha *)NULL;
1387         memcpy(&user->options, &global_options, sizeof(user->options));
1388         user->options.dtmfmode = 0;
1389         user->options.holdHandling = 0;
1390         /* Set default context */
1391         ast_copy_string(user->context, default_context, sizeof(user->context));
1392         if (user && !found)
1393                 ast_copy_string(user->name, name, sizeof(user->name));
1394
1395 #if 0 /* XXX Port channel variables functionality from chan_sip XXX */
1396         if (user->chanvars) {
1397                 ast_variables_destroy(user->chanvars);
1398                 user->chanvars = NULL;
1399         }
1400 #endif
1401
1402         for (; v || ((v = alt) && !(alt = NULL)); v = v->next) {
1403                 if (!update_common_options(v, &user->options))
1404                         continue;
1405                 if (!strcasecmp(v->name, "context")) {
1406                         ast_copy_string(user->context, v->value, sizeof(user->context));
1407                 } else if (!strcasecmp(v->name, "secret")) {
1408                         ast_copy_string(user->secret, v->value, sizeof(user->secret));
1409                 } else if (!strcasecmp(v->name, "accountcode")) {
1410                         ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
1411                 } else if (!strcasecmp(v->name, "host")) {
1412                         if (!strcasecmp(v->value, "dynamic")) {
1413                                 ast_log(LOG_ERROR, "A dynamic host on a type=user does not make any sense\n");
1414                                 ASTOBJ_UNREF(user, oh323_destroy_user);
1415                                 return NULL;
1416                         } else if (ast_get_ip(&user->addr, v->value)) {
1417                                 ASTOBJ_UNREF(user, oh323_destroy_user);
1418                                 return NULL;
1419                         }
1420                         /* Let us know we need to use ip authentication */
1421                         user->host = 1;
1422                 } else if (!strcasecmp(v->name, "amaflags")) {
1423                         format = ast_cdr_amaflags2int(v->value);
1424                         if (format < 0) {
1425                                 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
1426                         } else {
1427                                 user->amaflags = format;
1428                         }
1429                 } else if (!strcasecmp(v->name, "permit") ||
1430                                         !strcasecmp(v->name, "deny")) {
1431                         int ha_error = 0;
1432
1433                         user->ha = ast_append_ha(v->name, v->value, user->ha, &ha_error);
1434                         if (ha_error)
1435                                 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
1436                 }
1437         }
1438         if (!user->options.dtmfmode)
1439                 user->options.dtmfmode = global_options.dtmfmode;
1440         if (user->options.holdHandling == ~0)
1441                 user->options.holdHandling = 0;
1442         else if (!user->options.holdHandling)
1443                 user->options.holdHandling = global_options.holdHandling;
1444         ASTOBJ_UNMARK(user);
1445         ast_free_ha(oldha);
1446         return user;
1447 }
1448
1449 static struct oh323_user *realtime_user(const call_details_t *cd)
1450 {
1451         struct ast_variable *var, *tmp;
1452         struct oh323_user *user;
1453         char *username;
1454
1455         if (userbyalias)
1456                 var = ast_load_realtime("h323", "name", username = cd->call_source_aliases, NULL);
1457         else {
1458                 username = (char *)NULL;
1459                 var = ast_load_realtime("h323", "host", cd->sourceIp, NULL);
1460         }
1461
1462         if (!var)
1463                 return NULL;
1464
1465         for (tmp = var; tmp; tmp = tmp->next) {
1466                 if (!strcasecmp(tmp->name, "type") &&
1467                 !(!strcasecmp(tmp->value, "user") || !strcasecmp(tmp->value, "friend"))) {
1468                         ast_variables_destroy(var);
1469                         return NULL;
1470                 } else if (!username && !strcasecmp(tmp->name, "name"))
1471                         username = tmp->value;
1472         }
1473
1474         if (!username) {
1475                 ast_log(LOG_WARNING, "Cannot determine user name for IP address %s\n", cd->sourceIp);
1476                 ast_variables_destroy(var);
1477                 return NULL;
1478         }
1479
1480         user = build_user(username, var, NULL, 1);
1481
1482         ast_variables_destroy(var);
1483
1484         return user;
1485 }
1486
1487 static struct oh323_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
1488 {
1489         struct oh323_peer *peer;
1490         struct ast_ha *oldha;
1491         int found = 0;
1492
1493         peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
1494
1495         if (peer)
1496                 found++;
1497         else {
1498                 if (!(peer = (struct oh323_peer*)calloc(1, sizeof(*peer))))
1499                         return NULL;
1500                 ASTOBJ_INIT(peer);
1501         }
1502         oldha = peer->ha;
1503         peer->ha = NULL;
1504         memcpy(&peer->options, &global_options, sizeof(peer->options));
1505         peer->options.dtmfmode = 0;
1506         peer->options.holdHandling = 0;
1507         peer->addr.sin_port = htons(h323_signalling_port);
1508         peer->addr.sin_family = AF_INET;
1509         if (!found && name)
1510                 ast_copy_string(peer->name, name, sizeof(peer->name));
1511
1512 #if 0 /* XXX Port channel variables functionality from chan_sip XXX */
1513         if (peer->chanvars) {
1514                 ast_variables_destroy(peer->chanvars);
1515                 peer->chanvars = NULL;
1516         }
1517 #endif
1518         /* Default settings for mailbox */
1519         peer->mailbox[0] = '\0';
1520
1521         for (; v || ((v = alt) && !(alt = NULL)); v = v->next) {
1522                 if (!update_common_options(v, &peer->options))
1523                         continue;
1524                 if (!strcasecmp(v->name, "host")) {
1525                         if (!strcasecmp(v->value, "dynamic")) {
1526                                 ast_log(LOG_ERROR, "Dynamic host configuration not implemented.\n");
1527                                 ASTOBJ_UNREF(peer, oh323_destroy_peer);
1528                                 return NULL;
1529                         }
1530                         if (ast_get_ip(&peer->addr, v->value)) {
1531                                 ast_log(LOG_ERROR, "Could not determine IP for %s\n", v->value);
1532                                 ASTOBJ_UNREF(peer, oh323_destroy_peer);
1533                                 return NULL;
1534                         }
1535                 } else if (!strcasecmp(v->name, "port")) {
1536                         peer->addr.sin_port = htons(atoi(v->value));
1537                 } else if (!strcasecmp(v->name, "permit") ||
1538                                         !strcasecmp(v->name, "deny")) {
1539                         int ha_error = 0;
1540
1541                         peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
1542                         if (ha_error)
1543                                 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
1544                 } else if (!strcasecmp(v->name, "mailbox")) {
1545                         ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
1546                 }
1547         }
1548         if (!peer->options.dtmfmode)
1549                 peer->options.dtmfmode = global_options.dtmfmode;
1550         if (peer->options.holdHandling == ~0)
1551                 peer->options.holdHandling = 0;
1552         else if (!peer->options.holdHandling)
1553                 peer->options.holdHandling = global_options.holdHandling;
1554         ASTOBJ_UNMARK(peer);
1555         ast_free_ha(oldha);
1556         return peer;
1557 }
1558
1559 static struct oh323_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1560 {
1561         struct oh323_peer *peer;
1562         struct ast_variable *var;
1563         struct ast_variable *tmp;
1564         const char *addr;
1565
1566         /* First check on peer name */
1567         if (peername)
1568                 var = ast_load_realtime("h323", "name", peername, addr = NULL);
1569         else if (sin) /* Then check on IP address for dynamic peers */
1570                 var = ast_load_realtime("h323", "host", addr = ast_inet_ntoa(sin->sin_addr), NULL);
1571         else
1572                 return NULL;
1573
1574         if (!var)
1575                 return NULL;
1576
1577         for (tmp = var; tmp; tmp = tmp->next) {
1578                 /* If this is type=user, then skip this object. */
1579                 if (!strcasecmp(tmp->name, "type") &&
1580                                 !(!strcasecmp(tmp->value, "peer") || !strcasecmp(tmp->value, "friend"))) {
1581                         ast_variables_destroy(var);
1582                         return NULL;
1583                 } else if (!peername && !strcasecmp(tmp->name, "name")) {
1584                         peername = tmp->value;
1585                 }
1586         }
1587
1588         if (!peername) {        /* Did not find peer in realtime */
1589                 ast_log(LOG_WARNING, "Cannot determine peer name for IP address %s\n", addr);
1590                 ast_variables_destroy(var);
1591                 return NULL;
1592         }
1593
1594         /* Peer found in realtime, now build it in memory */
1595         peer = build_peer(peername, var, NULL, 1);
1596
1597         ast_variables_destroy(var);
1598
1599         return peer;
1600 }
1601
1602 static int oh323_addrcmp_str(struct in_addr inaddr, char *addr)
1603 {
1604         return strcmp(ast_inet_ntoa(inaddr), addr);
1605 }
1606
1607 static struct oh323_user *find_user(const call_details_t *cd, int realtime)
1608 {
1609         struct oh323_user *u;
1610
1611         if (userbyalias)
1612                 u = ASTOBJ_CONTAINER_FIND(&userl, cd->call_source_aliases);
1613         else
1614                 u = ASTOBJ_CONTAINER_FIND_FULL(&userl, cd->sourceIp, addr.sin_addr, 0, 0, oh323_addrcmp_str);
1615
1616         if (!u && realtime)
1617                 u = realtime_user(cd);
1618
1619         if (!u && h323debug)
1620                 ast_log(LOG_DEBUG, "Could not find user by name %s or address %s\n", cd->call_source_aliases, cd->sourceIp);
1621
1622         return u;
1623 }
1624
1625 static int oh323_addrcmp(struct sockaddr_in addr, struct sockaddr_in *sin)
1626 {
1627         int res;
1628
1629         if (!sin)
1630                 res = -1;
1631         else
1632                 res = inaddrcmp(&addr , sin);
1633
1634         return res;
1635 }
1636
1637 static struct oh323_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1638 {
1639         struct oh323_peer *p;
1640
1641         if (peer)
1642                 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
1643         else
1644                 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, addr, 0, 0, oh323_addrcmp);
1645
1646         if (!p && realtime)
1647                 p = realtime_peer(peer, sin);
1648
1649         if (!p && h323debug)
1650                 ast_log(LOG_DEBUG, "Could not find peer by name %s or address %s\n", (peer ? peer : "<NONE>"), (sin ? ast_inet_ntoa(sin->sin_addr) : "<NONE>"));
1651
1652         return p;
1653 }
1654
1655 static int create_addr(struct oh323_pvt *pvt, char *opeer)
1656 {
1657         struct hostent *hp;
1658         struct ast_hostent ahp;
1659         struct oh323_peer *p;
1660         int portno;
1661         int found = 0;
1662         char *port;
1663         char *hostn;
1664         char peer[256] = "";
1665
1666         ast_copy_string(peer, opeer, sizeof(peer));
1667         port = strchr(peer, ':');
1668         if (port) {
1669                 *port = '\0';
1670                 port++;
1671         }
1672         pvt->sa.sin_family = AF_INET;
1673         p = find_peer(peer, NULL, 1);
1674         if (p) {
1675                 found++;
1676                 memcpy(&pvt->options, &p->options, sizeof(pvt->options));
1677                 pvt->jointcapability = pvt->options.capability;
1678                 if (pvt->options.dtmfmode) {
1679                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1680                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1681                         } else {
1682                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1683                         }
1684                 }
1685                 if (p->addr.sin_addr.s_addr) {
1686                         pvt->sa.sin_addr = p->addr.sin_addr;
1687                         pvt->sa.sin_port = p->addr.sin_port;
1688                 }
1689                 ASTOBJ_UNREF(p, oh323_destroy_peer);
1690         }
1691         if (!p && !found) {
1692                 hostn = peer;
1693                 if (port) {
1694                         portno = atoi(port);
1695                 } else {
1696                         portno = h323_signalling_port;
1697                 }
1698                 hp = ast_gethostbyname(hostn, &ahp);
1699                 if (hp) {
1700                         memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
1701                         pvt->sa.sin_port = htons(portno);
1702                         /* Look peer by address */
1703                         p = find_peer(NULL, &pvt->sa, 1);
1704                         memcpy(&pvt->options, (p ? &p->options : &global_options), sizeof(pvt->options));
1705                         pvt->jointcapability = pvt->options.capability;
1706                         if (p) {
1707                                 ASTOBJ_UNREF(p, oh323_destroy_peer);
1708                         }
1709                         if (pvt->options.dtmfmode) {
1710                                 if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1711                                         pvt->nonCodecCapability |= AST_RTP_DTMF;
1712                                 } else {
1713                                         pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1714                                 }
1715                         }
1716                         return 0;
1717                 } else {
1718                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1719                         return -1;
1720                 }
1721         } else if (!found) {
1722                 return -1;
1723         } else {
1724                 return 0;
1725         }
1726 }
1727 static struct ast_channel *oh323_request(const char *type, int format, void *data, int *cause)
1728 {
1729         int oldformat;
1730         struct oh323_pvt *pvt;
1731         struct ast_channel *tmpc = NULL;
1732         char *dest = (char *)data;
1733         char *ext, *host;
1734         char *h323id = NULL;
1735         char tmp[256], tmp1[256];
1736
1737         if (h323debug)
1738                 ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
1739
1740         pvt = oh323_alloc(0);
1741         if (!pvt) {
1742                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
1743                 return NULL;
1744         }
1745         oldformat = format;
1746         format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
1747         if (!format) {
1748                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
1749                 oh323_destroy(pvt);
1750                 if (cause)
1751                         *cause = AST_CAUSE_INCOMPATIBLE_DESTINATION;
1752                 return NULL;
1753         }
1754         ast_copy_string(tmp, dest, sizeof(tmp));
1755         host = strchr(tmp, '@');
1756         if (host) {
1757                 *host = '\0';
1758                 host++;
1759                 ext = tmp;
1760         } else {
1761                 ext = strrchr(tmp, '/');
1762                 if (ext)
1763                         *ext++ = '\0';
1764                 host = tmp;
1765         }
1766         strtok_r(host, "/", &(h323id));
1767         if (!ast_strlen_zero(h323id)) {
1768                 h323_set_id(h323id);
1769         }
1770         if (ext) {
1771                 ast_copy_string(pvt->exten, ext, sizeof(pvt->exten));
1772         }
1773         if (h323debug)
1774                 ast_log(LOG_DEBUG, "Extension: %s Host: %s\n", pvt->exten, host);
1775
1776         if (gatekeeper_disable) {
1777                 if (create_addr(pvt, host)) {
1778                         oh323_destroy(pvt);
1779                         if (cause)
1780                                 *cause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1781                         return NULL;
1782                 }
1783         }
1784         else {
1785                 memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1786                 pvt->jointcapability = pvt->options.capability;
1787                 if (pvt->options.dtmfmode) {
1788                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1789                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1790                         } else {
1791                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1792                         }
1793                 }
1794         }
1795
1796         ast_mutex_lock(&caplock);
1797         /* Generate unique channel identifier */
1798         snprintf(tmp1, sizeof(tmp1)-1, "%s-%u", host, ++unique);
1799         tmp1[sizeof(tmp1)-1] = '\0';
1800         ast_mutex_unlock(&caplock);
1801
1802         ast_mutex_lock(&pvt->lock);
1803         tmpc = __oh323_new(pvt, AST_STATE_DOWN, tmp1);
1804         ast_mutex_unlock(&pvt->lock);
1805         if (!tmpc) {
1806                 oh323_destroy(pvt);
1807                 if (cause)
1808                         *cause = AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
1809         }
1810         ast_update_use_count();
1811         restart_monitor();
1812         return tmpc;
1813 }
1814
1815 /*! \brief Find a call by alias */
1816 static struct oh323_alias *find_alias(const char *source_aliases, int realtime)
1817 {
1818         struct oh323_alias *a;
1819
1820         a = ASTOBJ_CONTAINER_FIND(&aliasl, source_aliases);
1821
1822         if (!a && realtime)
1823                 a = realtime_alias(source_aliases);
1824
1825         return a;
1826 }
1827
1828 /*! \brief
1829   * Callback for sending digits from H.323 up to asterisk
1830   *
1831   */
1832 static int receive_digit(unsigned call_reference, char digit, const char *token, int duration)
1833 {
1834         struct oh323_pvt *pvt;
1835         int res;
1836
1837         pvt = find_call_locked(call_reference, token);
1838         if (!pvt) {
1839                 ast_log(LOG_ERROR, "Received digit '%c' (%u ms) for call %s without private structure\n", digit, duration, token);
1840                 return -1;
1841         }
1842         if (h323debug)
1843                 ast_log(LOG_DTMF, "Received %s digit '%c' (%u ms) for call %s\n", (digit == ' ' ? "update for" : "new"), (digit == ' ' ? pvt->curDTMF : digit), duration, token);
1844
1845         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
1846                 if (digit == '!')
1847                         res = ast_queue_control(pvt->owner, AST_CONTROL_FLASH);
1848                 else {
1849                         struct ast_frame f = {
1850                                 .frametype = AST_FRAME_DTMF_END,
1851                                 .subclass = digit,
1852                                 .samples = duration * 8,
1853                                 .len = duration,
1854                                 .src = "SEND_DIGIT",
1855                         };
1856                         if (digit == ' ') {             /* signalUpdate message */
1857                                 f.subclass = pvt->curDTMF;
1858                                 if (pvt->DTMFsched >= 0) {
1859                                         ast_sched_del(sched, pvt->DTMFsched);
1860                                         pvt->DTMFsched = -1;
1861                                 }
1862                         } else {                                /* Regular input or signal message */
1863                                 if (pvt->DTMFsched >= 0) {
1864                                         /* We still don't send DTMF END from previous event, send it now */
1865                                         ast_sched_del(sched, pvt->DTMFsched);
1866                                         pvt->DTMFsched = -1;
1867                                         f.subclass = pvt->curDTMF;
1868                                         f.samples = f.len = 0;
1869                                         ast_queue_frame(pvt->owner, &f);
1870                                         /* Restore values */
1871                                         f.subclass = digit;
1872                                         f.samples = duration * 8;
1873                                         f.len = duration;
1874                                 }
1875                                 if (duration) {         /* This is a signal, signalUpdate follows */
1876                                         f.frametype = AST_FRAME_DTMF_BEGIN;
1877                                         pvt->DTMFsched = ast_sched_add(sched, duration, oh323_simulate_dtmf_end, pvt);
1878                                         if (h323debug)
1879                                                 ast_log(LOG_DTMF, "Scheduled DTMF END simulation for %d ms, id=%d\n", duration, pvt->DTMFsched);
1880                                 }
1881                                 pvt->curDTMF = digit;
1882                         }
1883                         res = ast_queue_frame(pvt->owner, &f);
1884                 }
1885                 ast_channel_unlock(pvt->owner);
1886         } else {
1887                 if (digit == '!')
1888                         pvt->newcontrol = AST_CONTROL_FLASH;
1889                 else {
1890                         pvt->newduration = duration;
1891                         pvt->newdigit = digit;
1892                 }
1893                 res = 0;
1894         }
1895         ast_mutex_unlock(&pvt->lock);
1896         return res;
1897 }
1898
1899 /*! \brief
1900   * Callback function used to inform the H.323 stack of the local rtp ip/port details
1901   *
1902   * \return Returns the local RTP information
1903   */
1904 static struct rtp_info *external_rtp_create(unsigned call_reference, const char * token)
1905 {
1906         struct oh323_pvt *pvt;
1907         struct sockaddr_in us;
1908         struct rtp_info *info;
1909
1910         info = (struct rtp_info *)malloc(sizeof(struct rtp_info));
1911         if (!info) {
1912                 ast_log(LOG_ERROR, "Unable to allocated info structure, this is very bad\n");
1913                 return NULL;
1914         }
1915         pvt = find_call_locked(call_reference, token);
1916         if (!pvt) {
1917                 free(info);
1918                 ast_log(LOG_ERROR, "Unable to find call %s(%d)\n", token, call_reference);
1919                 return NULL;
1920         }
1921         if (!pvt->rtp)
1922                 __oh323_rtp_create(pvt);
1923         if (!pvt->rtp) {
1924                 ast_mutex_unlock(&pvt->lock);
1925                 free(info);
1926                 ast_log(LOG_ERROR, "No RTP stream is available for call %s (%d)", token, call_reference);
1927                 return NULL;
1928         }
1929         /* figure out our local RTP port and tell the H.323 stack about it */
1930         ast_rtp_get_us(pvt->rtp, &us);
1931         ast_mutex_unlock(&pvt->lock);
1932
1933         ast_copy_string(info->addr, ast_inet_ntoa(us.sin_addr), sizeof(info->addr));
1934         info->port = ntohs(us.sin_port);
1935         if (h323debug)
1936                 ast_log(LOG_DEBUG, "Sending RTP 'US' %s:%d\n", info->addr, info->port);
1937         return info;
1938 }
1939
1940 /*! \brief
1941  * Definition taken from rtp.c for rtpPayloadType because we need it here.
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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "Native format changed to %d from %d, read format is %d, write format is %d\n", pvt->nativeformats, pvt->owner->nativeformats, pvt->owner->readformat, pvt->owner->writeformat);
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_log(LOG_DEBUG, "RTP connection preparation for %s is pending...\n", token);
2048                 }
2049         }
2050         ast_mutex_unlock(&pvt->lock);
2051
2052         if (h323debug)
2053                 ast_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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_verbose(VERBOSE_PREFIX_3 "Setting up Call\n");
2142                 ast_verbose(VERBOSE_PREFIX_3 " \tCall token:  [%s]\n", pvt->cd.call_token);
2143                 ast_verbose(VERBOSE_PREFIX_3 " \tCalling party name:  [%s]\n", pvt->cd.call_source_name);
2144                 ast_verbose(VERBOSE_PREFIX_3 " \tCalling party number:  [%s]\n", pvt->cd.call_source_e164);
2145                 ast_verbose(VERBOSE_PREFIX_3 " \tCalled party name:  [%s]\n", pvt->cd.call_dest_alias);
2146                 ast_verbose(VERBOSE_PREFIX_3 " \tCalled party number:  [%s]\n", pvt->cd.call_dest_e164);
2147                 if (pvt->cd.redirect_reason >= 0)
2148                         ast_verbose(VERBOSE_PREFIX_3 " \tRedirecting party number:  [%s] (reason %d)\n", pvt->cd.redirect_number, pvt->cd.redirect_reason);
2149                 ast_verbose(VERBOSE_PREFIX_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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "Hanging up connection to %s with cause %d\n", token, cause);
2410         }
2411
2412         pvt = find_call_locked(call_reference, token);
2413         if (!pvt) {
2414                 if (h323debug) {
2415                         ast_log(LOG_DEBUG, "Connection to %s already cleared\n", token);
2416                 }
2417                 return;
2418         }
2419         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
2420                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2421                 pvt->owner->hangupcause = pvt->hangupcause = cause;
2422                 ast_queue_hangup(pvt->owner);
2423                 ast_channel_unlock(pvt->owner);
2424         }
2425         else {
2426                 pvt->needhangup = 1;
2427                 pvt->hangupcause = cause;
2428                 if (h323debug)
2429                         ast_log(LOG_DEBUG, "Hangup for %s is pending\n", token);
2430         }
2431         ast_mutex_unlock(&pvt->lock);
2432 }
2433
2434 static void set_dtmf_payload(unsigned call_reference, const char *token, int payload, int is_cisco)
2435 {
2436         struct oh323_pvt *pvt;
2437
2438         if (h323debug)
2439                 ast_log(LOG_DEBUG, "Setting %s DTMF payload to %d on %s\n", (is_cisco ? "Cisco" : "RFC2833"), payload, token);
2440
2441         pvt = find_call_locked(call_reference, token);
2442         if (!pvt) {
2443                 return;
2444         }
2445         if (pvt->rtp) {
2446                 ast_rtp_set_rtpmap_type(pvt->rtp, payload, "audio", (is_cisco ? "cisco-telephone-event" : "telephone-event"), 0);
2447         }
2448         pvt->dtmf_pt[is_cisco ? 1 : 0] = payload;
2449         ast_mutex_unlock(&pvt->lock);
2450         if (h323debug)
2451                 ast_log(LOG_DEBUG, "DTMF payload on %s set to %d\n", token, payload);
2452 }
2453
2454 static void set_peer_capabilities(unsigned call_reference, const char *token, int capabilities, struct ast_codec_pref *prefs)
2455 {
2456         struct oh323_pvt *pvt;
2457
2458         if (h323debug)
2459                 ast_log(LOG_DEBUG, "Got remote capabilities from connection %s\n", token);
2460
2461         pvt = find_call_locked(call_reference, token);
2462         if (!pvt)
2463                 return;
2464         pvt->peercapability = capabilities;
2465         pvt->jointcapability = pvt->options.capability & capabilities;
2466         if (prefs) {
2467                 memcpy(&pvt->peer_prefs, prefs, sizeof(pvt->peer_prefs));
2468                 if (h323debug) {
2469                         int i;
2470                         for (i = 0; i < 32; ++i) {
2471                                 if (!prefs->order[i])
2472                                         break;
2473                                 ast_log(LOG_DEBUG, "prefs[%d]=%s:%d\n", i, (prefs->order[i] ? ast_getformatname(1 << (prefs->order[i]-1)) : "<none>"), prefs->framing[i]);
2474                         }
2475                 }
2476                 if (pvt->rtp)
2477                         ast_rtp_codec_setpref(pvt->rtp, &pvt->peer_prefs);
2478         }
2479         ast_mutex_unlock(&pvt->lock);
2480 }
2481
2482 static void set_local_capabilities(unsigned call_reference, const char *token)
2483 {
2484         struct oh323_pvt *pvt;
2485         int capability, dtmfmode, pref_codec;
2486         struct ast_codec_pref prefs;
2487
2488         if (h323debug)
2489                 ast_log(LOG_DEBUG, "Setting capabilities for connection %s\n", token);
2490
2491         pvt = find_call_locked(call_reference, token);
2492         if (!pvt)
2493                 return;
2494         capability = (pvt->jointcapability) ? pvt->jointcapability : pvt->options.capability;
2495         dtmfmode = pvt->options.dtmfmode;
2496         prefs = pvt->options.prefs;
2497         pref_codec = pvt->pref_codec;
2498         ast_mutex_unlock(&pvt->lock);
2499         h323_set_capabilities(token, capability, dtmfmode, &prefs, pref_codec);
2500
2501         if (h323debug)
2502                 ast_log(LOG_DEBUG, "Capabilities for connection %s is set\n", token);
2503 }
2504
2505 static void remote_hold(unsigned call_reference, const char *token, int is_hold)
2506 {
2507         struct oh323_pvt *pvt;
2508
2509         if (h323debug)
2510                 ast_log(LOG_DEBUG, "Setting %shold status for connection %s\n", (is_hold ? "" : "un"), token);
2511
2512         pvt = find_call_locked(call_reference, token);
2513         if (!pvt)
2514                 return;
2515         if (pvt->owner && !ast_channel_trylock(pvt->owner)) {
2516                 if (is_hold)
2517                         ast_queue_control(pvt->owner, AST_CONTROL_HOLD);
2518                 else
2519                         ast_queue_control(pvt->owner, AST_CONTROL_UNHOLD);
2520                 ast_channel_unlock(pvt->owner);
2521         }
2522         else {
2523                 if (is_hold)
2524                         pvt->newcontrol = AST_CONTROL_HOLD;
2525                 else
2526                         pvt->newcontrol = AST_CONTROL_UNHOLD;
2527         }
2528         ast_mutex_unlock(&pvt->lock);
2529 }
2530
2531 static void *do_monitor(void *data)
2532 {
2533         int res;
2534         int reloading;
2535         struct oh323_pvt *oh323 = NULL;
2536
2537         for(;;) {
2538                 /* Check for a reload request */
2539                 ast_mutex_lock(&h323_reload_lock);
2540                 reloading = h323_reloading;
2541                 h323_reloading = 0;
2542                 ast_mutex_unlock(&h323_reload_lock);
2543                 if (reloading) {
2544                         if (option_verbose > 0) {
2545                                 ast_verbose(VERBOSE_PREFIX_1 "Reloading H.323\n");
2546                         }
2547                         h323_do_reload();
2548                 }
2549                 /* Check for interfaces needing to be killed */
2550                 if (!ast_mutex_trylock(&iflock)) {
2551 #if 1
2552                         do {
2553                                 for (oh323 = iflist; oh323; oh323 = oh323->next) {
2554                                         if (!ast_mutex_trylock(&oh323->lock)) {
2555                                                 if (oh323->needdestroy) {
2556                                                         __oh323_destroy(oh323);
2557                                                         break;
2558                                                 }
2559                                                 ast_mutex_unlock(&oh323->lock);
2560                                         }
2561                                 }
2562                         } while (/*oh323*/ 0);
2563 #else
2564 restartsearch:
2565                         oh323 = iflist;
2566                         while(oh323) {
2567                                 if (!ast_mutex_trylock(&oh323->lock)) {
2568                                         if (oh323->needdestroy) {
2569                                                 __oh323_destroy(oh323);
2570                                                 goto restartsearch;
2571                                         }
2572                                         ast_mutex_unlock(&oh323->lock);
2573                                         oh323 = oh323->next;
2574                                 }
2575                         }
2576 #endif
2577                         ast_mutex_unlock(&iflock);
2578                 } else
2579                         oh323 = (struct oh323_pvt *)1;  /* Force fast loop */
2580                 pthread_testcancel();
2581                 /* Wait for sched or io */
2582                 res = ast_sched_wait(sched);
2583                 if ((res < 0) || (res > 1000)) {
2584                         res = 1000;
2585                 }
2586                 /* Do not wait if some channel(s) is destroyed, probably, more available too */
2587                 if (oh323)
2588                         res = 1;
2589                 res = ast_io_wait(io, res);
2590                 pthread_testcancel();
2591                 ast_mutex_lock(&monlock);
2592                 if (res >= 0) {
2593                         ast_sched_runq(sched);
2594                 }
2595                 ast_mutex_unlock(&monlock);
2596         }
2597         /* Never reached */
2598         return NULL;
2599 }
2600
2601 static int restart_monitor(void)
2602 {
2603         pthread_attr_t attr;
2604         /* If we're supposed to be stopped -- stay stopped */
2605         if (ast_mutex_lock(&monlock)) {
2606                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
2607                 return -1;
2608         }
2609         if (monitor_thread == AST_PTHREADT_STOP) {
2610                 ast_mutex_unlock(&monlock);
2611                 return 0;
2612         }
2613         if (monitor_thread == pthread_self()) {
2614                 ast_mutex_unlock(&monlock);
2615                 ast_log(LOG_WARNING, "Cannot kill myself\n");
2616                 return -1;
2617         }
2618         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
2619                 /* Wake up the thread */
2620                 pthread_kill(monitor_thread, SIGURG);
2621         } else {
2622                 pthread_attr_init(&attr);
2623                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2624                 /* Start a new monitor */
2625                 if (ast_pthread_create_background(&monitor_thread, &attr, do_monitor, NULL) < 0) {
2626                         monitor_thread = AST_PTHREADT_NULL;
2627                         ast_mutex_unlock(&monlock);
2628                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
2629                         pthread_attr_destroy(&attr);
2630                         return -1;
2631                 }
2632                 pthread_attr_destroy(&attr);
2633         }
2634         ast_mutex_unlock(&monlock);
2635         return 0;
2636 }
2637
2638 static int h323_do_trace(int fd, int argc, char *argv[])
2639 {
2640         if (argc != 4) {
2641                 return RESULT_SHOWUSAGE;
2642         }
2643         h323_debug(1, atoi(argv[3]));
2644         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
2645         return RESULT_SUCCESS;
2646 }
2647
2648 static int h323_no_trace(int fd, int argc, char *argv[])
2649 {
2650         if (argc < 3 || argc > 4) {
2651                 return RESULT_SHOWUSAGE;
2652         }
2653         h323_debug(0,0);
2654         ast_cli(fd, "H.323 trace disabled\n");
2655         return RESULT_SUCCESS;
2656 }
2657
2658 static int h323_do_debug(int fd, int argc, char *argv[])
2659 {
2660         if (argc < 2 || argc > 3) {
2661                 return RESULT_SHOWUSAGE;
2662         }
2663         h323debug = 1;
2664         ast_cli(fd, "H.323 debug enabled\n");
2665         return RESULT_SUCCESS;
2666 }
2667
2668 static int h323_no_debug(int fd, int argc, char *argv[])
2669 {
2670         if (argc < 3 || argc > 4) {
2671                 return RESULT_SHOWUSAGE;
2672         }
2673         h323debug = 0;
2674         ast_cli(fd, "H.323 debug disabled\n");
2675         return RESULT_SUCCESS;
2676 }
2677
2678 static int h323_gk_cycle(int fd, int argc, char *argv[])
2679 {
2680         if (argc != 3) {
2681                 return RESULT_SHOWUSAGE;
2682         }
2683         h323_gk_urq();
2684
2685         /* Possibly register with a GK */
2686         if (!gatekeeper_disable) {
2687                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
2688                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
2689                 }
2690         }
2691         return RESULT_SUCCESS;
2692 }
2693
2694 static int h323_ep_hangup(int fd, int argc, char *argv[])
2695 {
2696         if (argc != 3) {
2697                 return RESULT_SHOWUSAGE;
2698         }
2699         if (h323_soft_hangup(argv[2])) {
2700                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
2701         } else {
2702                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
2703         }
2704         return RESULT_SUCCESS;
2705 }
2706
2707 static int h323_tokens_show(int fd, int argc, char *argv[])
2708 {
2709         if (argc != 3) {
2710                 return RESULT_SHOWUSAGE;
2711         }
2712         h323_show_tokens();
2713         return RESULT_SUCCESS;
2714 }
2715
2716 static char trace_usage[] =
2717 "Usage: h323 trace <level num>\n"
2718 "       Enables H.323 stack tracing for debugging purposes\n";
2719
2720 static char no_trace_usage[] =
2721 "Usage: h323 no trace\n"
2722 "       Disables H.323 stack tracing for debugging purposes\n";
2723
2724 static char debug_usage[] =
2725 "Usage: h323 debug\n"
2726 "       Enables H.323 debug output\n";
2727
2728 static char no_debug_usage[] =
2729 "Usage: h323 no debug\n"
2730 "       Disables H.323 debug output\n";
2731
2732 static char show_cycle_usage[] =
2733 "Usage: h323 gk cycle\n"
2734 "       Manually re-register with the Gatekeper (Currently Disabled)\n";
2735
2736 static char show_hangup_usage[] =
2737 "Usage: h323 hangup <token>\n"
2738 "       Manually try to hang up call identified by <token>\n";
2739
2740 static char show_tokens_usage[] =
2741 "Usage: h323 show tokens\n"
2742 "       Print out all active call tokens\n";
2743
2744 static char h323_reload_usage[] =
2745 "Usage: h323 reload\n"
2746 "       Reloads H.323 configuration from h323.conf\n";
2747
2748 static struct ast_cli_entry cli_h323_trace_deprecated =
2749         { { "h.323", "trace", NULL },
2750         h323_do_trace, "Enable H.323 Stack Tracing",
2751         trace_usage };
2752
2753 static struct ast_cli_entry cli_h323_no_trace_deprecated =
2754         { { "h.323", "no", "trace", NULL },
2755         h323_no_trace, "Disable H.323 Stack Tracing",
2756         no_trace_usage };
2757
2758 static struct ast_cli_entry cli_h323_debug_deprecated =
2759         { { "h.323", "debug", NULL },
2760         h323_do_debug, "Enable H.323 debug",
2761         debug_usage };
2762
2763 static struct ast_cli_entry cli_h323_no_debug_deprecated =
2764         { { "h.323", "no", "debug", NULL },
2765         h323_no_debug, "Disable H.323 debug",
2766         no_debug_usage };
2767
2768 static struct ast_cli_entry cli_h323_gk_cycle_deprecated =
2769         { { "h.323", "gk", "cycle", NULL },
2770         h323_gk_cycle, "Manually re-register with the Gatekeper",
2771         show_cycle_usage };
2772
2773 static struct ast_cli_entry cli_h323_hangup_deprecated =
2774         { { "h.323", "hangup", NULL },
2775         h323_ep_hangup, "Manually try to hang up a call",
2776         show_hangup_usage };
2777
2778 static struct ast_cli_entry cli_h323_show_tokens_deprecated =
2779         { { "h.323", "show", "tokens", NULL },
2780         h323_tokens_show, "Show all active call tokens",
2781         show_tokens_usage };
2782
2783 static struct ast_cli_entry cli_h323[] = {
2784         { { "h323", "set", "trace", NULL },
2785         h323_do_trace, "Enable H.323 Stack Tracing",
2786         trace_usage, NULL, &cli_h323_trace_deprecated },
2787
2788         { { "h323", "set", "trace", "off", NULL },
2789         h323_no_trace, "Disable H.323 Stack Tracing",
2790         no_trace_usage, NULL, &cli_h323_no_trace_deprecated },
2791
2792         { { "h323", "set", "debug", NULL },
2793         h323_do_debug, "Enable H.323 debug",
2794         debug_usage, NULL, &cli_h323_debug_deprecated },
2795
2796         { { "h323", "set", "debug", "off", NULL },
2797         h323_no_debug, "Disable H.323 debug",
2798         no_debug_usage, NULL, &cli_h323_no_debug_deprecated },
2799
2800         { { "h323", "cycle", "gk", NULL },
2801         h323_gk_cycle, "Manually re-register with the Gatekeper",
2802         show_cycle_usage, NULL, &cli_h323_gk_cycle_deprecated },
2803
2804         { { "h323", "hangup", NULL },
2805         h323_ep_hangup, "Manually try to hang up a call",
2806         show_hangup_usage, NULL, &cli_h323_hangup_deprecated },
2807
2808         { { "h323", "show", "tokens", NULL },
2809         h323_tokens_show, "Show all active call tokens",
2810         show_tokens_usage, NULL, &cli_h323_show_tokens_deprecated },
2811 };
2812
2813 static int reload_config(int is_reload)
2814 {
2815         int format;
2816         struct ast_config *cfg, *ucfg;
2817         struct ast_variable *v;
2818         struct oh323_peer *peer = NULL;
2819         struct oh323_user *user = NULL;
2820         struct oh323_alias *alias = NULL;
2821         struct ast_hostent ahp; struct hostent *hp;
2822         char *cat;
2823         const char *utype;
2824         int is_user, is_peer, is_alias;
2825         char _gatekeeper[100];
2826         int gk_discover, gk_disable, gk_changed;
2827
2828         cfg = ast_config_load(config);
2829
2830         /* We *must* have a config file otherwise stop immediately */
2831         if (!cfg) {
2832                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
2833                 return 1;
2834         }
2835
2836         /* fire up the H.323 Endpoint */
2837         if (!h323_end_point_exist()) {
2838                 h323_end_point_create();
2839         }
2840         ast_copy_string(_gatekeeper, gatekeeper, sizeof(_gatekeeper));
2841         gk_discover = gatekeeper_discover;
2842         gk_disable = gatekeeper_disable;
2843         memset(&bindaddr, 0, sizeof(bindaddr));
2844         memset(&global_options, 0, sizeof(global_options));
2845         global_options.fastStart = 1;
2846         global_options.h245Tunneling = 1;
2847         global_options.dtmfcodec[0] = H323_DTMF_RFC2833_PT;
2848         global_options.dtmfcodec[1] = H323_DTMF_CISCO_PT;
2849         global_options.dtmfmode = 0;
2850         global_options.holdHandling = 0;
2851         global_options.capability = GLOBAL_CAPABILITY;
2852         global_options.bridge = 1;              /* Do native bridging by default */
2853         strcpy(default_context, "default");
2854         h323_signalling_port = 1720;
2855         gatekeeper_disable = 1;
2856         gatekeeper_discover = 0;
2857         gkroute = 0;
2858         userbyalias = 1;
2859         acceptAnonymous = 1;
2860         tos = 0;
2861
2862         /* Copy the default jb config over global_jbconf */
2863         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
2864
2865         /* Load configuration from users.conf */
2866         ucfg = ast_config_load("users.conf");
2867         if (ucfg) {
2868                 struct ast_variable *gen;
2869                 int genhas_h323;
2870                 const char *has_h323;
2871
2872                 genhas_h323 = ast_true(ast_variable_retrieve(ucfg, "general", "hash323"));
2873                 gen = ast_variable_browse(ucfg, "general");
2874                 for (cat = ast_category_browse(ucfg, NULL); cat; cat = ast_category_browse(ucfg, cat)) {
2875                         if (strcasecmp(cat, "general")) {
2876                                 has_h323 = ast_variable_retrieve(ucfg, cat, "hash323");
2877                                 if (ast_true(has_h323) || (!has_h323 && genhas_h323)) {
2878                                         user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
2879                                         if (user) {
2880                                                 ASTOBJ_CONTAINER_LINK(&userl, user);
2881                                                 ASTOBJ_UNREF(user, oh323_destroy_user);
2882                                         }
2883                                 }
2884                         }
2885                 }
2886                 ast_config_destroy(ucfg);
2887         }
2888
2889         for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
2890                 /* handle jb conf */
2891                 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
2892                         continue;
2893                 /* Create the interface list */
2894                 if (!strcasecmp(v->name, "port")) {
2895                         h323_signalling_port = (int)strtol(v->value, NULL, 10);
2896                 } else if (!strcasecmp(v->name, "bindaddr")) {
2897                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
2898                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
2899                         } else {
2900                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
2901                         }
2902                 } else if (!strcasecmp(v->name, "tos")) {
2903                         if (sscanf(v->value, "%d", &format)) {
2904                                 tos = format & 0xff;
2905                         } else if (!strcasecmp(v->value, "lowdelay")) {
2906                                 tos = IPTOS_LOWDELAY;
2907                         } else if (!strcasecmp(v->value, "throughput")) {
2908                                 tos = IPTOS_THROUGHPUT;
2909                         } else if (!strcasecmp(v->value, "reliability")) {
2910                                 tos = IPTOS_RELIABILITY;
2911                         } else if (!strcasecmp(v->value, "mincost")) {
2912                                 tos = IPTOS_MINCOST;
2913                         } else if (!strcasecmp(v->value, "none")) {
2914                                 tos = 0;
2915                         } else {
2916                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
2917                         }
2918                 } else if (!strcasecmp(v->name, "gatekeeper")) {
2919                         if (!strcasecmp(v->value, "DISABLE")) {
2920                                 gatekeeper_disable = 1;
2921                         } else if (!strcasecmp(v->value, "DISCOVER")) {
2922                                 gatekeeper_disable = 0;
2923                                 gatekeeper_discover = 1;
2924                         } else {
2925                                 gatekeeper_disable = 0;
2926                                 ast_copy_string(gatekeeper, v->value, sizeof(gatekeeper));
2927                         }
2928                 } else if (!strcasecmp(v->name, "secret")) {
2929                         ast_copy_string(secret, v->value, sizeof(secret));
2930                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
2931                         gkroute = ast_true(v->value);
2932                 } else if (!strcasecmp(v->name, "context")) {
2933                         ast_copy_string(default_context, v->value, sizeof(default_context));
2934                         ast_verbose(VERBOSE_PREFIX_2 "Setting default context to %s\n", default_context);
2935                 } else if (!strcasecmp(v->name, "UserByAlias")) {
2936                         userbyalias = ast_true(v->value);
2937                 } else if (!strcasecmp(v->name, "AcceptAnonymous")) {
2938                         acceptAnonymous = ast_true(v->value);
2939                 } else if (!update_common_options(v, &global_options)) {
2940                         /* dummy */
2941                 }
2942         }
2943         if (!global_options.dtmfmode)
2944                 global_options.dtmfmode = H323_DTMF_RFC2833;
2945         if (global_options.holdHandling == ~0)
2946                 global_options.holdHandling = 0;
2947         else if (!global_options.holdHandling)
2948                 global_options.holdHandling = H323_HOLD_H450;
2949
2950         for (cat = ast_category_browse(cfg, NULL); cat; cat = ast_category_browse(cfg, cat)) {
2951                 if (strcasecmp(cat, "general")) {
2952                         utype = ast_variable_retrieve(cfg, cat, "type");
2953                         if (utype) {
2954                                 is_user = is_peer = is_alias = 0;
2955                                 if (!strcasecmp(utype, "user"))
2956                                         is_user = 1;
2957                                 else if (!strcasecmp(utype, "peer"))
2958                                         is_peer = 1;
2959                                 else if (!strcasecmp(utype, "friend"))
2960                                         is_user = is_peer = 1;
2961                                 else if (!strcasecmp(utype, "h323") || !strcasecmp(utype, "alias"))
2962                                         is_alias = 1;
2963                                 else {
2964                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
2965                                         continue;
2966                                 }
2967                                 if (is_user) {
2968                                         user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
2969                                         if (user) {
2970                                                 ASTOBJ_CONTAINER_LINK(&userl, user);
2971                                                 ASTOBJ_UNREF(user, oh323_destroy_user);
2972                                         }
2973                                 }
2974                                 if (is_peer) {
2975                                         peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
2976                                         if (peer) {
2977                                                 ASTOBJ_CONTAINER_LINK(&peerl, peer);
2978                                                 ASTOBJ_UNREF(peer, oh323_destroy_peer);
2979                                         }
2980                                 }
2981                                 if (is_alias) {
2982                                         alias = build_alias(cat, ast_variable_browse(cfg, cat), NULL, 0);
2983                                         if (alias) {
2984                                                 ASTOBJ_CONTAINER_LINK(&aliasl, alias);
2985                                                 ASTOBJ_UNREF(alias, oh323_destroy_alias);
2986                                         }
2987                                 }
2988                         } else {
2989                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
2990                         }
2991                 }
2992         }
2993         ast_config_destroy(cfg);
2994
2995         /* Register our H.323 aliases if any*/
2996         ASTOBJ_CONTAINER_WRLOCK(&aliasl);
2997         ASTOBJ_CONTAINER_TRAVERSE(&aliasl, 1, do {
2998                 ASTOBJ_RDLOCK(iterator);
2999                 if (h323_set_alias(iterator)) {
3000                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
3001                         ASTOBJ_UNLOCK(iterator);
3002                         continue;
3003                 }
3004                 ASTOBJ_UNLOCK(iterator);
3005         } while (0) );
3006         ASTOBJ_CONTAINER_UNLOCK(&aliasl);
3007
3008         /* Don't touch GK if nothing changed because URQ will drop all existing calls */
3009         gk_changed = 0;
3010         if (gatekeeper_disable != gk_disable)
3011                 gk_changed = is_reload;
3012         else if(!gatekeeper_disable && (gatekeeper_discover != gk_discover))
3013                 gk_changed = is_reload;
3014         else if(!gatekeeper_disable && (strncmp(_gatekeeper, gatekeeper, sizeof(_gatekeeper)) != 0))
3015                 gk_changed = is_reload;
3016         if (gk_changed) {
3017                 if(!gk_disable)
3018                         h323_gk_urq();
3019                 if (!gatekeeper_disable) {
3020                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
3021                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
3022                                 gatekeeper_disable = 1;
3023                         }
3024                 }
3025         }
3026         return 0;
3027 }
3028
3029 static void delete_users(void)
3030 {
3031         int pruned = 0;
3032
3033         /* Delete all users */
3034         ASTOBJ_CONTAINER_WRLOCK(&userl);
3035         ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
3036                 ASTOBJ_RDLOCK(iterator);
3037                 ASTOBJ_MARK(iterator);
3038                 ++pruned;
3039                 ASTOBJ_UNLOCK(iterator);
3040         } while (0) );
3041         if (pruned) {
3042                 ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, oh323_destroy_user);
3043         }
3044         ASTOBJ_CONTAINER_UNLOCK(&userl);
3045
3046         ASTOBJ_CONTAINER_WRLOCK(&peerl);
3047         ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
3048                 ASTOBJ_RDLOCK(iterator);
3049                 ASTOBJ_MARK(iterator);
3050                 ASTOBJ_UNLOCK(iterator);
3051         } while (0) );
3052         ASTOBJ_CONTAINER_UNLOCK(&peerl);
3053 }
3054
3055 static void delete_aliases(void)
3056 {
3057         int pruned = 0;
3058
3059         /* Delete all aliases */
3060         ASTOBJ_CONTAINER_WRLOCK(&aliasl);
3061         ASTOBJ_CONTAINER_TRAVERSE(&aliasl, 1, do {
3062                 ASTOBJ_RDLOCK(iterator);
3063                 ASTOBJ_MARK(iterator);
3064                 ++pruned;
3065                 ASTOBJ_UNLOCK(iterator);
3066         } while (0) );
3067         if (pruned) {
3068                 ASTOBJ_CONTAINER_PRUNE_MARKED(&aliasl, oh323_destroy_alias);
3069         }
3070         ASTOBJ_CONTAINER_UNLOCK(&aliasl);
3071 }
3072
3073 static void prune_peers(void)
3074 {
3075         /* Prune peers who still are supposed to be deleted */
3076         ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, oh323_destroy_peer);
3077 }
3078
3079 static int h323_reload(int fd, int argc, char *argv[])
3080 {
3081         ast_mutex_lock(&h323_reload_lock);
3082         if (h323_reloading) {
3083                 ast_verbose("Previous H.323 reload not yet done\n");
3084         } else {
3085                 h323_reloading = 1;
3086         }
3087         ast_mutex_unlock(&h323_reload_lock);
3088         restart_monitor();
3089         return 0;
3090 }
3091
3092 static int h323_do_reload(void)
3093 {
3094         delete_users();
3095         delete_aliases();
3096         prune_peers();
3097         reload_config(1);
3098         return 0;
3099 }
3100
3101 static int reload(void)
3102 {
3103         return h323_reload(0, 0, NULL);
3104 }
3105
3106 static struct ast_cli_entry cli_h323_reload_deprecated =
3107         { { "h.323", "reload", NULL },
3108         h323_reload, "Reload H.323 configuration",
3109         h323_reload_usage
3110 };
3111
3112 static struct ast_cli_entry cli_h323_reload =
3113         { { "h323", "reload", NULL },
3114         h323_reload, "Reload H.323 configuration",
3115         h323_reload_usage, NULL, &cli_h323_reload_deprecated
3116 };
3117
3118 static enum ast_rtp_get_result oh323_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
3119 {
3120         struct oh323_pvt *pvt;
3121         enum ast_rtp_get_result res = AST_RTP_GET_FAILED;
3122
3123         if (!(pvt = (struct oh323_pvt *)chan->tech_pvt))
3124                 return res;
3125
3126         ast_mutex_lock(&pvt->lock);
3127         if (pvt->rtp && pvt->options.bridge) {
3128                 *rtp = pvt->rtp;
3129                 res = AST_RTP_TRY_NATIVE;
3130         }
3131         ast_mutex_unlock(&pvt->lock);
3132
3133         return res;
3134 }
3135
3136 static enum ast_rtp_get_result oh323_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
3137 {
3138         return AST_RTP_GET_FAILED;
3139 }
3140
3141 static char *convertcap(int cap)
3142 {
3143         switch (cap) {
3144         case AST_FORMAT_G723_1:
3145                 return "G.723";
3146         case AST_FORMAT_GSM:
3147                 return "GSM";
3148         case AST_FORMAT_ULAW:
3149                 return "ULAW";
3150         case AST_FORMAT_ALAW:
3151                 return "ALAW";
3152         case AST_FORMAT_G722:
3153                 return "G.722";
3154         case AST_FORMAT_ADPCM:
3155                 return "G.728";
3156         case AST_FORMAT_G729A:
3157                 return "G.729";
3158         case AST_FORMAT_SPEEX:
3159                 return "SPEEX";
3160         case AST_FORMAT_ILBC:
3161                 return "ILBC";
3162         default:
3163                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
3164                 return NULL;
3165         }
3166 }
3167
3168 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)
3169 {
3170         /* XXX Deal with Video */
3171         struct oh323_pvt *pvt;
3172         struct sockaddr_in them;
3173         struct sockaddr_in us;
3174         char *mode;
3175
3176         if (!rtp) {
3177                 return 0;
3178         }
3179
3180         mode = convertcap(chan->writeformat);
3181         pvt = (struct oh323_pvt *) chan->tech_pvt;
3182         if (!pvt) {
3183                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
3184                 return -1;
3185         }
3186         ast_rtp_get_peer(rtp, &them);
3187         ast_rtp_get_us(rtp, &us);
3188 #if 0   /* Native bridge still isn't ready */
3189         h323_native_bridge(pvt->cd.call_token, ast_inet_ntoa(them.sin_addr), mode);
3190 #endif
3191         return 0;
3192 }
3193
3194 static struct ast_rtp_protocol oh323_rtp = {
3195         .type = "H323",
3196         .get_rtp_info = oh323_get_rtp_peer,
3197         .get_vrtp_info = oh323_get_vrtp_peer,
3198         .set_rtp_peer = oh323_set_rtp_peer,
3199 };
3200
3201 static enum ast_module_load_result load_module(void)
3202 {
3203         int res;
3204
3205         h323debug = 0;
3206         sched = sched_context_create();
3207         if (!sched) {
3208                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
3209                 return AST_MODULE_LOAD_FAILURE;
3210         }
3211         io = io_context_create();
3212         if (!io) {
3213                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
3214                 return AST_MODULE_LOAD_FAILURE;
3215         }
3216         ast_cli_register(&cli_h323_reload);
3217         ASTOBJ_CONTAINER_INIT(&userl);
3218         ASTOBJ_CONTAINER_INIT(&peerl);
3219         ASTOBJ_CONTAINER_INIT(&aliasl);
3220         res = reload_config(0);
3221         if (res) {
3222                 /* No config entry */
3223                 ast_log(LOG_NOTICE, "Unload and load chan_h323.so again in order to receive configuration changes.\n");
3224                 ast_cli_unregister(&cli_h323_reload);
3225                 io_context_destroy(io);
3226                 io = NULL;
3227                 sched_context_destroy(sched);
3228                 sched = NULL;
3229                 ASTOBJ_CONTAINER_DESTROY(&userl);
3230                 ASTOBJ_CONTAINER_DESTROY(&peerl);
3231                 ASTOBJ_CONTAINER_DESTROY(&aliasl);
3232                 return AST_MODULE_LOAD_DECLINE;
3233         } else {
3234                 /* Make sure we can register our channel type */
3235                 if (ast_channel_register(&oh323_tech)) {
3236                         ast_log(LOG_ERROR, "Unable to register channel class 'H323'\n");
3237                         ast_cli_unregister(&cli_h323_reload);
3238                         h323_end_process();
3239                         io_context_destroy(io);
3240                         sched_context_destroy(sched);
3241
3242                         ASTOBJ_CONTAINER_DESTROYALL(&userl, oh323_destroy_user);
3243                         ASTOBJ_CONTAINER_DESTROY(&userl);
3244                         ASTOBJ_CONTAINER_DESTROYALL(&peerl, oh323_destroy_peer);
3245                         ASTOBJ_CONTAINER_DESTROY(&peerl);
3246                         ASTOBJ_CONTAINER_DESTROYALL(&aliasl, oh323_destroy_alias);
3247                         ASTOBJ_CONTAINER_DESTROY(&aliasl);
3248
3249                         return AST_MODULE_LOAD_FAILURE;
3250                 }
3251                 ast_cli_register_multiple(cli_h323, sizeof(cli_h323) / sizeof(struct ast_cli_entry));
3252
3253                 ast_rtp_proto_register(&oh323_rtp);
3254
3255                 /* Register our callback functions */
3256                 h323_callback_register(setup_incoming_call,
3257                                                 setup_outgoing_call,
3258                                                 external_rtp_create,
3259                                                 setup_rtp_connection,
3260                                                 cleanup_connection,
3261                                                 chan_ringing,
3262                                                 connection_made,
3263                                                 receive_digit,
3264                                                 answer_call,
3265                                                 progress,
3266                                                 set_dtmf_payload,
3267                                                 hangup_connection,
3268                                                 set_local_capabilities,
3269                                                 set_peer_capabilities,
3270                                                 remote_hold);
3271                 /* start the h.323 listener */
3272                 if (h323_start_listener(h323_signalling_port, bindaddr)) {
3273                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
3274                         ast_rtp_proto_unregister(&oh323_rtp);
3275                         ast_cli_unregister_multiple(cli_h323, sizeof(cli_h323) / sizeof(struct ast_cli_entry));
3276                         ast_cli_unregister(&cli_h323_reload);
3277                         h323_end_process();
3278                         io_context_destroy(io);
3279                         sched_context_destroy(sched);
3280
3281                         ASTOBJ_CONTAINER_DESTROYALL(&userl, oh323_destroy_user);
3282                         ASTOBJ_CONTAINER_DESTROY(&userl);
3283                         ASTOBJ_CONTAINER_DESTROYALL(&peerl, oh323_destroy_peer);
3284                         ASTOBJ_CONTAINER_DESTROY(&peerl);
3285                         ASTOBJ_CONTAINER_DESTROYALL(&aliasl, oh323_destroy_alias);
3286                         ASTOBJ_CONTAINER_DESTROY(&aliasl);
3287
3288                         return AST_MODULE_LOAD_FAILURE;
3289                 }
3290                 /* Possibly register with a GK */
3291                 if (!gatekeeper_disable) {
3292                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
3293                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
3294                                 gatekeeper_disable = 1;
3295                                 res = AST_MODULE_LOAD_SUCCESS;
3296                         }
3297                 }
3298                 /* And start the monitor for the first time */
3299                 restart_monitor();
3300         }
3301         return res;
3302 }
3303
3304 static int unload_module(void)
3305 {
3306         struct oh323_pvt *p, *pl;
3307
3308         /* unregister commands */
3309         ast_cli_unregister_multiple(cli_h323, sizeof(cli_h323) / sizeof(struct ast_cli_entry));
3310         ast_cli_unregister(&cli_h323_reload);
3311
3312         ast_channel_unregister(&oh323_tech);
3313         ast_rtp_proto_unregister(&oh323_rtp);
3314
3315         if (!ast_mutex_lock(&iflock)) {
3316                 /* hangup all interfaces if they have an owner */
3317                 p = iflist;
3318                 while(p) {
3319                         if (p->owner) {
3320                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
3321                         }
3322                         p = p->next;
3323                 }
3324                 iflist = NULL;
3325                 ast_mutex_unlock(&iflock);
3326         } else {
3327                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
3328                 return -1;
3329         }
3330         if (!ast_mutex_lock(&monlock)) {
3331                 if ((monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
3332                         /* this causes a seg, anyone know why? */
3333                         if (monitor_thread != pthread_self())
3334                                 pthread_cancel(monitor_thread);
3335                         pthread_kill(monitor_thread, SIGURG);
3336                         pthread_join(monitor_thread, NULL);
3337                 }
3338                 monitor_thread = AST_PTHREADT_STOP;
3339                 ast_mutex_unlock(&monlock);
3340         } else {
3341                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
3342                 return -1;
3343         }
3344         if (!ast_mutex_lock(&iflock)) {
3345                 /* destroy all the interfaces and free their memory */
3346                 p = iflist;
3347                 while(p) {
3348                         pl = p;
3349                         p = p->next;
3350                         /* free associated memory */
3351                         ast_mutex_destroy(&pl->lock);
3352                         free(pl);
3353                 }
3354                 iflist = NULL;
3355                 ast_mutex_unlock(&iflock);
3356         } else {
3357                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
3358                 return -1;
3359         }
3360         if (!gatekeeper_disable)
3361                 h323_gk_urq();
3362         h323_end_process();
3363         if (io)
3364                 io_context_destroy(io);
3365         if (sched)
3366                 sched_context_destroy(sched);
3367
3368         ASTOBJ_CONTAINER_DESTROYALL(&userl, oh323_destroy_user);
3369         ASTOBJ_CONTAINER_DESTROY(&userl);
3370         ASTOBJ_CONTAINER_DESTROYALL(&peerl, oh323_destroy_peer);
3371         ASTOBJ_CONTAINER_DESTROY(&peerl);
3372         ASTOBJ_CONTAINER_DESTROYALL(&aliasl, oh323_destroy_alias);
3373         ASTOBJ_CONTAINER_DESTROY(&aliasl);
3374
3375         return 0;
3376 }
3377
3378 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "The NuFone Network's OpenH323 Channel Driver",
3379                 .load = load_module,
3380                 .unload = unload_module,
3381                 .reload = reload,
3382 );