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