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