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