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