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