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