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