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