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