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