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