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