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