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