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