Support for withheld or missing CID string
[asterisk-bristuff.git] / main / channel.c
blobaf2f97f518358ffb6a1bdebf49a4c3ce0850bcba
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
19 /*! \file
21 * \brief Channel Management
23 * \author Mark Spencer <markster@digium.com>
26 #include "asterisk.h"
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <sys/time.h>
35 #include <signal.h>
36 #include <errno.h>
37 #include <unistd.h>
38 #include <math.h>
40 #if defined(HAVE_ZAPTEL) || defined (HAVE_DAHDI)
41 #include <sys/ioctl.h>
42 #include "asterisk/dahdi_compat.h"
43 #endif
45 #include "asterisk/pbx.h"
46 #include "asterisk/frame.h"
47 #include "asterisk/sched.h"
48 #include "asterisk/options.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/audiohook.h"
51 #include "asterisk/musiconhold.h"
52 #include "asterisk/logger.h"
53 #include "asterisk/say.h"
54 #include "asterisk/file.h"
55 #include "asterisk/cli.h"
56 #include "asterisk/translate.h"
57 #include "asterisk/manager.h"
58 #include "asterisk/chanvars.h"
59 #include "asterisk/linkedlists.h"
60 #include "asterisk/indications.h"
61 #include "asterisk/monitor.h"
62 #include "asterisk/causes.h"
63 #include "asterisk/callerid.h"
64 #include "asterisk/utils.h"
65 #include "asterisk/lock.h"
66 #include "asterisk/app.h"
67 #include "asterisk/transcap.h"
68 #include "asterisk/devicestate.h"
69 #include "asterisk/sha1.h"
70 #include "asterisk/threadstorage.h"
71 #include "asterisk/slinfactory.h"
73 /* uncomment if you have problems with 'monitoring' synchronized files */
74 #if 0
75 #define MONITOR_CONSTANT_DELAY
76 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
77 #endif
79 /*! Prevent new channel allocation if shutting down. */
80 static int shutting_down;
82 static int uniqueint;
84 unsigned long global_fin, global_fout;
86 AST_THREADSTORAGE(state2str_threadbuf, state2str_threadbuf_init);
87 #define STATE2STR_BUFSIZE 32
89 /*! Default amount of time to use when emulating a digit as a begin and end
90 * 100ms */
91 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
93 /*! Minimum allowed digit length - 80ms */
94 #define AST_MIN_DTMF_DURATION 80
96 /*! Minimum amount of time between the end of the last digit and the beginning
97 * of a new one - 45ms */
98 #define AST_MIN_DTMF_GAP 45
100 struct chanlist {
101 const struct ast_channel_tech *tech;
102 AST_LIST_ENTRY(chanlist) list;
105 /*! the list of registered channel types */
106 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
108 /*! the list of channels we have. Note that the lock for this list is used for
109 both the channels list and the backends list. */
110 static AST_LIST_HEAD_STATIC(channels, ast_channel);
112 /*! map AST_CAUSE's to readable string representations */
113 const struct ast_cause {
114 int cause;
115 const char *name;
116 const char *desc;
117 } causes[] = {
118 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
119 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
120 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
121 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
122 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
123 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
124 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
125 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
126 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
127 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
128 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
129 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
130 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
131 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
132 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
133 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
134 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
135 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
136 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
137 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
138 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
139 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
140 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
141 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
142 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
143 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
144 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
145 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
146 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
147 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
148 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
149 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
150 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
151 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
152 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
153 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
154 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
155 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
156 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
157 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
158 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
159 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
160 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
161 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
164 struct ast_variable *ast_channeltype_list(void)
166 struct chanlist *cl;
167 struct ast_variable *var=NULL, *prev = NULL;
168 AST_LIST_TRAVERSE(&backends, cl, list) {
169 if (prev) {
170 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description)))
171 prev = prev->next;
172 } else {
173 var = ast_variable_new(cl->tech->type, cl->tech->description);
174 prev = var;
177 return var;
180 static int show_channeltypes(int fd, int argc, char *argv[])
182 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
183 struct chanlist *cl;
184 int count_chan = 0;
186 ast_cli(fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
187 ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
188 if (AST_LIST_LOCK(&channels)) {
189 ast_log(LOG_WARNING, "Unable to lock channel list\n");
190 return -1;
192 AST_LIST_TRAVERSE(&backends, cl, list) {
193 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description,
194 (cl->tech->devicestate) ? "yes" : "no",
195 (cl->tech->indicate) ? "yes" : "no",
196 (cl->tech->transfer) ? "yes" : "no");
197 count_chan++;
199 AST_LIST_UNLOCK(&channels);
200 ast_cli(fd, "----------\n%d channel drivers registered.\n", count_chan);
201 return RESULT_SUCCESS;
203 #undef FORMAT
207 static int show_channeltype_deprecated(int fd, int argc, char *argv[])
209 struct chanlist *cl = NULL;
211 if (argc != 3)
212 return RESULT_SHOWUSAGE;
214 if (AST_LIST_LOCK(&channels)) {
215 ast_log(LOG_WARNING, "Unable to lock channel list\n");
216 return RESULT_FAILURE;
219 AST_LIST_TRAVERSE(&backends, cl, list) {
220 if (!strncasecmp(cl->tech->type, argv[2], strlen(cl->tech->type))) {
221 break;
226 if (!cl) {
227 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[2]);
228 AST_LIST_UNLOCK(&channels);
229 return RESULT_FAILURE;
232 ast_cli(fd,
233 "-- Info about channel driver: %s --\n"
234 " Device State: %s\n"
235 " Indication: %s\n"
236 " Transfer : %s\n"
237 " Capabilities: %d\n"
238 " Digit Begin: %s\n"
239 " Digit End: %s\n"
240 " Send HTML : %s\n"
241 " Image Support: %s\n"
242 " Text Support: %s\n",
243 cl->tech->type,
244 (cl->tech->devicestate) ? "yes" : "no",
245 (cl->tech->indicate) ? "yes" : "no",
246 (cl->tech->transfer) ? "yes" : "no",
247 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
248 (cl->tech->send_digit_begin) ? "yes" : "no",
249 (cl->tech->send_digit_end) ? "yes" : "no",
250 (cl->tech->send_html) ? "yes" : "no",
251 (cl->tech->send_image) ? "yes" : "no",
252 (cl->tech->send_text) ? "yes" : "no"
256 AST_LIST_UNLOCK(&channels);
257 return RESULT_SUCCESS;
260 static int show_channeltype(int fd, int argc, char *argv[])
262 struct chanlist *cl = NULL;
264 if (argc != 4)
265 return RESULT_SHOWUSAGE;
267 if (AST_LIST_LOCK(&channels)) {
268 ast_log(LOG_WARNING, "Unable to lock channel list\n");
269 return RESULT_FAILURE;
272 AST_LIST_TRAVERSE(&backends, cl, list) {
273 if (!strncasecmp(cl->tech->type, argv[3], strlen(cl->tech->type))) {
274 break;
279 if (!cl) {
280 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[3]);
281 AST_LIST_UNLOCK(&channels);
282 return RESULT_FAILURE;
285 ast_cli(fd,
286 "-- Info about channel driver: %s --\n"
287 " Device State: %s\n"
288 " Indication: %s\n"
289 " Transfer : %s\n"
290 " Capabilities: %d\n"
291 " Digit Begin: %s\n"
292 " Digit End: %s\n"
293 " Send HTML : %s\n"
294 " Image Support: %s\n"
295 " Text Support: %s\n",
296 cl->tech->type,
297 (cl->tech->devicestate) ? "yes" : "no",
298 (cl->tech->indicate) ? "yes" : "no",
299 (cl->tech->transfer) ? "yes" : "no",
300 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
301 (cl->tech->send_digit_begin) ? "yes" : "no",
302 (cl->tech->send_digit_end) ? "yes" : "no",
303 (cl->tech->send_html) ? "yes" : "no",
304 (cl->tech->send_image) ? "yes" : "no",
305 (cl->tech->send_text) ? "yes" : "no"
309 AST_LIST_UNLOCK(&channels);
310 return RESULT_SUCCESS;
313 static char *complete_channeltypes_deprecated(const char *line, const char *word, int pos, int state)
315 struct chanlist *cl;
316 int which = 0;
317 int wordlen;
318 char *ret = NULL;
320 if (pos != 2)
321 return NULL;
323 wordlen = strlen(word);
325 AST_LIST_TRAVERSE(&backends, cl, list) {
326 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
327 ret = strdup(cl->tech->type);
328 break;
332 return ret;
335 static char *complete_channeltypes(const char *line, const char *word, int pos, int state)
337 struct chanlist *cl;
338 int which = 0;
339 int wordlen;
340 char *ret = NULL;
342 if (pos != 3)
343 return NULL;
345 wordlen = strlen(word);
347 AST_LIST_TRAVERSE(&backends, cl, list) {
348 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
349 ret = strdup(cl->tech->type);
350 break;
354 return ret;
357 static char show_channeltypes_usage[] =
358 "Usage: core show channeltypes\n"
359 " Lists available channel types registered in your Asterisk server.\n";
361 static char show_channeltype_usage[] =
362 "Usage: core show channeltype <name>\n"
363 " Show details about the specified channel type, <name>.\n";
365 static struct ast_cli_entry cli_show_channeltypes_deprecated = {
366 { "show", "channeltypes", NULL },
367 show_channeltypes, NULL,
368 NULL };
370 static struct ast_cli_entry cli_show_channeltype_deprecated = {
371 { "show", "channeltype", NULL },
372 show_channeltype_deprecated, NULL,
373 NULL, complete_channeltypes_deprecated };
375 static struct ast_cli_entry cli_channel[] = {
376 { { "core", "show", "channeltypes", NULL },
377 show_channeltypes, "List available channel types",
378 show_channeltypes_usage, NULL, &cli_show_channeltypes_deprecated },
380 { { "core", "show", "channeltype", NULL },
381 show_channeltype, "Give more details on that channel type",
382 show_channeltype_usage, complete_channeltypes, &cli_show_channeltype_deprecated },
385 /*! \brief Checks to see if a channel is needing hang up */
386 int ast_check_hangup(struct ast_channel *chan)
388 if (chan->_softhangup) /* yes if soft hangup flag set */
389 return 1;
390 if (!chan->tech_pvt) /* yes if no technology private data */
391 return 1;
392 if (!chan->whentohangup) /* no if no hangup scheduled */
393 return 0;
394 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
395 return 0;
396 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
397 return 1;
400 static int ast_check_hangup_locked(struct ast_channel *chan)
402 int res;
403 ast_channel_lock(chan);
404 res = ast_check_hangup(chan);
405 ast_channel_unlock(chan);
406 return res;
409 /*! \brief printf the string into a correctly sized mallocd buffer, and return the buffer */
410 char *ast_safe_string_alloc(const char *fmt, ...)
412 char *b2, buf[1];
413 int len;
414 va_list args;
416 va_start(args, fmt);
417 len = vsnprintf(buf, 1, fmt, args);
418 va_end(args);
420 if (!(b2 = ast_malloc(len + 1)))
421 return NULL;
423 va_start(args, fmt);
424 vsnprintf(b2, len + 1, fmt, args);
425 va_end(args);
427 return b2;
430 /*! \brief Initiate system shutdown */
431 void ast_begin_shutdown(int hangup)
433 struct ast_channel *c;
434 shutting_down = 1;
435 if (hangup) {
436 AST_LIST_LOCK(&channels);
437 AST_LIST_TRAVERSE(&channels, c, chan_list)
438 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
439 AST_LIST_UNLOCK(&channels);
443 /*! \brief returns number of active/allocated channels */
444 int ast_active_channels(void)
446 struct ast_channel *c;
447 int cnt = 0;
448 AST_LIST_LOCK(&channels);
449 AST_LIST_TRAVERSE(&channels, c, chan_list)
450 cnt++;
451 AST_LIST_UNLOCK(&channels);
452 return cnt;
455 /*! \brief Cancel a shutdown in progress */
456 void ast_cancel_shutdown(void)
458 shutting_down = 0;
461 /*! \brief Returns non-zero if Asterisk is being shut down */
462 int ast_shutting_down(void)
464 return shutting_down;
467 /*! \brief Set when to hangup channel */
468 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
470 chan->whentohangup = offset ? time(NULL) + offset : 0;
471 ast_queue_frame(chan, &ast_null_frame);
472 return;
475 /*! \brief Compare a offset with when to hangup channel */
476 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
478 time_t whentohangup;
480 if (chan->whentohangup == 0) {
481 return (offset == 0) ? 0 : -1;
482 } else {
483 if (offset == 0) /* XXX why is this special ? */
484 return (1);
485 else {
486 whentohangup = offset + time (NULL);
487 if (chan->whentohangup < whentohangup)
488 return (1);
489 else if (chan->whentohangup == whentohangup)
490 return (0);
491 else
492 return (-1);
497 /*! \brief Register a new telephony channel in Asterisk */
498 int ast_channel_register(const struct ast_channel_tech *tech)
500 struct chanlist *chan;
502 AST_LIST_LOCK(&channels);
504 AST_LIST_TRAVERSE(&backends, chan, list) {
505 if (!strcasecmp(tech->type, chan->tech->type)) {
506 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
507 AST_LIST_UNLOCK(&channels);
508 return -1;
512 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
513 AST_LIST_UNLOCK(&channels);
514 return -1;
516 chan->tech = tech;
517 AST_LIST_INSERT_HEAD(&backends, chan, list);
519 if (option_debug)
520 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
522 if (option_verbose > 1)
523 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
524 chan->tech->description);
526 AST_LIST_UNLOCK(&channels);
527 return 0;
530 void ast_channel_unregister(const struct ast_channel_tech *tech)
532 struct chanlist *chan;
534 if (option_debug)
535 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
537 AST_LIST_LOCK(&channels);
539 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
540 if (chan->tech == tech) {
541 AST_LIST_REMOVE_CURRENT(&backends, list);
542 free(chan);
543 if (option_verbose > 1)
544 ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
545 break;
548 AST_LIST_TRAVERSE_SAFE_END
550 AST_LIST_UNLOCK(&channels);
553 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
555 struct chanlist *chanls;
556 const struct ast_channel_tech *ret = NULL;
558 if (AST_LIST_LOCK(&channels)) {
559 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
560 return NULL;
563 AST_LIST_TRAVERSE(&backends, chanls, list) {
564 if (!strcasecmp(name, chanls->tech->type)) {
565 ret = chanls->tech;
566 break;
570 AST_LIST_UNLOCK(&channels);
572 return ret;
575 /*! \brief Gives the string form of a given hangup cause */
576 const char *ast_cause2str(int cause)
578 int x;
580 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
581 if (causes[x].cause == cause)
582 return causes[x].desc;
585 return "Unknown";
588 /*! \brief Convert a symbolic hangup cause to number */
589 int ast_str2cause(const char *name)
591 int x;
593 for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
594 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
595 return causes[x].cause;
597 return -1;
600 /*! \brief Gives the string form of a given channel state */
601 char *ast_state2str(enum ast_channel_state state)
603 char *buf;
605 switch(state) {
606 case AST_STATE_DOWN:
607 return "Down";
608 case AST_STATE_RESERVED:
609 return "Rsrvd";
610 case AST_STATE_OFFHOOK:
611 return "OffHook";
612 case AST_STATE_DIALING:
613 return "Dialing";
614 case AST_STATE_RING:
615 return "Ring";
616 case AST_STATE_RINGING:
617 return "Ringing";
618 case AST_STATE_UP:
619 return "Up";
620 case AST_STATE_BUSY:
621 return "Busy";
622 case AST_STATE_DIALING_OFFHOOK:
623 return "Dialing Offhook";
624 case AST_STATE_PRERING:
625 return "Pre-ring";
626 default:
627 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
628 return "Unknown";
629 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
630 return buf;
634 /*! \brief Gives the string form of a given transfer capability */
635 char *ast_transfercapability2str(int transfercapability)
637 switch(transfercapability) {
638 case AST_TRANS_CAP_SPEECH:
639 return "SPEECH";
640 case AST_TRANS_CAP_DIGITAL:
641 return "DIGITAL";
642 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
643 return "RESTRICTED_DIGITAL";
644 case AST_TRANS_CAP_3_1K_AUDIO:
645 return "3K1AUDIO";
646 case AST_TRANS_CAP_DIGITAL_W_TONES:
647 return "DIGITAL_W_TONES";
648 case AST_TRANS_CAP_VIDEO:
649 return "VIDEO";
650 default:
651 return "UNKNOWN";
655 /*! \brief Pick the best audio codec */
656 int ast_best_codec(int fmts)
658 /* This just our opinion, expressed in code. We are asked to choose
659 the best codec to use, given no information */
660 int x;
661 static int prefs[] =
663 /*! Okay, ulaw is used by all telephony equipment, so start with it */
664 AST_FORMAT_ULAW,
665 /*! Unless of course, you're a silly European, so then prefer ALAW */
666 AST_FORMAT_ALAW,
667 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
668 AST_FORMAT_G722,
669 /*! Okay, well, signed linear is easy to translate into other stuff */
670 AST_FORMAT_SLINEAR,
671 /*! G.726 is standard ADPCM, in RFC3551 packing order */
672 AST_FORMAT_G726,
673 /*! G.726 is standard ADPCM, in AAL2 packing order */
674 AST_FORMAT_G726_AAL2,
675 /*! ADPCM has great sound quality and is still pretty easy to translate */
676 AST_FORMAT_ADPCM,
677 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
678 translate and sounds pretty good */
679 AST_FORMAT_GSM,
680 /*! iLBC is not too bad */
681 AST_FORMAT_ILBC,
682 /*! Speex is free, but computationally more expensive than GSM */
683 AST_FORMAT_SPEEX,
684 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
685 to use it */
686 AST_FORMAT_LPC10,
687 /*! G.729a is faster than 723 and slightly less expensive */
688 AST_FORMAT_G729A,
689 /*! Down to G.723.1 which is proprietary but at least designed for voice */
690 AST_FORMAT_G723_1,
693 /* Strip out video */
694 fmts &= AST_FORMAT_AUDIO_MASK;
696 /* Find the first preferred codec in the format given */
697 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
698 if (fmts & prefs[x])
699 return prefs[x];
700 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
701 return 0;
704 static const struct ast_channel_tech null_tech = {
705 .type = "NULL",
706 .description = "Null channel (should not see this)",
709 /*! \brief Create a new channel structure */
710 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num, const char *cid_name, const char *acctcode, const char *exten, const char *context, const int amaflag, const char *name_fmt, ...)
712 struct ast_channel *tmp;
713 int x;
714 int flags;
715 struct varshead *headp;
716 va_list ap1, ap2;
718 /* If shutting down, don't allocate any new channels */
719 if (shutting_down) {
720 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
721 return NULL;
724 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
725 return NULL;
727 if (!(tmp->sched = sched_context_create())) {
728 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
729 free(tmp);
730 return NULL;
733 if ((ast_string_field_init(tmp, 128))) {
734 sched_context_destroy(tmp->sched);
735 free(tmp);
736 return NULL;
739 /* Don't bother initializing the last two FD here, because they
740 will *always* be set just a few lines down (AST_TIMING_FD,
741 AST_ALERT_FD). */
742 for (x = 0; x < AST_MAX_FDS - 2; x++)
743 tmp->fds[x] = -1;
745 #ifdef HAVE_DAHDI
747 #ifdef HAVE_ZAPTEL
748 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
749 #else
750 tmp->timingfd = open("/dev/dahdi/timer", O_RDWR);
751 #endif
753 if (tmp->timingfd > -1) {
754 /* Check if timing interface supports new
755 ping/pong scheme */
756 flags = 1;
757 if (!ioctl(tmp->timingfd, DAHDI_TIMERPONG, &flags))
758 needqueue = 0;
760 #else
761 tmp->timingfd = -1;
762 #endif
764 if (needqueue) {
765 if (pipe(tmp->alertpipe)) {
766 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
767 alertpipe_failed:
768 #ifdef HAVE_DAHDI
769 if (tmp->timingfd > -1)
770 close(tmp->timingfd);
771 #endif
772 sched_context_destroy(tmp->sched);
773 ast_string_field_free_memory(tmp);
774 free(tmp);
775 return NULL;
776 } else {
777 flags = fcntl(tmp->alertpipe[0], F_GETFL);
778 if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
779 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
780 close(tmp->alertpipe[0]);
781 close(tmp->alertpipe[1]);
782 goto alertpipe_failed;
784 flags = fcntl(tmp->alertpipe[1], F_GETFL);
785 if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
786 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
787 close(tmp->alertpipe[0]);
788 close(tmp->alertpipe[1]);
789 goto alertpipe_failed;
792 } else /* Make sure we've got it done right if they don't */
793 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
795 /* Always watch the alertpipe */
796 tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
797 /* And timing pipe */
798 tmp->fds[AST_TIMING_FD] = tmp->timingfd;
799 ast_string_field_set(tmp, name, "**Unknown**");
801 /* Initial state */
802 tmp->_state = state;
804 tmp->streamid = -1;
806 tmp->fin = global_fin;
807 tmp->fout = global_fout;
809 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
810 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
811 ast_atomic_fetchadd_int(&uniqueint, 1));
812 } else {
813 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
814 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
817 tmp->cid.cid_name = ast_strdup(cid_name);
818 tmp->cid.cid_num = ast_strdup(cid_num);
820 if (!ast_strlen_zero(name_fmt)) {
821 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
822 * And they all use slightly different formats for their name string.
823 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
824 * This means, that the stringfields must have a routine that takes the va_lists directly, and
825 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
826 * This new function was written so this can be accomplished.
828 va_start(ap1, name_fmt);
829 va_start(ap2, name_fmt);
830 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
831 va_end(ap1);
832 va_end(ap2);
835 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
837 /* These 4 variables need to be set up for the cdr_init() to work right */
838 if (amaflag)
839 tmp->amaflags = amaflag;
840 else
841 tmp->amaflags = ast_default_amaflags;
843 if (!ast_strlen_zero(acctcode))
844 ast_string_field_set(tmp, accountcode, acctcode);
845 else
846 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
848 if (!ast_strlen_zero(context))
849 ast_copy_string(tmp->context, context, sizeof(tmp->context));
850 else
851 strcpy(tmp->context, "default");
853 if (!ast_strlen_zero(exten))
854 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
855 else
856 strcpy(tmp->exten, "s");
858 tmp->priority = 1;
860 tmp->cdr = ast_cdr_alloc();
861 ast_cdr_init(tmp->cdr, tmp);
862 ast_cdr_start(tmp->cdr);
864 headp = &tmp->varshead;
865 AST_LIST_HEAD_INIT_NOLOCK(headp);
867 ast_mutex_init(&tmp->lock);
869 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
871 ast_string_field_set(tmp, language, defaultlanguage);
873 tmp->tech = &null_tech;
875 AST_LIST_LOCK(&channels);
876 AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
877 AST_LIST_UNLOCK(&channels);
879 /*\!note
880 * and now, since the channel structure is built, and has its name, let's
881 * call the manager event generator with this Newchannel event. This is the
882 * proper and correct place to make this call, but you sure do have to pass
883 * a lot of data into this func to do it here!
885 if (!ast_strlen_zero(name_fmt)) {
886 manager_event(EVENT_FLAG_CALL, "Newchannel",
887 "Channel: %s\r\n"
888 "State: %s\r\n"
889 "CallerIDNum: %s\r\n"
890 "CallerIDName: %s\r\n"
891 "Uniqueid: %s\r\n",
892 tmp->name, ast_state2str(state),
893 S_OR(cid_num, "<unknown>"),
894 S_OR(cid_name, "<unknown>"),
895 tmp->uniqueid);
898 return tmp;
901 /*! \brief Queue an outgoing media frame */
902 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
904 struct ast_frame *f;
905 struct ast_frame *cur;
906 int blah = 1;
907 int qlen = 0;
909 /* Build us a copy and free the original one */
910 if (!(f = ast_frdup(fin))) {
911 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
912 return -1;
914 ast_channel_lock(chan);
916 /* See if the last frame on the queue is a hangup, if so don't queue anything */
917 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
918 ast_frfree(f);
919 ast_channel_unlock(chan);
920 return 0;
923 /* Count how many frames exist on the queue */
924 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
925 qlen++;
928 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
929 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
930 if (fin->frametype != AST_FRAME_VOICE) {
931 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
932 ast_assert(fin->frametype == AST_FRAME_VOICE);
933 } else {
934 if (option_debug)
935 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
936 ast_frfree(f);
937 ast_channel_unlock(chan);
938 return 0;
941 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
942 if (chan->alertpipe[1] > -1) {
943 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
944 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
945 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
946 #ifdef HAVE_DAHDI
947 } else if (chan->timingfd > -1) {
948 ioctl(chan->timingfd, DAHDI_TIMERPING, &blah);
949 #endif
950 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
951 pthread_kill(chan->blocker, SIGURG);
953 ast_channel_unlock(chan);
954 return 0;
957 /*! \brief Queue a hangup frame for channel */
958 int ast_queue_hangup(struct ast_channel *chan)
960 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
961 /* Yeah, let's not change a lock-critical value without locking */
962 if (!ast_channel_trylock(chan)) {
963 chan->_softhangup |= AST_SOFTHANGUP_DEV;
964 ast_channel_unlock(chan);
966 return ast_queue_frame(chan, &f);
969 /*! \brief Queue a control frame */
970 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
972 struct ast_frame f = { AST_FRAME_CONTROL, };
974 f.subclass = control;
976 return ast_queue_frame(chan, &f);
979 /*! \brief Queue a control frame with payload */
980 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
981 const void *data, size_t datalen)
983 struct ast_frame f = { AST_FRAME_CONTROL, };
985 f.subclass = control;
986 f.data = (void *) data;
987 f.datalen = datalen;
989 return ast_queue_frame(chan, &f);
992 /*! \brief Set defer DTMF flag on channel */
993 int ast_channel_defer_dtmf(struct ast_channel *chan)
995 int pre = 0;
997 if (chan) {
998 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
999 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1001 return pre;
1004 /*! \brief Unset defer DTMF flag on channel */
1005 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1007 if (chan)
1008 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1012 * \brief Helper function to find channels.
1014 * It supports these modes:
1016 * prev != NULL : get channel next in list after prev
1017 * name != NULL : get channel with matching name
1018 * name != NULL && namelen != 0 : get channel whose name starts with prefix
1019 * exten != NULL : get channel whose exten or macroexten matches
1020 * context != NULL && exten != NULL : get channel whose context or macrocontext
1022 * It returns with the channel's lock held. If getting the individual lock fails,
1023 * unlock and retry quickly up to 10 times, then give up.
1025 * \note XXX Note that this code has cost O(N) because of the need to verify
1026 * that the object is still on the global list.
1028 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
1029 * can only be done with the lock held or someone could delete the
1030 * object while we work on it. This causes some ugliness in the code.
1031 * Note that removing the first ast_log() may be harmful, as it would
1032 * shorten the retry period and possibly cause failures.
1033 * We should definitely go for a better scheme that is deadlock-free.
1035 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
1036 const char *name, const int namelen,
1037 const char *context, const char *exten)
1039 const char *msg = prev ? "deadlock" : "initial deadlock";
1040 int retries;
1041 struct ast_channel *c;
1042 const struct ast_channel *_prev = prev;
1044 for (retries = 0; retries < 200; retries++) {
1045 int done;
1046 /* Reset prev on each retry. See note below for the reason. */
1047 prev = _prev;
1048 AST_LIST_LOCK(&channels);
1049 AST_LIST_TRAVERSE(&channels, c, chan_list) {
1050 if (prev) { /* look for last item, first, before any evaluation */
1051 if (c != prev) /* not this one */
1052 continue;
1053 /* found, prepare to return c->next */
1054 if ((c = AST_LIST_NEXT(c, chan_list)) == NULL) break;
1055 /*!\note
1056 * We're done searching through the list for the previous item.
1057 * Any item after this point, we want to evaluate for a match.
1058 * If we didn't set prev to NULL here, then we would only
1059 * return matches for the first matching item (since the above
1060 * "if (c != prev)" would not permit any other potential
1061 * matches to reach the additional matching logic, below).
1062 * Instead, it would just iterate until it once again found the
1063 * original match, then iterate down to the end of the list and
1064 * quit.
1066 prev = NULL;
1068 if (name) { /* want match by name */
1069 if ((!namelen && strcasecmp(c->name, name)) ||
1070 (namelen && strncasecmp(c->name, name, namelen)))
1071 continue; /* name match failed */
1072 } else if (exten) {
1073 if (context && strcasecmp(c->context, context) &&
1074 strcasecmp(c->macrocontext, context))
1075 continue; /* context match failed */
1076 if (strcasecmp(c->exten, exten) &&
1077 strcasecmp(c->macroexten, exten))
1078 continue; /* exten match failed */
1080 /* if we get here, c points to the desired record */
1081 break;
1083 /* exit if chan not found or mutex acquired successfully */
1084 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1085 done = c == NULL || ast_channel_trylock(c) == 0;
1086 if (!done) {
1087 if (option_debug)
1088 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
1089 if (retries == 199) {
1090 /* We are about to fail due to a deadlock, so report this
1091 * while we still have the list lock.
1093 if (option_debug)
1094 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n", c, retries);
1095 /* As we have deadlocked, we will skip this channel and
1096 * see if there is another match.
1097 * NOTE: No point doing this for a full-name match,
1098 * as there can be no more matches.
1100 if (!(name && !namelen)) {
1101 prev = c;
1102 retries = -1;
1106 AST_LIST_UNLOCK(&channels);
1107 if (done)
1108 return c;
1109 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1110 * starting from the beginning of the list we can restore our saved pointer to the previous
1111 * channel and start from there.
1113 prev = _prev;
1114 usleep(1); /* give other threads a chance before retrying */
1117 return NULL;
1120 /*! \brief Browse channels in use */
1121 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1123 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1126 /*! \brief Get channel by name and lock it */
1127 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1129 return channel_find_locked(NULL, name, 0, NULL, NULL);
1132 /*! \brief Get channel by name prefix and lock it */
1133 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1135 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1138 /*! \brief Get next channel by name prefix and lock it */
1139 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1140 const int namelen)
1142 return channel_find_locked(chan, name, namelen, NULL, NULL);
1145 /*! \brief Get channel by exten (and optionally context) and lock it */
1146 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1148 return channel_find_locked(NULL, NULL, 0, context, exten);
1151 /*! \brief Get next channel by exten (and optionally context) and lock it */
1152 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1153 const char *context)
1155 return channel_find_locked(chan, NULL, 0, context, exten);
1158 /*! \brief Wait, look for hangups and condition arg */
1159 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1161 struct ast_frame *f;
1163 while (ms > 0) {
1164 if (cond && ((*cond)(data) == 0))
1165 return 0;
1166 ms = ast_waitfor(chan, ms);
1167 if (ms < 0)
1168 return -1;
1169 if (ms > 0) {
1170 f = ast_read(chan);
1171 if (!f)
1172 return -1;
1173 ast_frfree(f);
1176 return 0;
1179 /*! \brief Wait, look for hangups */
1180 int ast_safe_sleep(struct ast_channel *chan, int ms)
1182 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1185 static void free_cid(struct ast_callerid *cid)
1187 if (cid->cid_dnid)
1188 free(cid->cid_dnid);
1189 if (cid->cid_num)
1190 free(cid->cid_num);
1191 if (cid->cid_name)
1192 free(cid->cid_name);
1193 if (cid->cid_ani)
1194 free(cid->cid_ani);
1195 if (cid->cid_rdnis)
1196 free(cid->cid_rdnis);
1199 /*! \brief Free a channel structure */
1200 void ast_channel_free(struct ast_channel *chan)
1202 int fd;
1203 struct ast_var_t *vardata;
1204 struct ast_frame *f;
1205 struct varshead *headp;
1206 struct ast_datastore *datastore = NULL;
1207 char name[AST_CHANNEL_NAME], *dashptr;
1209 headp=&chan->varshead;
1211 AST_LIST_LOCK(&channels);
1212 if (!AST_LIST_REMOVE(&channels, chan, chan_list)) {
1213 AST_LIST_UNLOCK(&channels);
1214 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1216 /* Lock and unlock the channel just to be sure nobody has it locked still
1217 due to a reference retrieved from the channel list. */
1218 ast_channel_lock(chan);
1219 ast_channel_unlock(chan);
1221 /* Get rid of each of the data stores on the channel */
1222 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1223 /* Free the data store */
1224 ast_channel_datastore_free(datastore);
1226 /* Lock and unlock the channel just to be sure nobody has it locked still
1227 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1228 ast_channel_lock(chan);
1229 ast_channel_unlock(chan);
1231 if (chan->tech_pvt) {
1232 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1233 free(chan->tech_pvt);
1236 if (chan->sched)
1237 sched_context_destroy(chan->sched);
1239 ast_copy_string(name, chan->name, sizeof(name));
1240 if ((dashptr = strrchr(name, '-'))) {
1241 *dashptr = '\0';
1244 /* Stop monitoring */
1245 if (chan->monitor)
1246 chan->monitor->stop( chan, 0 );
1248 /* If there is native format music-on-hold state, free it */
1249 if (chan->music_state)
1250 ast_moh_cleanup(chan);
1252 /* Free translators */
1253 if (chan->readtrans)
1254 ast_translator_free_path(chan->readtrans);
1255 if (chan->writetrans)
1256 ast_translator_free_path(chan->writetrans);
1257 if (chan->pbx)
1258 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1259 free_cid(&chan->cid);
1260 /* Close pipes if appropriate */
1261 if ((fd = chan->alertpipe[0]) > -1)
1262 close(fd);
1263 if ((fd = chan->alertpipe[1]) > -1)
1264 close(fd);
1265 if ((fd = chan->timingfd) > -1)
1266 close(fd);
1267 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1268 ast_frfree(f);
1270 /* loop over the variables list, freeing all data and deleting list items */
1271 /* no need to lock the list, as the channel is already locked */
1273 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1274 ast_var_delete(vardata);
1276 ast_app_group_discard(chan);
1278 /* Destroy the jitterbuffer */
1279 ast_jb_destroy(chan);
1281 if (chan->cdr) {
1282 ast_cdr_detach(chan->cdr);
1283 chan->cdr = NULL;
1286 ast_mutex_destroy(&chan->lock);
1288 ast_string_field_free_memory(chan);
1289 free(chan);
1290 AST_LIST_UNLOCK(&channels);
1292 ast_device_state_changed_literal(name);
1295 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1297 struct ast_datastore *datastore = NULL;
1299 /* Make sure we at least have type so we can identify this */
1300 if (info == NULL) {
1301 return NULL;
1304 /* Allocate memory for datastore and clear it */
1305 datastore = ast_calloc(1, sizeof(*datastore));
1306 if (datastore == NULL) {
1307 return NULL;
1310 datastore->info = info;
1312 datastore->uid = ast_strdup(uid);
1314 return datastore;
1317 int ast_channel_datastore_free(struct ast_datastore *datastore)
1319 int res = 0;
1321 /* Using the destroy function (if present) destroy the data */
1322 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1323 datastore->info->destroy(datastore->data);
1324 datastore->data = NULL;
1327 /* Free allocated UID memory */
1328 if (datastore->uid != NULL) {
1329 free(datastore->uid);
1330 datastore->uid = NULL;
1333 /* Finally free memory used by ourselves */
1334 free(datastore);
1336 return res;
1339 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1341 struct ast_datastore *datastore = NULL, *datastore2;
1343 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1344 if (datastore->inheritance > 0) {
1345 datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1346 if (datastore2) {
1347 datastore2->data = datastore->info->duplicate(datastore->data);
1348 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1349 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1353 return 0;
1356 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1358 int res = 0;
1360 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1362 return res;
1365 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1367 struct ast_datastore *datastore2 = NULL;
1368 int res = -1;
1370 /* Find our position and remove ourselves */
1371 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1372 if (datastore2 == datastore) {
1373 AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1374 res = 0;
1375 break;
1378 AST_LIST_TRAVERSE_SAFE_END
1380 return res;
1383 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1385 struct ast_datastore *datastore = NULL;
1387 if (info == NULL)
1388 return NULL;
1390 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1391 if (datastore->info == info) {
1392 if (uid != NULL && datastore->uid != NULL) {
1393 if (!strcasecmp(uid, datastore->uid)) {
1394 /* Matched by type AND uid */
1395 break;
1397 } else {
1398 /* Matched by type at least */
1399 break;
1403 AST_LIST_TRAVERSE_SAFE_END
1405 return datastore;
1408 /*! \brief Softly hangup a channel, don't lock */
1409 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1411 if (option_debug)
1412 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1413 /* Inform channel driver that we need to be hung up, if it cares */
1414 chan->_softhangup |= cause;
1415 ast_queue_frame(chan, &ast_null_frame);
1416 /* Interrupt any poll call or such */
1417 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1418 pthread_kill(chan->blocker, SIGURG);
1419 return 0;
1422 /*! \brief Softly hangup a channel, lock */
1423 int ast_softhangup(struct ast_channel *chan, int cause)
1425 int res;
1426 ast_channel_lock(chan);
1427 res = ast_softhangup_nolock(chan, cause);
1428 ast_channel_unlock(chan);
1429 return res;
1432 static void free_translation(struct ast_channel *clone)
1434 if (clone->writetrans)
1435 ast_translator_free_path(clone->writetrans);
1436 if (clone->readtrans)
1437 ast_translator_free_path(clone->readtrans);
1438 clone->writetrans = NULL;
1439 clone->readtrans = NULL;
1440 clone->rawwriteformat = clone->nativeformats;
1441 clone->rawreadformat = clone->nativeformats;
1444 /*! \brief Hangup a channel */
1445 int ast_hangup(struct ast_channel *chan)
1447 int res = 0;
1449 /* Don't actually hang up a channel that will masquerade as someone else, or
1450 if someone is going to masquerade as us */
1451 ast_channel_lock(chan);
1453 if (chan->audiohooks) {
1454 ast_audiohook_detach_list(chan->audiohooks);
1455 chan->audiohooks = NULL;
1458 ast_autoservice_stop(chan);
1460 if (chan->masq) {
1461 if (ast_do_masquerade(chan))
1462 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1465 if (chan->masq) {
1466 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1467 ast_channel_unlock(chan);
1468 return 0;
1470 /* If this channel is one which will be masqueraded into something,
1471 mark it as a zombie already, so we know to free it later */
1472 if (chan->masqr) {
1473 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1474 ast_channel_unlock(chan);
1475 return 0;
1477 free_translation(chan);
1478 /* Close audio stream */
1479 if (chan->stream) {
1480 ast_closestream(chan->stream);
1481 chan->stream = NULL;
1483 /* Close video stream */
1484 if (chan->vstream) {
1485 ast_closestream(chan->vstream);
1486 chan->vstream = NULL;
1488 if (chan->sched) {
1489 sched_context_destroy(chan->sched);
1490 chan->sched = NULL;
1493 if (chan->generatordata) /* Clear any tone stuff remaining */
1494 chan->generator->release(chan, chan->generatordata);
1495 chan->generatordata = NULL;
1496 chan->generator = NULL;
1497 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1498 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1499 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1500 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1501 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
1503 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1504 if (option_debug)
1505 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1506 if (chan->tech->hangup)
1507 res = chan->tech->hangup(chan);
1508 } else {
1509 if (option_debug)
1510 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1513 ast_channel_unlock(chan);
1514 manager_event(EVENT_FLAG_CALL, "Hangup",
1515 "Channel: %s\r\n"
1516 "Uniqueid: %s\r\n"
1517 "Cause: %d\r\n"
1518 "Cause-txt: %s\r\n",
1519 chan->name,
1520 chan->uniqueid,
1521 chan->hangupcause,
1522 ast_cause2str(chan->hangupcause)
1525 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
1526 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
1527 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
1529 ast_cdr_end(chan->cdr);
1530 ast_cdr_detach(chan->cdr);
1531 chan->cdr = NULL;
1534 ast_channel_free(chan);
1536 return res;
1539 int ast_answer(struct ast_channel *chan)
1541 int res = 0;
1542 ast_channel_lock(chan);
1543 /* You can't answer an outbound call */
1544 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1545 ast_channel_unlock(chan);
1546 return 0;
1548 /* Stop if we're a zombie or need a soft hangup */
1549 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1550 ast_channel_unlock(chan);
1551 return -1;
1553 switch(chan->_state) {
1554 case AST_STATE_RINGING:
1555 case AST_STATE_RING:
1556 if (chan->tech->answer)
1557 res = chan->tech->answer(chan);
1558 ast_setstate(chan, AST_STATE_UP);
1559 ast_cdr_answer(chan->cdr);
1560 break;
1561 case AST_STATE_UP:
1562 break;
1563 default:
1564 break;
1566 chan->visible_indication = 0;
1567 ast_channel_unlock(chan);
1568 return res;
1571 void ast_deactivate_generator(struct ast_channel *chan)
1573 ast_channel_lock(chan);
1574 if (chan->generatordata) {
1575 if (chan->generator && chan->generator->release)
1576 chan->generator->release(chan, chan->generatordata);
1577 chan->generatordata = NULL;
1578 chan->generator = NULL;
1579 chan->fds[AST_GENERATOR_FD] = -1;
1580 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1581 ast_settimeout(chan, 0, NULL, NULL);
1583 ast_channel_unlock(chan);
1586 static int generator_force(const void *data)
1588 /* Called if generator doesn't have data */
1589 void *tmp;
1590 int res;
1591 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1592 struct ast_channel *chan = (struct ast_channel *)data;
1594 ast_channel_lock(chan);
1595 tmp = chan->generatordata;
1596 chan->generatordata = NULL;
1597 if (chan->generator)
1598 generate = chan->generator->generate;
1599 ast_channel_unlock(chan);
1601 if (!tmp || !generate)
1602 return 0;
1604 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
1606 chan->generatordata = tmp;
1608 if (res) {
1609 if (option_debug)
1610 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1611 ast_deactivate_generator(chan);
1614 return 0;
1617 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1619 int res = 0;
1621 ast_channel_lock(chan);
1623 if (chan->generatordata) {
1624 if (chan->generator && chan->generator->release)
1625 chan->generator->release(chan, chan->generatordata);
1626 chan->generatordata = NULL;
1629 ast_prod(chan);
1630 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1631 res = -1;
1634 if (!res) {
1635 ast_settimeout(chan, 160, generator_force, chan);
1636 chan->generator = gen;
1639 ast_channel_unlock(chan);
1641 return res;
1644 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1645 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1647 int winner = -1;
1648 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1649 return winner;
1652 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1653 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1654 int *exception, int *outfd, int *ms)
1656 struct timeval start = { 0 , 0 };
1657 struct pollfd *pfds = NULL;
1658 int res;
1659 long rms;
1660 int x, y, max;
1661 int sz;
1662 time_t now = 0;
1663 long whentohangup = 0, diff;
1664 struct ast_channel *winner = NULL;
1665 struct fdmap {
1666 int chan;
1667 int fdno;
1668 } *fdmap = NULL;
1670 if ((sz = n * AST_MAX_FDS + nfds)) {
1671 pfds = alloca(sizeof(*pfds) * sz);
1672 fdmap = alloca(sizeof(*fdmap) * sz);
1675 if (outfd)
1676 *outfd = -99999;
1677 if (exception)
1678 *exception = 0;
1680 /* Perform any pending masquerades */
1681 for (x=0; x < n; x++) {
1682 ast_channel_lock(c[x]);
1683 if (c[x]->masq) {
1684 if (ast_do_masquerade(c[x])) {
1685 ast_log(LOG_WARNING, "Masquerade failed\n");
1686 *ms = -1;
1687 ast_channel_unlock(c[x]);
1688 return NULL;
1691 if (c[x]->whentohangup) {
1692 if (!whentohangup)
1693 time(&now);
1694 diff = c[x]->whentohangup - now;
1695 if (diff < 1) {
1696 /* Should already be hungup */
1697 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1698 ast_channel_unlock(c[x]);
1699 return c[x];
1701 if (!whentohangup || (diff < whentohangup))
1702 whentohangup = diff;
1704 ast_channel_unlock(c[x]);
1706 /* Wait full interval */
1707 rms = *ms;
1708 if (whentohangup) {
1709 rms = whentohangup * 1000; /* timeout in milliseconds */
1710 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1711 rms = *ms;
1714 * Build the pollfd array, putting the channels' fds first,
1715 * followed by individual fds. Order is important because
1716 * individual fd's must have priority over channel fds.
1718 max = 0;
1719 for (x=0; x<n; x++) {
1720 for (y=0; y<AST_MAX_FDS; y++) {
1721 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1722 fdmap[max].chan = x; /* channel x is linked to this pfds */
1723 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1725 CHECK_BLOCKING(c[x]);
1727 /* Add the individual fds */
1728 for (x=0; x<nfds; x++) {
1729 fdmap[max].chan = -1;
1730 max += ast_add_fd(&pfds[max], fds[x]);
1733 if (*ms > 0)
1734 start = ast_tvnow();
1736 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1737 do {
1738 int kbrms = rms;
1739 if (kbrms > 600000)
1740 kbrms = 600000;
1741 res = poll(pfds, max, kbrms);
1742 if (!res)
1743 rms -= kbrms;
1744 } while (!res && (rms > 0));
1745 } else {
1746 res = poll(pfds, max, rms);
1748 for (x=0; x<n; x++)
1749 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1750 if (res < 0) { /* Simulate a timeout if we were interrupted */
1751 if (errno != EINTR)
1752 *ms = -1;
1753 return NULL;
1755 if (whentohangup) { /* if we have a timeout, check who expired */
1756 time(&now);
1757 for (x=0; x<n; x++) {
1758 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1759 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1760 if (winner == NULL)
1761 winner = c[x];
1765 if (res == 0) { /* no fd ready, reset timeout and done */
1766 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1767 return winner;
1770 * Then check if any channel or fd has a pending event.
1771 * Remember to check channels first and fds last, as they
1772 * must have priority on setting 'winner'
1774 for (x = 0; x < max; x++) {
1775 res = pfds[x].revents;
1776 if (res == 0)
1777 continue;
1778 if (fdmap[x].chan >= 0) { /* this is a channel */
1779 winner = c[fdmap[x].chan]; /* override previous winners */
1780 if (res & POLLPRI)
1781 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1782 else
1783 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1784 winner->fdno = fdmap[x].fdno;
1785 } else { /* this is an fd */
1786 if (outfd)
1787 *outfd = pfds[x].fd;
1788 if (exception)
1789 *exception = (res & POLLPRI) ? -1 : 0;
1790 winner = NULL;
1793 if (*ms > 0) {
1794 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1795 if (*ms < 0)
1796 *ms = 0;
1798 return winner;
1801 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1803 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1806 int ast_waitfor(struct ast_channel *c, int ms)
1808 int oldms = ms; /* -1 if no timeout */
1810 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1811 if ((ms < 0) && (oldms < 0))
1812 ms = 0;
1813 return ms;
1816 /* XXX never to be called with ms = -1 */
1817 int ast_waitfordigit(struct ast_channel *c, int ms)
1819 return ast_waitfordigit_full(c, ms, -1, -1);
1822 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
1824 int res = -1;
1825 #ifdef HAVE_DAHDI
1826 if (c->timingfd > -1) {
1827 if (!func) {
1828 samples = 0;
1829 data = 0;
1831 if (option_debug)
1832 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1833 res = ioctl(c->timingfd, DAHDI_TIMERCONFIG, &samples);
1834 c->timingfunc = func;
1835 c->timingdata = data;
1837 #endif
1838 return res;
1841 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1843 /* Stop if we're a zombie or need a soft hangup */
1844 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1845 return -1;
1847 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
1848 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
1850 /* Wait for a digit, no more than ms milliseconds total. */
1851 while (ms) {
1852 struct ast_channel *rchan;
1853 int outfd;
1855 errno = 0;
1856 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1857 if (!rchan && outfd < 0 && ms) {
1858 if (errno == 0 || errno == EINTR)
1859 continue;
1860 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1861 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1862 return -1;
1863 } else if (outfd > -1) {
1864 /* The FD we were watching has something waiting */
1865 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1866 return 1;
1867 } else if (rchan) {
1868 int res;
1869 struct ast_frame *f = ast_read(c);
1870 if (!f)
1871 return -1;
1873 switch(f->frametype) {
1874 case AST_FRAME_DTMF_BEGIN:
1875 break;
1876 case AST_FRAME_DTMF_END:
1877 res = f->subclass;
1878 ast_frfree(f);
1879 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1880 return res;
1881 case AST_FRAME_CONTROL:
1882 switch(f->subclass) {
1883 case AST_CONTROL_HANGUP:
1884 ast_frfree(f);
1885 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1886 return -1;
1887 case AST_CONTROL_RINGING:
1888 case AST_CONTROL_ANSWER:
1889 case AST_CONTROL_SRCUPDATE:
1890 /* Unimportant */
1891 break;
1892 default:
1893 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1894 break;
1896 break;
1897 case AST_FRAME_VOICE:
1898 /* Write audio if appropriate */
1899 if (audiofd > -1)
1900 write(audiofd, f->data, f->datalen);
1901 default:
1902 /* Ignore */
1903 break;
1905 ast_frfree(f);
1909 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1911 return 0; /* Time is up */
1914 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
1916 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
1917 void *tmp = chan->generatordata;
1918 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1919 int res;
1920 int samples;
1922 if (chan->timingfunc) {
1923 if (option_debug > 1)
1924 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1925 ast_settimeout(chan, 0, NULL, NULL);
1928 chan->generatordata = NULL; /* reset, to let writes go through */
1930 if (f->subclass != chan->writeformat) {
1931 float factor;
1932 factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass));
1933 samples = (int) ( ((float) f->samples) * factor );
1934 } else {
1935 samples = f->samples;
1938 if (chan->generator->generate) {
1939 generate = chan->generator->generate;
1941 /* This unlock is here based on two assumptions that hold true at this point in the
1942 * code. 1) this function is only called from within __ast_read() and 2) all generators
1943 * call ast_write() in their generate callback.
1945 * The reason this is added is so that when ast_write is called, the lock that occurs
1946 * there will not recursively lock the channel. Doing this will cause intended deadlock
1947 * avoidance not to work in deeper functions
1949 ast_channel_unlock(chan);
1950 res = generate(chan, tmp, f->datalen, samples);
1951 ast_channel_lock(chan);
1952 chan->generatordata = tmp;
1953 if (res) {
1954 if (option_debug > 1)
1955 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1956 ast_deactivate_generator(chan);
1959 } else if (f->frametype == AST_FRAME_CNG) {
1960 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1961 if (option_debug > 1)
1962 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
1963 ast_settimeout(chan, 160, generator_force, chan);
1968 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1970 struct ast_frame *f = NULL; /* the return value */
1971 int blah;
1972 int prestate;
1973 int count = 0;
1975 /* this function is very long so make sure there is only one return
1976 * point at the end (there are only two exceptions to this).
1978 while(ast_channel_trylock(chan)) {
1979 if(count++ > 10)
1980 /*cannot goto done since the channel is not locked*/
1981 return &ast_null_frame;
1982 usleep(1);
1985 if (chan->masq) {
1986 if (ast_do_masquerade(chan))
1987 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1988 else
1989 f = &ast_null_frame;
1990 goto done;
1993 /* Stop if we're a zombie or need a soft hangup */
1994 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1995 if (chan->generator)
1996 ast_deactivate_generator(chan);
1997 goto done;
1999 prestate = chan->_state;
2001 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2002 !ast_strlen_zero(chan->dtmfq) &&
2003 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2004 /* We have DTMF that has been deferred. Return it now */
2005 chan->dtmff.subclass = chan->dtmfq[0];
2006 /* Drop first digit from the buffer */
2007 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2008 f = &chan->dtmff;
2009 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2010 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2011 chan->dtmff.frametype = AST_FRAME_DTMF_END;
2012 } else {
2013 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %d queued on %s\n", f->subclass, AST_DEFAULT_EMULATE_DTMF_DURATION, chan->name);
2014 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2015 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2016 chan->emulate_dtmf_digit = f->subclass;
2017 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2019 chan->dtmf_tv = ast_tvnow();
2020 goto done;
2023 /* Read and ignore anything on the alertpipe, but read only
2024 one sizeof(blah) per frame that we send from it */
2025 if (chan->alertpipe[0] > -1) {
2026 int flags = fcntl(chan->alertpipe[0], F_GETFL);
2027 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
2028 * which immediately causes a deadlock scenario. Detect and prevent this. */
2029 if ((flags & O_NONBLOCK) == 0) {
2030 ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
2031 if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2032 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
2033 f = &ast_null_frame;
2034 goto done;
2037 read(chan->alertpipe[0], &blah, sizeof(blah));
2040 #ifdef HAVE_DAHDI
2041 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2042 int res;
2044 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2045 blah = -1;
2046 /* IF we can't get event, assume it's an expired as-per the old interface */
2047 res = ioctl(chan->timingfd, DAHDI_GETEVENT, &blah);
2048 if (res)
2049 blah = DAHDI_EVENT_TIMER_EXPIRED;
2051 if (blah == DAHDI_EVENT_TIMER_PING) {
2052 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2053 /* Acknowledge PONG unless we need it again */
2054 if (ioctl(chan->timingfd, DAHDI_TIMERPONG, &blah)) {
2055 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2058 } else if (blah == DAHDI_EVENT_TIMER_EXPIRED) {
2059 ioctl(chan->timingfd, DAHDI_TIMERACK, &blah);
2060 if (chan->timingfunc) {
2061 /* save a copy of func/data before unlocking the channel */
2062 int (*func)(const void *) = chan->timingfunc;
2063 void *data = chan->timingdata;
2064 ast_channel_unlock(chan);
2065 func(data);
2066 } else {
2067 blah = 0;
2068 ioctl(chan->timingfd, DAHDI_TIMERCONFIG, &blah);
2069 chan->timingdata = NULL;
2070 ast_channel_unlock(chan);
2072 /* cannot 'goto done' because the channel is already unlocked */
2073 return &ast_null_frame;
2074 } else
2075 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2076 } else
2077 #endif
2078 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2079 /* if the AST_GENERATOR_FD is set, call the generator with args
2080 * set to -1 so it can do whatever it needs to.
2082 void *tmp = chan->generatordata;
2083 chan->generatordata = NULL; /* reset to let ast_write get through */
2084 chan->generator->generate(chan, tmp, -1, -1);
2085 chan->generatordata = tmp;
2086 f = &ast_null_frame;
2087 goto done;
2090 /* Check for pending read queue */
2091 if (!AST_LIST_EMPTY(&chan->readq)) {
2092 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2093 /* Interpret hangup and return NULL */
2094 /* XXX why not the same for frames from the channel ? */
2095 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2096 ast_frfree(f);
2097 f = NULL;
2099 } else {
2100 chan->blocker = pthread_self();
2101 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2102 if (chan->tech->exception)
2103 f = chan->tech->exception(chan);
2104 else {
2105 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2106 f = &ast_null_frame;
2108 /* Clear the exception flag */
2109 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2110 } else if (chan->tech->read)
2111 f = chan->tech->read(chan);
2112 else
2113 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2116 if (f) {
2117 /* if the channel driver returned more than one frame, stuff the excess
2118 into the readq for the next ast_read call (note that we can safely assume
2119 that the readq is empty, because otherwise we would not have called into
2120 the channel driver and f would be only a single frame)
2122 if (AST_LIST_NEXT(f, frame_list)) {
2123 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2124 AST_LIST_NEXT(f, frame_list) = NULL;
2127 switch (f->frametype) {
2128 case AST_FRAME_CONTROL:
2129 if (f->subclass == AST_CONTROL_ANSWER) {
2130 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2131 if (option_debug)
2132 ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
2133 ast_frfree(f);
2134 f = &ast_null_frame;
2135 } else if (prestate == AST_STATE_UP) {
2136 if (option_debug)
2137 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
2138 ast_frfree(f);
2139 f = &ast_null_frame;
2140 } else {
2141 /* Answer the CDR */
2142 ast_setstate(chan, AST_STATE_UP);
2143 /* removed a call to ast_cdr_answer(chan->cdr) from here. */
2146 break;
2147 case AST_FRAME_DTMF_END:
2148 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2149 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2150 * However, only let emulation be forced if the other end cares about BEGIN frames */
2151 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2152 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2153 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2154 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2155 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2156 } else
2157 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2158 ast_frfree(f);
2159 f = &ast_null_frame;
2160 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2161 if (!ast_tvzero(chan->dtmf_tv) &&
2162 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2163 /* If it hasn't been long enough, defer this digit */
2164 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2165 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2166 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2167 } else
2168 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2169 ast_frfree(f);
2170 f = &ast_null_frame;
2171 } else {
2172 /* There was no begin, turn this into a begin and send the end later */
2173 f->frametype = AST_FRAME_DTMF_BEGIN;
2174 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2175 chan->emulate_dtmf_digit = f->subclass;
2176 chan->dtmf_tv = ast_tvnow();
2177 if (f->len) {
2178 if (f->len > AST_MIN_DTMF_DURATION)
2179 chan->emulate_dtmf_duration = f->len;
2180 else
2181 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2182 } else
2183 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2184 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2186 if (chan->audiohooks) {
2187 struct ast_frame *old_frame = f;
2188 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2189 if (old_frame != f)
2190 ast_frfree(old_frame);
2192 } else {
2193 struct timeval now = ast_tvnow();
2194 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2195 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2196 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2197 if (!f->len)
2198 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2199 } else if (!f->len) {
2200 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2201 f->len = AST_MIN_DTMF_DURATION;
2203 if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2204 ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f->subclass, f->len, AST_MIN_DTMF_DURATION, chan->name);
2205 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2206 chan->emulate_dtmf_digit = f->subclass;
2207 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2208 ast_frfree(f);
2209 f = &ast_null_frame;
2210 } else {
2211 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2212 if (f->len < AST_MIN_DTMF_DURATION) {
2213 f->len = AST_MIN_DTMF_DURATION;
2215 chan->dtmf_tv = now;
2217 if (chan->audiohooks) {
2218 struct ast_frame *old_frame = f;
2219 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2220 if (old_frame != f)
2221 ast_frfree(old_frame);
2224 break;
2225 case AST_FRAME_DTMF_BEGIN:
2226 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2227 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
2228 (!ast_tvzero(chan->dtmf_tv) &&
2229 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2230 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2231 ast_frfree(f);
2232 f = &ast_null_frame;
2233 } else {
2234 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2235 chan->dtmf_tv = ast_tvnow();
2236 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2238 break;
2239 case AST_FRAME_NULL:
2240 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2241 * is reached , because we want to make sure we pass at least one
2242 * voice frame through before starting the next digit, to ensure a gap
2243 * between DTMF digits. */
2244 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2245 struct timeval now = ast_tvnow();
2246 if (!chan->emulate_dtmf_duration) {
2247 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2248 chan->emulate_dtmf_digit = 0;
2249 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2250 chan->emulate_dtmf_duration = 0;
2251 ast_frfree(f);
2252 f = &chan->dtmff;
2253 f->frametype = AST_FRAME_DTMF_END;
2254 f->subclass = chan->emulate_dtmf_digit;
2255 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2256 chan->dtmf_tv = now;
2257 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2258 chan->emulate_dtmf_digit = 0;
2259 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2262 break;
2263 case AST_FRAME_VOICE:
2264 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2265 * is reached , because we want to make sure we pass at least one
2266 * voice frame through before starting the next digit, to ensure a gap
2267 * between DTMF digits. */
2268 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2269 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2270 chan->emulate_dtmf_digit = 0;
2273 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2274 if (dropaudio)
2275 ast_read_generator_actions(chan, f);
2276 ast_frfree(f);
2277 f = &ast_null_frame;
2280 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2281 struct timeval now = ast_tvnow();
2282 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2283 chan->emulate_dtmf_duration = 0;
2284 ast_frfree(f);
2285 f = &chan->dtmff;
2286 f->frametype = AST_FRAME_DTMF_END;
2287 f->subclass = chan->emulate_dtmf_digit;
2288 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2289 chan->dtmf_tv = now;
2290 if (chan->audiohooks) {
2291 struct ast_frame *old_frame = f;
2292 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2293 if (old_frame != f)
2294 ast_frfree(old_frame);
2296 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2297 } else {
2298 /* Drop voice frames while we're still in the middle of the digit */
2299 ast_frfree(f);
2300 f = &ast_null_frame;
2302 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2303 /* This frame is not one of the current native formats -- drop it on the floor */
2304 char to[200];
2305 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2306 chan->name, ast_getformatname(f->subclass), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
2307 ast_frfree(f);
2308 f = &ast_null_frame;
2309 } else if ((f->frametype == AST_FRAME_VOICE)) {
2310 if (chan->audiohooks) {
2311 struct ast_frame *old_frame = f;
2312 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2313 if (old_frame != f)
2314 ast_frfree(old_frame);
2316 if (chan->monitor && chan->monitor->read_stream ) {
2317 /* XXX what does this do ? */
2318 #ifndef MONITOR_CONSTANT_DELAY
2319 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2320 if (jump >= 0) {
2321 jump = chan->outsmpl - chan->insmpl;
2322 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2323 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2324 chan->insmpl += jump + f->samples;
2325 } else
2326 chan->insmpl+= f->samples;
2327 #else
2328 int jump = chan->outsmpl - chan->insmpl;
2329 if (jump - MONITOR_DELAY >= 0) {
2330 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2331 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2332 chan->insmpl += jump;
2333 } else
2334 chan->insmpl += f->samples;
2335 #endif
2336 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2337 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2338 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2342 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2343 f = &ast_null_frame;
2345 /* Run generator sitting on the line if timing device not available
2346 * and synchronous generation of outgoing frames is necessary */
2347 ast_read_generator_actions(chan, f);
2349 default:
2350 /* Just pass it on! */
2351 break;
2353 } else {
2354 /* Make sure we always return NULL in the future */
2355 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2356 if (chan->generator)
2357 ast_deactivate_generator(chan);
2358 /* We no longer End the CDR here */
2361 /* High bit prints debugging */
2362 if (chan->fin & DEBUGCHAN_FLAG)
2363 ast_frame_dump(chan->name, f, "<<");
2364 chan->fin = FRAMECOUNT_INC(chan->fin);
2366 done:
2367 ast_channel_unlock(chan);
2368 return f;
2371 int ast_internal_timing_enabled(struct ast_channel *chan)
2373 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2374 if (option_debug > 4)
2375 ast_log(LOG_DEBUG, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2376 return ret;
2379 struct ast_frame *ast_read(struct ast_channel *chan)
2381 return __ast_read(chan, 0);
2384 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2386 return __ast_read(chan, 1);
2389 int ast_indicate(struct ast_channel *chan, int condition)
2391 return ast_indicate_data(chan, condition, NULL, 0);
2394 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2396 int res = -1;
2398 ast_channel_lock(chan);
2399 /* Stop if we're a zombie or need a soft hangup */
2400 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2401 ast_channel_unlock(chan);
2402 return -1;
2404 if (chan->tech->indicate)
2405 res = chan->tech->indicate(chan, condition, data, datalen);
2406 ast_channel_unlock(chan);
2407 if (!chan->tech->indicate || res) {
2409 * Device does not support (that) indication, lets fake
2410 * it by doing our own tone generation. (PM2002)
2412 if (condition < 0)
2413 ast_playtones_stop(chan);
2414 else {
2415 const struct ind_tone_zone_sound *ts = NULL;
2416 switch (condition) {
2417 case AST_CONTROL_RINGING:
2418 ts = ast_get_indication_tone(chan->zone, "ring");
2419 break;
2420 case AST_CONTROL_BUSY:
2421 ts = ast_get_indication_tone(chan->zone, "busy");
2422 break;
2423 case AST_CONTROL_CONGESTION:
2424 ts = ast_get_indication_tone(chan->zone, "congestion");
2425 break;
2427 if (ts && ts->data[0]) {
2428 if (option_debug)
2429 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2430 ast_playtones_start(chan,0,ts->data, 1);
2431 res = 0;
2432 chan->visible_indication = condition;
2433 } else if (condition == AST_CONTROL_PROGRESS) {
2434 /* ast_playtones_stop(chan); */
2435 } else if (condition == AST_CONTROL_PROCEEDING) {
2436 /* Do nothing, really */
2437 } else if (condition == AST_CONTROL_HOLD) {
2438 /* Do nothing.... */
2439 } else if (condition == AST_CONTROL_UNHOLD) {
2440 /* Do nothing.... */
2441 } else if (condition == AST_CONTROL_VIDUPDATE) {
2442 /* Do nothing.... */
2443 } else if (condition == AST_CONTROL_SRCUPDATE) {
2444 /* Do nothing... */
2445 } else {
2446 /* not handled */
2447 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2448 res = -1;
2451 } else
2452 chan->visible_indication = condition;
2454 return res;
2457 int ast_recvchar(struct ast_channel *chan, int timeout)
2459 int c;
2460 char *buf = ast_recvtext(chan, timeout);
2461 if (buf == NULL)
2462 return -1; /* error or timeout */
2463 c = *(unsigned char *)buf;
2464 free(buf);
2465 return c;
2468 char *ast_recvtext(struct ast_channel *chan, int timeout)
2470 int res, done = 0;
2471 char *buf = NULL;
2473 while (!done) {
2474 struct ast_frame *f;
2475 if (ast_check_hangup(chan))
2476 break;
2477 res = ast_waitfor(chan, timeout);
2478 if (res <= 0) /* timeout or error */
2479 break;
2480 timeout = res; /* update timeout */
2481 f = ast_read(chan);
2482 if (f == NULL)
2483 break; /* no frame */
2484 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2485 done = 1; /* force a break */
2486 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2487 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2488 done = 1;
2490 ast_frfree(f);
2492 return buf;
2495 int ast_sendtext(struct ast_channel *chan, const char *text)
2497 int res = 0;
2498 /* Stop if we're a zombie or need a soft hangup */
2499 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2500 return -1;
2501 CHECK_BLOCKING(chan);
2502 if (chan->tech->send_text)
2503 res = chan->tech->send_text(chan, text);
2504 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2505 return res;
2508 int ast_sendmessage(struct ast_channel *chan, const char *dest, const char *text, int ispdu)
2510 int res = 0;
2511 /* Stop if we're a zombie or need a soft hangup */
2512 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2513 return -1;
2514 CHECK_BLOCKING(chan);
2515 if (chan->tech->send_message)
2516 res = chan->tech->send_message(chan, dest, text, ispdu);
2517 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2518 return res;
2521 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2523 /* Device does not support DTMF tones, lets fake
2524 * it by doing our own generation. */
2525 static const char* dtmf_tones[] = {
2526 "941+1336", /* 0 */
2527 "697+1209", /* 1 */
2528 "697+1336", /* 2 */
2529 "697+1477", /* 3 */
2530 "770+1209", /* 4 */
2531 "770+1336", /* 5 */
2532 "770+1477", /* 6 */
2533 "852+1209", /* 7 */
2534 "852+1336", /* 8 */
2535 "852+1477", /* 9 */
2536 "697+1633", /* A */
2537 "770+1633", /* B */
2538 "852+1633", /* C */
2539 "941+1633", /* D */
2540 "941+1209", /* * */
2541 "941+1477" /* # */
2544 if (!chan->tech->send_digit_begin)
2545 return 0;
2547 if (!chan->tech->send_digit_begin(chan, digit))
2548 return 0;
2550 if (digit >= '0' && digit <='9')
2551 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2552 else if (digit >= 'A' && digit <= 'D')
2553 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2554 else if (digit == '*')
2555 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2556 else if (digit == '#')
2557 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2558 else {
2559 /* not handled */
2560 if (option_debug)
2561 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2564 return 0;
2567 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2569 int res = -1;
2571 if (chan->tech->send_digit_end)
2572 res = chan->tech->send_digit_end(chan, digit, duration);
2574 if (res && chan->generator)
2575 ast_playtones_stop(chan);
2577 return 0;
2580 int ast_senddigit(struct ast_channel *chan, char digit)
2582 if (chan->tech->send_digit_begin) {
2583 ast_senddigit_begin(chan, digit);
2584 ast_safe_sleep(chan, AST_DEFAULT_EMULATE_DTMF_DURATION);
2587 return ast_senddigit_end(chan, digit, AST_DEFAULT_EMULATE_DTMF_DURATION);
2590 int ast_prod(struct ast_channel *chan)
2592 struct ast_frame a = { AST_FRAME_VOICE };
2593 char nothing[128];
2595 /* Send an empty audio frame to get things moving */
2596 if (chan->_state != AST_STATE_UP) {
2597 if (option_debug)
2598 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2599 a.subclass = chan->rawwriteformat;
2600 a.data = nothing + AST_FRIENDLY_OFFSET;
2601 a.src = "ast_prod";
2602 if (ast_write(chan, &a))
2603 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2605 return 0;
2608 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2610 int res;
2611 if (!chan->tech->write_video)
2612 return 0;
2613 res = ast_write(chan, fr);
2614 if (!res)
2615 res = 1;
2616 return res;
2619 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2621 int res = -1;
2622 int count = 0;
2623 struct ast_frame *f = NULL, *f2 = NULL;
2625 /*Deadlock avoidance*/
2626 while(ast_channel_trylock(chan)) {
2627 /*cannot goto done since the channel is not locked*/
2628 if(count++ > 10) {
2629 if(option_debug)
2630 ast_log(LOG_DEBUG, "Deadlock avoided for write to channel '%s'\n", chan->name);
2631 return 0;
2633 usleep(1);
2635 /* Stop if we're a zombie or need a soft hangup */
2636 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2637 goto done;
2639 /* Handle any pending masquerades */
2640 if (chan->masq && ast_do_masquerade(chan)) {
2641 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2642 goto done;
2644 if (chan->masqr) {
2645 res = 0; /* XXX explain, why 0 ? */
2646 goto done;
2648 if (chan->generatordata) {
2649 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2650 ast_deactivate_generator(chan);
2651 else {
2652 if (fr->frametype == AST_FRAME_DTMF_END) {
2653 /* There is a generator running while we're in the middle of a digit.
2654 * It's probably inband DTMF, so go ahead and pass it so it can
2655 * stop the generator */
2656 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2657 ast_channel_unlock(chan);
2658 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2659 ast_channel_lock(chan);
2660 CHECK_BLOCKING(chan);
2661 } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2662 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2663 res = (chan->tech->indicate == NULL) ? 0 :
2664 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2666 res = 0; /* XXX explain, why 0 ? */
2667 goto done;
2670 /* High bit prints debugging */
2671 if (chan->fout & DEBUGCHAN_FLAG)
2672 ast_frame_dump(chan->name, fr, ">>");
2673 CHECK_BLOCKING(chan);
2674 switch(fr->frametype) {
2675 case AST_FRAME_CONTROL:
2676 res = (chan->tech->indicate == NULL) ? 0 :
2677 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2678 break;
2679 case AST_FRAME_DTMF_BEGIN:
2680 if (chan->audiohooks) {
2681 struct ast_frame *old_frame = fr;
2682 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2683 if (old_frame != fr)
2684 f = fr;
2686 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2687 ast_channel_unlock(chan);
2688 res = ast_senddigit_begin(chan, fr->subclass);
2689 ast_channel_lock(chan);
2690 CHECK_BLOCKING(chan);
2691 break;
2692 case AST_FRAME_DTMF_END:
2693 if (chan->audiohooks) {
2694 struct ast_frame *old_frame = fr;
2695 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2696 if (old_frame != fr)
2697 f = fr;
2699 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2700 ast_channel_unlock(chan);
2701 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2702 ast_channel_lock(chan);
2703 CHECK_BLOCKING(chan);
2704 break;
2705 case AST_FRAME_TEXT:
2706 res = (chan->tech->send_text == NULL) ? 0 :
2707 chan->tech->send_text(chan, (char *) fr->data);
2708 break;
2709 case AST_FRAME_HTML:
2710 res = (chan->tech->send_html == NULL) ? 0 :
2711 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2712 break;
2713 case AST_FRAME_VIDEO:
2714 /* XXX Handle translation of video codecs one day XXX */
2715 res = (chan->tech->write_video == NULL) ? 0 :
2716 chan->tech->write_video(chan, fr);
2717 break;
2718 case AST_FRAME_MODEM:
2719 res = (chan->tech->write == NULL) ? 0 :
2720 chan->tech->write(chan, fr);
2721 break;
2722 case AST_FRAME_VOICE:
2723 if (chan->tech->write == NULL)
2724 break; /*! \todo XXX should return 0 maybe ? */
2726 if (chan->audiohooks) {
2727 struct ast_frame *old_frame = fr;
2728 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2729 if (old_frame != fr)
2730 f2 = fr;
2733 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2734 if (fr->subclass == chan->rawwriteformat)
2735 f = fr;
2736 else
2737 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2739 /* If we have no frame of audio, then we have to bail out */
2740 if (!f) {
2741 res = 0;
2742 break;
2745 /* If Monitor is running on this channel, then we have to write frames out there too */
2746 if (chan->monitor && chan->monitor->write_stream) {
2747 /* XXX must explain this code */
2748 #ifndef MONITOR_CONSTANT_DELAY
2749 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2750 if (jump >= 0) {
2751 jump = chan->insmpl - chan->outsmpl;
2752 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2753 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2754 chan->outsmpl += jump + f->samples;
2755 } else
2756 chan->outsmpl += f->samples;
2757 #else
2758 int jump = chan->insmpl - chan->outsmpl;
2759 if (jump - MONITOR_DELAY >= 0) {
2760 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2761 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2762 chan->outsmpl += jump;
2763 } else
2764 chan->outsmpl += f->samples;
2765 #endif
2766 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2767 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2768 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2772 if (f)
2773 res = chan->tech->write(chan,f);
2774 else
2775 res = 0;
2776 break;
2777 case AST_FRAME_NULL:
2778 case AST_FRAME_IAX:
2779 /* Ignore these */
2780 res = 0;
2781 break;
2782 default:
2783 /* At this point, fr is the incoming frame and f is NULL. Channels do
2784 * not expect to get NULL as a frame pointer and will segfault. Hence,
2785 * we output the original frame passed in. */
2786 res = chan->tech->write(chan, fr);
2787 break;
2790 if (f && f != fr)
2791 ast_frfree(f);
2792 if (f2)
2793 ast_frfree(f2);
2794 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2795 /* Consider a write failure to force a soft hangup */
2796 if (res < 0)
2797 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2798 else {
2799 chan->fout = FRAMECOUNT_INC(chan->fout);
2801 done:
2802 ast_channel_unlock(chan);
2803 return res;
2806 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2807 struct ast_trans_pvt **trans, const int direction)
2809 int native;
2810 int res;
2811 char from[200], to[200];
2813 /* Make sure we only consider audio */
2814 fmt &= AST_FORMAT_AUDIO_MASK;
2816 native = chan->nativeformats;
2817 /* Find a translation path from the native format to one of the desired formats */
2818 if (!direction)
2819 /* reading */
2820 res = ast_translator_best_choice(&fmt, &native);
2821 else
2822 /* writing */
2823 res = ast_translator_best_choice(&native, &fmt);
2825 if (res < 0) {
2826 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2827 ast_getformatname_multiple(from, sizeof(from), native),
2828 ast_getformatname_multiple(to, sizeof(to), fmt));
2829 return -1;
2832 /* Now we have a good choice for both. */
2833 ast_channel_lock(chan);
2835 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2836 /* the channel is already in these formats, so nothing to do */
2837 ast_channel_unlock(chan);
2838 return 0;
2841 *rawformat = native;
2842 /* User perspective is fmt */
2843 *format = fmt;
2844 /* Free any read translation we have right now */
2845 if (*trans)
2846 ast_translator_free_path(*trans);
2847 /* Build a translation path from the raw format to the desired format */
2848 if (!direction)
2849 /* reading */
2850 *trans = ast_translator_build_path(*format, *rawformat);
2851 else
2852 /* writing */
2853 *trans = ast_translator_build_path(*rawformat, *format);
2854 ast_channel_unlock(chan);
2855 if (option_debug)
2856 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2857 direction ? "write" : "read", ast_getformatname(fmt));
2858 return 0;
2861 int ast_set_read_format(struct ast_channel *chan, int fmt)
2863 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2864 &chan->readtrans, 0);
2867 int ast_set_write_format(struct ast_channel *chan, int fmt)
2869 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2870 &chan->writetrans, 1);
2873 char *ast_channel_reason2str(int reason)
2875 switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
2877 case 0:
2878 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
2879 case AST_CONTROL_HANGUP:
2880 return "Hangup";
2881 case AST_CONTROL_RING:
2882 return "Local Ring";
2883 case AST_CONTROL_RINGING:
2884 return "Remote end Ringing";
2885 case AST_CONTROL_ANSWER:
2886 return "Remote end has Answered";
2887 case AST_CONTROL_BUSY:
2888 return "Remote end is Busy";
2889 case AST_CONTROL_CONGESTION:
2890 return "Congestion (circuits busy)";
2891 default:
2892 return "Unknown Reason!!";
2896 struct ast_channel *__ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, struct outgoing_helper *oh)
2898 int dummy_outstate;
2899 int cause = 0;
2900 struct ast_channel *chan;
2901 int res = 0;
2902 int last_subclass = 0;
2904 if (outstate)
2905 *outstate = 0;
2906 else
2907 outstate = &dummy_outstate; /* make outstate always a valid pointer */
2909 chan = ast_request(type, format, data, &cause);
2910 if (!chan) {
2911 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2912 /* compute error and return */
2913 if (cause == AST_CAUSE_BUSY)
2914 *outstate = AST_CONTROL_BUSY;
2915 else if (cause == AST_CAUSE_CONGESTION)
2916 *outstate = AST_CONTROL_CONGESTION;
2917 return NULL;
2920 if (oh) {
2921 if (oh->vars)
2922 ast_set_variables(chan, oh->vars);
2923 /* XXX why is this necessary, for the parent_channel perhaps ? */
2924 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2925 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2926 if (oh->parent_channel)
2927 ast_channel_inherit_variables(oh->parent_channel, chan);
2928 if (oh->account)
2929 ast_cdr_setaccount(chan, oh->account);
2931 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2933 if (ast_call(chan, data, 0)) { /* ast_call failed... */
2934 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2935 } else {
2936 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
2937 while (timeout && chan->_state != AST_STATE_UP) {
2938 struct ast_frame *f;
2939 res = ast_waitfor(chan, timeout);
2940 if (res <= 0) /* error, timeout, or done */
2941 break;
2942 if (timeout > -1)
2943 timeout = res;
2944 f = ast_read(chan);
2945 if (!f) {
2946 *outstate = AST_CONTROL_HANGUP;
2947 res = 0;
2948 break;
2950 if (f->frametype == AST_FRAME_CONTROL) {
2951 switch (f->subclass) {
2952 case AST_CONTROL_RINGING: /* record but keep going */
2953 *outstate = f->subclass;
2954 break;
2956 case AST_CONTROL_BUSY:
2957 case AST_CONTROL_CONGESTION:
2958 case AST_CONTROL_ANSWER:
2959 *outstate = f->subclass;
2960 timeout = 0; /* trick to force exit from the while() */
2961 break;
2963 /* Ignore these */
2964 case AST_CONTROL_PROGRESS:
2965 case AST_CONTROL_PROCEEDING:
2966 case AST_CONTROL_HOLD:
2967 case AST_CONTROL_UNHOLD:
2968 case AST_CONTROL_VIDUPDATE:
2969 case AST_CONTROL_SRCUPDATE:
2970 case -1: /* Ignore -- just stopping indications */
2971 break;
2973 default:
2974 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2976 last_subclass = f->subclass;
2978 ast_frfree(f);
2982 /* Final fixups */
2983 if (oh) {
2984 if (!ast_strlen_zero(oh->context))
2985 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2986 if (!ast_strlen_zero(oh->exten))
2987 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2988 if (oh->priority)
2989 chan->priority = oh->priority;
2991 if (chan->_state == AST_STATE_UP)
2992 *outstate = AST_CONTROL_ANSWER;
2994 if (res <= 0) {
2995 if ( AST_CONTROL_RINGING == last_subclass )
2996 chan->hangupcause = AST_CAUSE_NO_ANSWER;
2997 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2998 ast_cdr_init(chan->cdr, chan);
2999 if (chan->cdr) {
3000 char tmp[256];
3001 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
3002 ast_cdr_setapp(chan->cdr,"Dial",tmp);
3003 ast_cdr_update(chan);
3004 ast_cdr_start(chan->cdr);
3005 ast_cdr_end(chan->cdr);
3006 /* If the cause wasn't handled properly */
3007 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
3008 ast_cdr_failed(chan->cdr);
3010 ast_hangup(chan);
3011 chan = NULL;
3013 return chan;
3016 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
3018 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
3021 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
3023 struct chanlist *chan;
3024 struct ast_channel *c;
3025 int capabilities;
3026 int fmt;
3027 int res;
3028 int foo;
3029 int videoformat = format & AST_FORMAT_VIDEO_MASK;
3031 if (!cause)
3032 cause = &foo;
3033 *cause = AST_CAUSE_NOTDEFINED;
3035 if (AST_LIST_LOCK(&channels)) {
3036 ast_log(LOG_WARNING, "Unable to lock channel list\n");
3037 return NULL;
3040 AST_LIST_TRAVERSE(&backends, chan, list) {
3041 if (strcasecmp(type, chan->tech->type))
3042 continue;
3044 capabilities = chan->tech->capabilities;
3045 fmt = format & AST_FORMAT_AUDIO_MASK;
3046 res = ast_translator_best_choice(&fmt, &capabilities);
3047 if (res < 0) {
3048 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
3049 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3050 AST_LIST_UNLOCK(&channels);
3051 return NULL;
3053 AST_LIST_UNLOCK(&channels);
3054 if (!chan->tech->requester)
3055 return NULL;
3057 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
3058 return NULL;
3060 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3061 return c;
3064 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
3065 *cause = AST_CAUSE_NOSUCHDRIVER;
3066 AST_LIST_UNLOCK(&channels);
3068 return NULL;
3071 int ast_call(struct ast_channel *chan, char *addr, int timeout)
3073 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3074 If the remote end does not answer within the timeout, then do NOT hang up, but
3075 return anyway. */
3076 int res = -1;
3077 /* Stop if we're a zombie or need a soft hangup */
3078 ast_channel_lock(chan);
3079 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3080 if (chan->cdr)
3081 ast_set_flag(chan->cdr, AST_CDR_FLAG_DIALED);
3082 if (chan->tech->call)
3083 res = chan->tech->call(chan, addr, timeout);
3084 ast_set_flag(chan, AST_FLAG_OUTGOING);
3086 ast_channel_unlock(chan);
3087 return res;
3091 \brief Transfer a call to dest, if the channel supports transfer
3093 Called by:
3094 \arg app_transfer
3095 \arg the manager interface
3097 int ast_transfer(struct ast_channel *chan, char *dest)
3099 int res = -1;
3101 /* Stop if we're a zombie or need a soft hangup */
3102 ast_channel_lock(chan);
3103 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3104 if (chan->tech->transfer) {
3105 res = chan->tech->transfer(chan, dest);
3106 if (!res)
3107 res = 1;
3108 } else
3109 res = 0;
3111 ast_channel_unlock(chan);
3112 return res;
3115 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3117 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3120 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3122 int pos = 0; /* index in the buffer where we accumulate digits */
3123 int to = ftimeout;
3125 /* Stop if we're a zombie or need a soft hangup */
3126 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3127 return -1;
3128 if (!len)
3129 return -1;
3130 for (;;) {
3131 int d;
3132 if (c->stream) {
3133 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3134 ast_stopstream(c);
3135 usleep(1000);
3136 if (!d)
3137 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3138 } else {
3139 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3141 if (d < 0)
3142 return -1;
3143 if (d == 0) {
3144 s[pos]='\0';
3145 return 1;
3147 if (d == 1) {
3148 s[pos]='\0';
3149 return 2;
3151 if (!strchr(enders, d))
3152 s[pos++] = d;
3153 if (strchr(enders, d) || (pos >= len)) {
3154 s[pos]='\0';
3155 return 0;
3157 to = timeout;
3159 /* Never reached */
3160 return 0;
3163 int ast_channel_supports_html(struct ast_channel *chan)
3165 return (chan->tech->send_html) ? 1 : 0;
3168 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3170 if (chan->tech->send_html)
3171 return chan->tech->send_html(chan, subclass, data, datalen);
3172 return -1;
3175 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3177 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3180 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3182 int src;
3183 int dst;
3185 if (chan->readformat == peer->writeformat && chan->writeformat == peer->readformat) {
3186 /* Already compatible! Moving on ... */
3187 return 0;
3190 /* Set up translation from the chan to the peer */
3191 src = chan->nativeformats;
3192 dst = peer->nativeformats;
3193 if (ast_translator_best_choice(&dst, &src) < 0) {
3194 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
3195 return -1;
3198 /* if the best path is not 'pass through', then
3199 transcoding is needed; if desired, force transcode path
3200 to use SLINEAR between channels, but only if there is
3201 no direct conversion available */
3202 if ((src != dst) && ast_opt_transcode_via_slin &&
3203 (ast_translate_path_steps(dst, src) != 1))
3204 dst = AST_FORMAT_SLINEAR;
3205 if (ast_set_read_format(chan, dst) < 0) {
3206 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
3207 return -1;
3209 if (ast_set_write_format(peer, dst) < 0) {
3210 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
3211 return -1;
3214 /* Set up translation from the peer to the chan */
3215 src = peer->nativeformats;
3216 dst = chan->nativeformats;
3217 if (ast_translator_best_choice(&dst, &src) < 0) {
3218 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
3219 return -1;
3222 /* if the best path is not 'pass through', then
3223 transcoding is needed; if desired, force transcode path
3224 to use SLINEAR between channels, but only if there is
3225 no direct conversion available */
3226 if ((src != dst) && ast_opt_transcode_via_slin &&
3227 (ast_translate_path_steps(dst, src) != 1))
3228 dst = AST_FORMAT_SLINEAR;
3229 if (ast_set_read_format(peer, dst) < 0) {
3230 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
3231 return -1;
3233 if (ast_set_write_format(chan, dst) < 0) {
3234 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
3235 return -1;
3237 return 0;
3240 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3242 int res = -1;
3243 struct ast_channel *final_orig, *final_clone, *base;
3245 retrymasq:
3246 final_orig = original;
3247 final_clone = clone;
3249 ast_channel_lock(original);
3250 while (ast_channel_trylock(clone)) {
3251 ast_channel_unlock(original);
3252 usleep(1);
3253 ast_channel_lock(original);
3256 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3257 and if so, we don't really want to masquerade it, but its proxy */
3258 if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
3259 final_orig = original->_bridge;
3261 if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)) && (clone->_bridge->_bridge != clone))
3262 final_clone = clone->_bridge;
3264 if (final_clone->tech->get_base_channel && (base = final_clone->tech->get_base_channel(final_clone))) {
3265 final_clone = base;
3268 if ((final_orig != original) || (final_clone != clone)) {
3269 /* Lots and lots of deadlock avoidance. The main one we're competing with
3270 * is ast_write(), which locks channels recursively, when working with a
3271 * proxy channel. */
3272 if (ast_channel_trylock(final_orig)) {
3273 ast_channel_unlock(clone);
3274 ast_channel_unlock(original);
3275 goto retrymasq;
3277 if (ast_channel_trylock(final_clone)) {
3278 ast_channel_unlock(final_orig);
3279 ast_channel_unlock(clone);
3280 ast_channel_unlock(original);
3281 goto retrymasq;
3283 ast_channel_unlock(clone);
3284 ast_channel_unlock(original);
3285 original = final_orig;
3286 clone = final_clone;
3289 if (original == clone) {
3290 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3291 ast_channel_unlock(clone);
3292 ast_channel_unlock(original);
3293 return -1;
3296 if (option_debug)
3297 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
3298 clone->name, original->name);
3299 if (original->masq) {
3300 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3301 original->masq->name, original->name);
3302 } else if (clone->masqr) {
3303 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3304 clone->name, clone->masqr->name);
3305 } else {
3306 original->masq = clone;
3307 clone->masqr = original;
3308 ast_queue_frame(original, &ast_null_frame);
3309 ast_queue_frame(clone, &ast_null_frame);
3310 if (option_debug)
3311 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3312 res = 0;
3315 ast_channel_unlock(clone);
3316 ast_channel_unlock(original);
3318 return res;
3321 void ast_change_name(struct ast_channel *chan, char *newname)
3323 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3324 ast_string_field_set(chan, name, newname);
3327 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3329 struct ast_var_t *current, *newvar;
3330 const char *varname;
3332 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3333 int vartype = 0;
3335 varname = ast_var_full_name(current);
3336 if (!varname)
3337 continue;
3339 if (varname[0] == '_') {
3340 vartype = 1;
3341 if (varname[1] == '_')
3342 vartype = 2;
3345 switch (vartype) {
3346 case 1:
3347 newvar = ast_var_assign(&varname[1], ast_var_value(current));
3348 if (newvar) {
3349 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3350 if (option_debug)
3351 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3353 break;
3354 case 2:
3355 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
3356 if (newvar) {
3357 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3358 if (option_debug)
3359 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3361 break;
3362 default:
3363 if (option_debug)
3364 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
3365 break;
3371 \brief Clone channel variables from 'clone' channel into 'original' channel
3373 All variables except those related to app_groupcount are cloned.
3374 Variables are actually _removed_ from 'clone' channel, presumably
3375 because it will subsequently be destroyed.
3377 \note Assumes locks will be in place on both channels when called.
3379 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3381 struct ast_var_t *current, *newvar;
3382 /* Append variables from clone channel into original channel */
3383 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3384 if (AST_LIST_FIRST(&clone->varshead))
3385 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3387 /* then, dup the varshead list into the clone */
3389 AST_LIST_TRAVERSE(&original->varshead, current, entries) {
3390 newvar = ast_var_assign(current->name, current->value);
3391 if (newvar)
3392 AST_LIST_INSERT_TAIL(&clone->varshead, newvar, entries);
3397 \brief Masquerade a channel
3399 \note Assumes channel will be locked when called
3401 int ast_do_masquerade(struct ast_channel *original)
3403 int x,i;
3404 int res=0;
3405 int origstate;
3406 struct ast_frame *cur;
3407 const struct ast_channel_tech *t;
3408 void *t_pvt;
3409 struct ast_callerid tmpcid;
3410 struct ast_channel *clone = original->masq;
3411 struct ast_cdr *cdr;
3412 int rformat = original->readformat;
3413 int wformat = original->writeformat;
3414 char newn[100];
3415 char orig[100];
3416 char masqn[100];
3417 char zombn[100];
3419 if (option_debug > 3)
3420 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3421 clone->name, clone->_state, original->name, original->_state);
3423 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3424 the clone channel into the original channel. Start by killing off the original
3425 channel's backend. I'm not sure we're going to keep this function, because
3426 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3428 /* We need the clone's lock, too */
3429 ast_channel_lock(clone);
3431 if (option_debug > 1)
3432 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3434 /* Having remembered the original read/write formats, we turn off any translation on either
3435 one */
3436 free_translation(clone);
3437 free_translation(original);
3440 /* Unlink the masquerade */
3441 original->masq = NULL;
3442 clone->masqr = NULL;
3444 /* Save the original name */
3445 ast_copy_string(orig, original->name, sizeof(orig));
3446 /* Save the new name */
3447 ast_copy_string(newn, clone->name, sizeof(newn));
3448 /* Create the masq name */
3449 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3451 /* Copy the name from the clone channel */
3452 ast_string_field_set(original, name, newn);
3454 /* Mangle the name of the clone channel */
3455 ast_string_field_set(clone, name, masqn);
3457 /* Notify any managers of the change, first the masq then the other */
3458 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3459 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3461 /* Swap the technologies */
3462 t = original->tech;
3463 original->tech = clone->tech;
3464 clone->tech = t;
3466 /* Swap the cdrs */
3467 cdr = original->cdr;
3468 original->cdr = clone->cdr;
3469 clone->cdr = cdr;
3471 t_pvt = original->tech_pvt;
3472 original->tech_pvt = clone->tech_pvt;
3473 clone->tech_pvt = t_pvt;
3475 /* Swap the alertpipes */
3476 for (i = 0; i < 2; i++) {
3477 x = original->alertpipe[i];
3478 original->alertpipe[i] = clone->alertpipe[i];
3479 clone->alertpipe[i] = x;
3483 * Swap the readq's. The end result should be this:
3485 * 1) All frames should be on the new (original) channel.
3486 * 2) Any frames that were already on the new channel before this
3487 * masquerade need to be at the end of the readq, after all of the
3488 * frames on the old (clone) channel.
3489 * 3) The alertpipe needs to get poked for every frame that was already
3490 * on the new channel, since we are now using the alert pipe from the
3491 * old (clone) channel.
3494 AST_LIST_HEAD_NOLOCK(, ast_frame) tmp_readq;
3495 AST_LIST_HEAD_SET_NOLOCK(&tmp_readq, NULL);
3497 AST_LIST_APPEND_LIST(&tmp_readq, &original->readq, frame_list);
3498 AST_LIST_APPEND_LIST(&original->readq, &clone->readq, frame_list);
3500 while ((cur = AST_LIST_REMOVE_HEAD(&tmp_readq, frame_list))) {
3501 AST_LIST_INSERT_TAIL(&original->readq, cur, frame_list);
3502 if (original->alertpipe[1] > -1) {
3503 int poke = 0;
3504 write(original->alertpipe[1], &poke, sizeof(poke));
3509 /* Swap the raw formats */
3510 x = original->rawreadformat;
3511 original->rawreadformat = clone->rawreadformat;
3512 clone->rawreadformat = x;
3513 x = original->rawwriteformat;
3514 original->rawwriteformat = clone->rawwriteformat;
3515 clone->rawwriteformat = x;
3517 clone->_softhangup = AST_SOFTHANGUP_DEV;
3519 /* And of course, so does our current state. Note we need not
3520 call ast_setstate since the event manager doesn't really consider
3521 these separate. We do this early so that the clone has the proper
3522 state of the original channel. */
3523 origstate = original->_state;
3524 original->_state = clone->_state;
3525 clone->_state = origstate;
3527 if (clone->tech->fixup){
3528 res = clone->tech->fixup(original, clone);
3529 if (res)
3530 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3533 /* Start by disconnecting the original's physical side */
3534 if (clone->tech->hangup)
3535 res = clone->tech->hangup(clone);
3536 if (res) {
3537 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
3538 ast_channel_unlock(clone);
3539 return -1;
3542 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3543 /* Mangle the name of the clone channel */
3544 ast_string_field_set(clone, name, zombn);
3545 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3547 /* Update the type. */
3548 t_pvt = original->monitor;
3549 original->monitor = clone->monitor;
3550 clone->monitor = t_pvt;
3552 /* Keep the same language. */
3553 ast_string_field_set(original, language, clone->language);
3554 /* Copy the FD's other than the generator fd */
3555 for (x = 0; x < AST_MAX_FDS; x++) {
3556 if (x != AST_GENERATOR_FD)
3557 original->fds[x] = clone->fds[x];
3560 ast_app_group_update(clone, original);
3561 /* Move data stores over */
3562 if (AST_LIST_FIRST(&clone->datastores)) {
3563 struct ast_datastore *ds;
3564 AST_LIST_APPEND_LIST(&original->datastores, &clone->datastores, entry);
3565 AST_LIST_TRAVERSE(&original->datastores, ds, entry) {
3566 if (ds->info->chan_fixup)
3567 ds->info->chan_fixup(ds->data, clone, original);
3571 clone_variables(original, clone);
3572 /* Presense of ADSI capable CPE follows clone */
3573 original->adsicpe = clone->adsicpe;
3574 /* Bridge remains the same */
3575 /* CDR fields remain the same */
3576 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3577 /* Application and data remain the same */
3578 /* Clone exception becomes real one, as with fdno */
3579 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3580 original->fdno = clone->fdno;
3581 /* Schedule context remains the same */
3582 /* Stream stuff stays the same */
3583 /* Keep the original state. The fixup code will need to work with it most likely */
3585 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3586 out. */
3587 tmpcid = original->cid;
3588 original->cid = clone->cid;
3589 clone->cid = tmpcid;
3591 /* Restore original timing file descriptor */
3592 original->fds[AST_TIMING_FD] = original->timingfd;
3594 /* Our native formats are different now */
3595 original->nativeformats = clone->nativeformats;
3597 /* Context, extension, priority, app data, jump table, remain the same */
3598 /* pvt switches. pbx stays the same, as does next */
3600 /* Set the write format */
3601 ast_set_write_format(original, wformat);
3603 /* Set the read format */
3604 ast_set_read_format(original, rformat);
3606 /* Copy the music class */
3607 ast_string_field_set(original, musicclass, clone->musicclass);
3609 if (option_debug)
3610 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3612 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3613 can fix up everything as best as possible */
3614 if (original->tech->fixup) {
3615 res = original->tech->fixup(clone, original);
3616 if (res) {
3617 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3618 original->tech->type, original->name);
3619 ast_channel_unlock(clone);
3620 return -1;
3622 } else
3623 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3624 original->tech->type, original->name);
3626 /* If an indication is currently playing maintain it on the channel that is taking the place of original */
3627 if (original->visible_indication)
3628 ast_indicate(original, original->visible_indication);
3630 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3631 a zombie so nothing tries to touch it. If it's already been marked as a
3632 zombie, then free it now (since it already is considered invalid). */
3633 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3634 if (option_debug)
3635 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3636 ast_channel_unlock(clone);
3637 manager_event(EVENT_FLAG_CALL, "Hangup",
3638 "Channel: %s\r\n"
3639 "Uniqueid: %s\r\n"
3640 "Cause: %d\r\n"
3641 "Cause-txt: %s\r\n",
3642 clone->name,
3643 clone->uniqueid,
3644 clone->hangupcause,
3645 ast_cause2str(clone->hangupcause)
3647 ast_channel_free(clone);
3648 } else {
3649 if (option_debug)
3650 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3651 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3652 ast_queue_frame(clone, &ast_null_frame);
3653 ast_channel_unlock(clone);
3656 /* Signal any blocker */
3657 if (ast_test_flag(original, AST_FLAG_BLOCKING))
3658 pthread_kill(original->blocker, SIGURG);
3659 if (option_debug)
3660 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3661 return 0;
3664 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3666 ast_channel_lock(chan);
3668 if (callerid) {
3669 if (chan->cid.cid_num)
3670 free(chan->cid.cid_num);
3671 chan->cid.cid_num = ast_strdup(callerid);
3673 if (calleridname) {
3674 if (chan->cid.cid_name)
3675 free(chan->cid.cid_name);
3676 chan->cid.cid_name = ast_strdup(calleridname);
3678 if (ani) {
3679 if (chan->cid.cid_ani)
3680 free(chan->cid.cid_ani);
3681 chan->cid.cid_ani = ast_strdup(ani);
3683 manager_event(EVENT_FLAG_CALL, "Newcallerid",
3684 "Channel: %s\r\n"
3685 "CallerID: %s\r\n"
3686 "CallerIDName: %s\r\n"
3687 "Uniqueid: %s\r\n"
3688 "CID-CallingPres: %d (%s)\r\n",
3689 chan->name,
3690 S_OR(chan->cid.cid_num, "<Unknown>"),
3691 S_OR(chan->cid.cid_name, "<Unknown>"),
3692 chan->uniqueid,
3693 chan->cid.cid_pres,
3694 ast_describe_caller_presentation(chan->cid.cid_pres)
3697 ast_channel_unlock(chan);
3700 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
3702 char name[AST_CHANNEL_NAME], *dashptr;
3703 int oldstate = chan->_state;
3705 if (oldstate == state)
3706 return 0;
3708 ast_copy_string(name, chan->name, sizeof(name));
3709 if ((dashptr = strrchr(name, '-'))) {
3710 *dashptr = '\0';
3713 chan->_state = state;
3714 ast_device_state_changed_literal(name);
3715 /* setstate used to conditionally report Newchannel; this is no more */
3716 manager_event(EVENT_FLAG_CALL,
3717 "Newstate",
3718 "Channel: %s\r\n"
3719 "State: %s\r\n"
3720 "CallerID: %s\r\n"
3721 "CallerIDName: %s\r\n"
3722 "Uniqueid: %s\r\n",
3723 chan->name, ast_state2str(chan->_state),
3724 S_OR(chan->cid.cid_num, "<unknown>"),
3725 S_OR(chan->cid.cid_name, "<unknown>"),
3726 chan->uniqueid);
3728 return 0;
3731 /*! \brief Find bridged channel */
3732 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3734 struct ast_channel *bridged;
3735 bridged = chan->_bridge;
3736 if (bridged && bridged->tech->bridged_channel)
3737 bridged = bridged->tech->bridged_channel(chan, bridged);
3738 return bridged;
3741 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3743 int min = 0, sec = 0, check;
3745 check = ast_autoservice_start(peer);
3746 if (check)
3747 return;
3749 if (remain > 0) {
3750 if (remain / 60 > 1) {
3751 min = remain / 60;
3752 sec = remain % 60;
3753 } else {
3754 sec = remain;
3758 if (!strcmp(sound,"timeleft")) { /* Queue support */
3759 ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
3760 if (min) {
3761 ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
3762 ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
3764 if (sec) {
3765 ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
3766 ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
3768 } else {
3769 ast_stream_and_wait(chan, sound, chan->language, "");
3772 ast_autoservice_stop(peer);
3775 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3776 struct ast_bridge_config *config, struct ast_frame **fo,
3777 struct ast_channel **rc, struct timeval bridge_end)
3779 /* Copy voice back and forth between the two channels. */
3780 struct ast_channel *cs[3];
3781 struct ast_frame *f;
3782 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3783 int o0nativeformats;
3784 int o1nativeformats;
3785 int watch_c0_dtmf;
3786 int watch_c1_dtmf;
3787 void *pvt0, *pvt1;
3788 /* Indicates whether a frame was queued into a jitterbuffer */
3789 int frame_put_in_jb = 0;
3790 int jb_in_use;
3791 int to;
3793 cs[0] = c0;
3794 cs[1] = c1;
3795 pvt0 = c0->tech_pvt;
3796 pvt1 = c1->tech_pvt;
3797 o0nativeformats = c0->nativeformats;
3798 o1nativeformats = c1->nativeformats;
3799 watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3800 watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3802 /* Check the need of a jitterbuffer for each channel */
3803 jb_in_use = ast_jb_do_usecheck(c0, c1);
3804 if (jb_in_use)
3805 ast_jb_empty_and_reset(c0, c1);
3807 for (;;) {
3808 struct ast_channel *who, *other;
3810 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3811 (o0nativeformats != c0->nativeformats) ||
3812 (o1nativeformats != c1->nativeformats)) {
3813 /* Check for Masquerade, codec changes, etc */
3814 res = AST_BRIDGE_RETRY;
3815 break;
3817 if (bridge_end.tv_sec) {
3818 to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3819 if (to <= 0) {
3820 if (config->timelimit)
3821 res = AST_BRIDGE_RETRY;
3822 else
3823 res = AST_BRIDGE_COMPLETE;
3824 break;
3826 } else
3827 to = -1;
3828 /* Calculate the appropriate max sleep interval - in general, this is the time,
3829 left to the closest jb delivery moment */
3830 if (jb_in_use)
3831 to = ast_jb_get_when_to_wakeup(c0, c1, to);
3832 who = ast_waitfor_n(cs, 2, &to);
3833 if (!who) {
3834 /* No frame received within the specified timeout - check if we have to deliver now */
3835 if (jb_in_use)
3836 ast_jb_get_and_deliver(c0, c1);
3837 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3838 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3839 c0->_softhangup = 0;
3840 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3841 c1->_softhangup = 0;
3842 c0->_bridge = c1;
3843 c1->_bridge = c0;
3845 continue;
3847 f = ast_read(who);
3848 if (!f) {
3849 *fo = NULL;
3850 *rc = who;
3851 if (option_debug)
3852 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3853 break;
3856 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3857 /* Try add the frame info the who's bridged channel jitterbuff */
3858 if (jb_in_use)
3859 frame_put_in_jb = !ast_jb_put(other, f);
3861 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3862 int bridge_exit = 0;
3864 switch (f->subclass) {
3865 case AST_CONTROL_HOLD:
3866 case AST_CONTROL_UNHOLD:
3867 case AST_CONTROL_VIDUPDATE:
3868 case AST_CONTROL_SRCUPDATE:
3869 ast_indicate_data(other, f->subclass, f->data, f->datalen);
3870 if (jb_in_use) {
3871 ast_jb_empty_and_reset(c0, c1);
3873 break;
3874 default:
3875 *fo = f;
3876 *rc = who;
3877 bridge_exit = 1;
3878 if (option_debug)
3879 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3880 break;
3882 if (bridge_exit)
3883 break;
3885 if ((f->frametype == AST_FRAME_VOICE) ||
3886 (f->frametype == AST_FRAME_DTMF_BEGIN) ||
3887 (f->frametype == AST_FRAME_DTMF) ||
3888 (f->frametype == AST_FRAME_VIDEO) ||
3889 (f->frametype == AST_FRAME_IMAGE) ||
3890 (f->frametype == AST_FRAME_HTML) ||
3891 (f->frametype == AST_FRAME_MODEM) ||
3892 (f->frametype == AST_FRAME_TEXT)) {
3893 /* monitored dtmf causes exit from bridge */
3894 int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
3896 if (monitored_source &&
3897 (f->frametype == AST_FRAME_DTMF_END ||
3898 f->frametype == AST_FRAME_DTMF_BEGIN)) {
3899 *fo = f;
3900 *rc = who;
3901 if (option_debug)
3902 ast_log(LOG_DEBUG, "Got DTMF %s on channel (%s)\n",
3903 f->frametype == AST_FRAME_DTMF_END ? "end" : "begin",
3904 who->name);
3905 break;
3907 /* Write immediately frames, not passed through jb */
3908 if (!frame_put_in_jb)
3909 ast_write(other, f);
3911 /* Check if we have to deliver now */
3912 if (jb_in_use)
3913 ast_jb_get_and_deliver(c0, c1);
3915 /* XXX do we want to pass on also frames not matched above ? */
3916 ast_frfree(f);
3918 /* Swap who gets priority */
3919 cs[2] = cs[0];
3920 cs[0] = cs[1];
3921 cs[1] = cs[2];
3923 return res;
3926 /*! \brief Bridge two channels together */
3927 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3928 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
3930 struct ast_channel *who = NULL;
3931 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3932 int nativefailed=0;
3933 int firstpass;
3934 int o0nativeformats;
3935 int o1nativeformats;
3936 long time_left_ms=0;
3937 struct timeval nexteventts = { 0, };
3938 char caller_warning = 0;
3939 char callee_warning = 0;
3941 if (c0->_bridge) {
3942 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3943 c0->name, c0->_bridge->name);
3944 return -1;
3946 if (c1->_bridge) {
3947 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3948 c1->name, c1->_bridge->name);
3949 return -1;
3952 /* Stop if we're a zombie or need a soft hangup */
3953 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3954 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3955 return -1;
3957 *fo = NULL;
3958 firstpass = config->firstpass;
3959 config->firstpass = 0;
3961 if (ast_tvzero(config->start_time))
3962 config->start_time = ast_tvnow();
3963 time_left_ms = config->timelimit;
3965 caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3966 callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3968 if (config->start_sound && firstpass) {
3969 if (caller_warning)
3970 bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3971 if (callee_warning)
3972 bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3975 /* Keep track of bridge */
3976 c0->_bridge = c1;
3977 c1->_bridge = c0;
3979 /* \todo XXX here should check that cid_num is not NULL */
3980 manager_event(EVENT_FLAG_CALL, "Link",
3981 "Channel1: %s\r\n"
3982 "Channel2: %s\r\n"
3983 "Uniqueid1: %s\r\n"
3984 "Uniqueid2: %s\r\n"
3985 "CallerID1: %s\r\n"
3986 "CallerID2: %s\r\n",
3987 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3989 o0nativeformats = c0->nativeformats;
3990 o1nativeformats = c1->nativeformats;
3992 if (config->feature_timer) {
3993 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->feature_timer, 1000));
3994 } else if (config->timelimit) {
3995 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3996 if (caller_warning || callee_warning)
3997 nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
4000 if (!c0->tech->send_digit_begin)
4001 ast_set_flag(c1, AST_FLAG_END_DTMF_ONLY);
4002 if (!c1->tech->send_digit_begin)
4003 ast_set_flag(c0, AST_FLAG_END_DTMF_ONLY);
4005 /* Before we enter in and bridge these two together tell them both the source of audio has changed */
4006 ast_indicate(c0, AST_CONTROL_SRCUPDATE);
4007 ast_indicate(c1, AST_CONTROL_SRCUPDATE);
4009 for (/* ever */;;) {
4010 struct timeval now = { 0, };
4011 int to;
4013 to = -1;
4015 if (!ast_tvzero(nexteventts)) {
4016 now = ast_tvnow();
4017 to = ast_tvdiff_ms(nexteventts, now);
4018 if (to <= 0) {
4019 if (!config->timelimit) {
4020 res = AST_BRIDGE_COMPLETE;
4021 break;
4023 to = 0;
4027 if (config->timelimit) {
4028 time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
4029 if (time_left_ms < to)
4030 to = time_left_ms;
4032 if (time_left_ms <= 0) {
4033 if (caller_warning && config->end_sound)
4034 bridge_playfile(c0, c1, config->end_sound, 0);
4035 if (callee_warning && config->end_sound)
4036 bridge_playfile(c1, c0, config->end_sound, 0);
4037 *fo = NULL;
4038 if (who)
4039 *rc = who;
4040 res = 0;
4041 break;
4044 if (!to) {
4045 if (time_left_ms >= 5000 && config->warning_sound && config->play_warning) {
4046 int t = (time_left_ms + 500) / 1000; /* round to nearest second */
4047 if (caller_warning)
4048 bridge_playfile(c0, c1, config->warning_sound, t);
4049 if (callee_warning)
4050 bridge_playfile(c1, c0, config->warning_sound, t);
4052 if (config->warning_freq && (time_left_ms > (config->warning_freq + 5000)))
4053 nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
4054 else
4055 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
4059 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
4060 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4061 c0->_softhangup = 0;
4062 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4063 c1->_softhangup = 0;
4064 c0->_bridge = c1;
4065 c1->_bridge = c0;
4066 if (option_debug)
4067 ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
4068 continue;
4071 /* Stop if we're a zombie or need a soft hangup */
4072 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
4073 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
4074 *fo = NULL;
4075 if (who)
4076 *rc = who;
4077 res = 0;
4078 if (option_debug)
4079 ast_log(LOG_DEBUG, "Bridge stops because we're zombie or need a soft hangup: c0=%s, c1=%s, flags: %s,%s,%s,%s\n",
4080 c0->name, c1->name,
4081 ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
4082 ast_check_hangup(c0) ? "Yes" : "No",
4083 ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
4084 ast_check_hangup(c1) ? "Yes" : "No");
4085 break;
4088 /* See if the BRIDGEPEER variable needs to be updated */
4089 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER")))
4090 pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1->name);
4091 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER")))
4092 pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0->name);
4094 if (c0->tech->bridge &&
4095 (config->timelimit == 0) &&
4096 (c0->tech->bridge == c1->tech->bridge) &&
4097 !nativefailed && !c0->monitor && !c1->monitor &&
4098 !c0->audiohooks && !c1->audiohooks && !ast_test_flag(&(config->features_callee),AST_FEATURE_REDIRECT) &&
4099 !ast_test_flag(&(config->features_caller),AST_FEATURE_REDIRECT) &&
4100 !c0->masq && !c0->masqr && !c1->masq && !c1->masqr) {
4101 /* Looks like they share a bridge method and nothing else is in the way */
4102 ast_set_flag(c0, AST_FLAG_NBRIDGE);
4103 ast_set_flag(c1, AST_FLAG_NBRIDGE);
4104 if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, to)) == AST_BRIDGE_COMPLETE) {
4105 /* \todo XXX here should check that cid_num is not NULL */
4106 manager_event(EVENT_FLAG_CALL, "Unlink",
4107 "Channel1: %s\r\n"
4108 "Channel2: %s\r\n"
4109 "Uniqueid1: %s\r\n"
4110 "Uniqueid2: %s\r\n"
4111 "CallerID1: %s\r\n"
4112 "CallerID2: %s\r\n",
4113 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4114 if (option_debug)
4115 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
4117 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
4118 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
4120 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4121 continue;
4123 c0->_bridge = NULL;
4124 c1->_bridge = NULL;
4126 return res;
4127 } else {
4128 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
4129 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
4131 switch (res) {
4132 case AST_BRIDGE_RETRY:
4133 continue;
4134 default:
4135 if (option_verbose > 2)
4136 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s ended\n",
4137 c0->name, c1->name);
4138 /* fallthrough */
4139 case AST_BRIDGE_FAILED_NOWARN:
4140 nativefailed++;
4141 break;
4145 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
4146 (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
4147 !(c0->generator || c1->generator)) {
4148 if (ast_channel_make_compatible(c0, c1)) {
4149 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
4150 /* \todo XXX here should check that cid_num is not NULL */
4151 manager_event(EVENT_FLAG_CALL, "Unlink",
4152 "Channel1: %s\r\n"
4153 "Channel2: %s\r\n"
4154 "Uniqueid1: %s\r\n"
4155 "Uniqueid2: %s\r\n"
4156 "CallerID1: %s\r\n"
4157 "CallerID2: %s\r\n",
4158 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4159 return AST_BRIDGE_FAILED;
4161 o0nativeformats = c0->nativeformats;
4162 o1nativeformats = c1->nativeformats;
4165 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER")))
4166 pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1->name);
4167 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER")))
4168 pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0->name);
4170 res = ast_generic_bridge(c0, c1, config, fo, rc, nexteventts);
4171 if (res != AST_BRIDGE_RETRY)
4172 break;
4175 ast_clear_flag(c0, AST_FLAG_END_DTMF_ONLY);
4176 ast_clear_flag(c1, AST_FLAG_END_DTMF_ONLY);
4178 /* Now that we have broken the bridge the source will change yet again */
4179 ast_indicate(c0, AST_CONTROL_SRCUPDATE);
4180 ast_indicate(c1, AST_CONTROL_SRCUPDATE);
4182 c0->_bridge = NULL;
4183 c1->_bridge = NULL;
4185 /* \todo XXX here should check that cid_num is not NULL */
4186 manager_event(EVENT_FLAG_CALL, "Unlink",
4187 "Channel1: %s\r\n"
4188 "Channel2: %s\r\n"
4189 "Uniqueid1: %s\r\n"
4190 "Uniqueid2: %s\r\n"
4191 "CallerID1: %s\r\n"
4192 "CallerID2: %s\r\n",
4193 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4194 if (option_debug)
4195 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
4197 return res;
4200 /*! \brief Sets an option on a channel */
4201 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
4203 int res;
4205 if (chan->tech->setoption) {
4206 res = chan->tech->setoption(chan, option, data, datalen);
4207 if (res < 0)
4208 return res;
4209 } else {
4210 errno = ENOSYS;
4211 return -1;
4213 if (block) {
4214 /* XXX Implement blocking -- just wait for our option frame reply, discarding
4215 intermediate packets. XXX */
4216 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
4217 return -1;
4219 return 0;
4222 struct tonepair_def {
4223 int freq1;
4224 int freq2;
4225 int duration;
4226 int vol;
4229 struct tonepair_state {
4230 int fac1;
4231 int fac2;
4232 int v1_1;
4233 int v2_1;
4234 int v3_1;
4235 int v1_2;
4236 int v2_2;
4237 int v3_2;
4238 int origwfmt;
4239 int pos;
4240 int duration;
4241 int modulate;
4242 struct ast_frame f;
4243 unsigned char offset[AST_FRIENDLY_OFFSET];
4244 short data[4000];
4247 static void tonepair_release(struct ast_channel *chan, void *params)
4249 struct tonepair_state *ts = params;
4251 if (chan)
4252 ast_set_write_format(chan, ts->origwfmt);
4253 free(ts);
4256 static void *tonepair_alloc(struct ast_channel *chan, void *params)
4258 struct tonepair_state *ts;
4259 struct tonepair_def *td = params;
4261 if (!(ts = ast_calloc(1, sizeof(*ts))))
4262 return NULL;
4263 ts->origwfmt = chan->writeformat;
4264 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
4265 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
4266 tonepair_release(NULL, ts);
4267 ts = NULL;
4268 } else {
4269 ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
4270 ts->v1_1 = 0;
4271 ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4272 ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4273 ts->v2_1 = 0;
4274 ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
4275 ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4276 ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4277 ts->duration = td->duration;
4278 ts->modulate = 0;
4280 /* Let interrupts interrupt :) */
4281 ast_set_flag(chan, AST_FLAG_WRITE_INT);
4282 return ts;
4285 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
4287 struct tonepair_state *ts = data;
4288 int x;
4290 /* we need to prepare a frame with 16 * timelen samples as we're
4291 * generating SLIN audio
4293 len = samples * 2;
4295 if (len > sizeof(ts->data) / 2 - 1) {
4296 ast_log(LOG_WARNING, "Can't generate that much data!\n");
4297 return -1;
4299 memset(&ts->f, 0, sizeof(ts->f));
4300 for (x=0;x<len/2;x++) {
4301 ts->v1_1 = ts->v2_1;
4302 ts->v2_1 = ts->v3_1;
4303 ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;
4305 ts->v1_2 = ts->v2_2;
4306 ts->v2_2 = ts->v3_2;
4307 ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
4308 if (ts->modulate) {
4309 int p;
4310 p = ts->v3_2 - 32768;
4311 if (p < 0) p = -p;
4312 p = ((p * 9) / 10) + 1;
4313 ts->data[x] = (ts->v3_1 * p) >> 15;
4314 } else
4315 ts->data[x] = ts->v3_1 + ts->v3_2;
4317 ts->f.frametype = AST_FRAME_VOICE;
4318 ts->f.subclass = AST_FORMAT_SLINEAR;
4319 ts->f.datalen = len;
4320 ts->f.samples = samples;
4321 ts->f.offset = AST_FRIENDLY_OFFSET;
4322 ts->f.data = ts->data;
4323 ast_write(chan, &ts->f);
4324 ts->pos += x;
4325 if (ts->duration > 0) {
4326 if (ts->pos >= ts->duration * 8)
4327 return -1;
4329 return 0;
4332 static struct ast_generator tonepair = {
4333 alloc: tonepair_alloc,
4334 release: tonepair_release,
4335 generate: tonepair_generator,
4338 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4340 struct tonepair_def d = { 0, };
4342 d.freq1 = freq1;
4343 d.freq2 = freq2;
4344 d.duration = duration;
4345 d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
4346 if (ast_activate_generator(chan, &tonepair, &d))
4347 return -1;
4348 return 0;
4351 void ast_tonepair_stop(struct ast_channel *chan)
4353 ast_deactivate_generator(chan);
4356 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4358 int res;
4360 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
4361 return res;
4363 /* Give us some wiggle room */
4364 while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
4365 struct ast_frame *f = ast_read(chan);
4366 if (f)
4367 ast_frfree(f);
4368 else
4369 return -1;
4371 return 0;
4374 ast_group_t ast_get_group(const char *s)
4376 char *piece;
4377 char *c;
4378 int start=0, finish=0, x;
4379 ast_group_t group = 0;
4381 if (ast_strlen_zero(s))
4382 return 0;
4384 c = ast_strdupa(s);
4386 while ((piece = strsep(&c, ","))) {
4387 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
4388 /* Range */
4389 } else if (sscanf(piece, "%d", &start)) {
4390 /* Just one */
4391 finish = start;
4392 } else {
4393 ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
4394 continue;
4396 for (x = start; x <= finish; x++) {
4397 if ((x > 63) || (x < 0)) {
4398 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
4399 } else
4400 group |= ((ast_group_t) 1 << x);
4403 return group;
4406 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
4407 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
4408 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
4410 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
4411 void (*stop_ptr)(struct ast_channel *),
4412 void (*cleanup_ptr)(struct ast_channel *))
4414 ast_moh_start_ptr = start_ptr;
4415 ast_moh_stop_ptr = stop_ptr;
4416 ast_moh_cleanup_ptr = cleanup_ptr;
4419 void ast_uninstall_music_functions(void)
4421 ast_moh_start_ptr = NULL;
4422 ast_moh_stop_ptr = NULL;
4423 ast_moh_cleanup_ptr = NULL;
4426 /*! \brief Turn on music on hold on a given channel */
4427 int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
4429 if (ast_moh_start_ptr)
4430 return ast_moh_start_ptr(chan, mclass, interpclass);
4432 if (option_verbose > 2) {
4433 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n",
4434 mclass ? mclass : (interpclass ? interpclass : "default"));
4437 return 0;
4440 /*! \brief Turn off music on hold on a given channel */
4441 void ast_moh_stop(struct ast_channel *chan)
4443 if (ast_moh_stop_ptr)
4444 ast_moh_stop_ptr(chan);
4447 void ast_moh_cleanup(struct ast_channel *chan)
4449 if (ast_moh_cleanup_ptr)
4450 ast_moh_cleanup_ptr(chan);
4453 void ast_channels_init(void)
4455 ast_cli_register_multiple(cli_channel, sizeof(cli_channel) / sizeof(struct ast_cli_entry));
4458 /*! \brief Print call group and pickup group ---*/
4459 char *ast_print_group(char *buf, int buflen, ast_group_t group)
4461 unsigned int i;
4462 int first=1;
4463 char num[3];
4465 buf[0] = '\0';
4467 if (!group) /* Return empty string if no group */
4468 return buf;
4470 for (i = 0; i <= 63; i++) { /* Max group is 63 */
4471 if (group & ((ast_group_t) 1 << i)) {
4472 if (!first) {
4473 strncat(buf, ", ", buflen - strlen(buf) - 1);
4474 } else {
4475 first=0;
4477 snprintf(num, sizeof(num), "%u", i);
4478 strncat(buf, num, buflen - strlen(buf) - 1);
4481 return buf;
4484 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
4486 struct ast_variable *cur;
4488 for (cur = vars; cur; cur = cur->next)
4489 pbx_builtin_setvar_helper(chan, cur->name, cur->value);
4492 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
4494 /* just store the data pointer in the channel structure */
4495 return data;
4498 static void silence_generator_release(struct ast_channel *chan, void *data)
4500 /* nothing to do */
4503 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
4505 short buf[samples];
4506 struct ast_frame frame = {
4507 .frametype = AST_FRAME_VOICE,
4508 .subclass = AST_FORMAT_SLINEAR,
4509 .data = buf,
4510 .samples = samples,
4511 .datalen = sizeof(buf),
4513 memset(buf, 0, sizeof(buf));
4514 if (ast_write(chan, &frame))
4515 return -1;
4516 return 0;
4519 static struct ast_generator silence_generator = {
4520 .alloc = silence_generator_alloc,
4521 .release = silence_generator_release,
4522 .generate = silence_generator_generate,
4525 struct ast_silence_generator {
4526 int old_write_format;
4529 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
4531 struct ast_silence_generator *state;
4533 if (!(state = ast_calloc(1, sizeof(*state)))) {
4534 return NULL;
4537 state->old_write_format = chan->writeformat;
4539 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
4540 ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
4541 free(state);
4542 return NULL;
4545 ast_activate_generator(chan, &silence_generator, state);
4547 if (option_debug)
4548 ast_log(LOG_DEBUG, "Started silence generator on '%s'\n", chan->name);
4550 return state;
4553 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
4555 if (!state)
4556 return;
4558 ast_deactivate_generator(chan);
4560 if (option_debug)
4561 ast_log(LOG_DEBUG, "Stopped silence generator on '%s'\n", chan->name);
4563 if (ast_set_write_format(chan, state->old_write_format) < 0)
4564 ast_log(LOG_ERROR, "Could not return write format to its original state\n");
4566 free(state);
4570 int ast_send_message(const char *type, void *data, char *to, char *from, char *message, int ispdu) {
4571 struct ast_channel *chan = NULL;
4572 int status;
4573 int res = -1;
4575 chan = ast_request(type, AST_FORMAT_SLINEAR, data, &status);
4576 if (chan) {
4577 if (from) {
4578 ast_set_callerid(chan, from, from, from);
4580 res = ast_sendmessage(chan, to, message, ispdu);
4581 /* XXX what about message CDRs ??? XXX */
4582 ast_hangup(chan);
4583 return res;
4586 return res;
4589 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
4590 const char *channelreloadreason2txt(enum channelreloadreason reason)
4592 switch (reason) {
4593 case CHANNEL_MODULE_LOAD:
4594 return "LOAD (Channel module load)";
4596 case CHANNEL_MODULE_RELOAD:
4597 return "RELOAD (Channel module reload)";
4599 case CHANNEL_CLI_RELOAD:
4600 return "CLIRELOAD (Channel module reload by CLI command)";
4602 default:
4603 return "MANAGERRELOAD (Channel module reload by manager)";
4607 #ifdef DEBUG_CHANNEL_LOCKS
4609 /*! \brief Unlock AST channel (and print debugging output)
4610 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
4612 int __ast_channel_unlock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
4614 int res = 0;
4615 if (option_debug > 2)
4616 ast_log(LOG_DEBUG, "::::==== Unlocking AST channel %s\n", chan->name);
4618 if (!chan) {
4619 if (option_debug)
4620 ast_log(LOG_DEBUG, "::::==== Unlocking non-existing channel \n");
4621 return 0;
4623 #ifdef DEBUG_THREADS
4624 res = __ast_pthread_mutex_unlock(filename, lineno, func, "(channel lock)", &chan->lock);
4625 #else
4626 res = ast_mutex_unlock(&chan->lock);
4627 #endif
4629 if (option_debug > 2) {
4630 #ifdef DEBUG_THREADS
4631 int count = 0;
4632 if ((count = chan->lock.reentrancy))
4633 ast_log(LOG_DEBUG, ":::=== Still have %d locks (recursive)\n", count);
4634 #endif
4635 if (!res)
4636 if (option_debug)
4637 ast_log(LOG_DEBUG, "::::==== Channel %s was unlocked\n", chan->name);
4638 if (res == EINVAL) {
4639 if (option_debug)
4640 ast_log(LOG_DEBUG, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan->name);
4643 if (res == EPERM) {
4644 /* We had no lock, so okay any way*/
4645 if (option_debug > 3)
4646 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked at all \n", chan->name);
4647 res = 0;
4649 return res;
4652 /*! \brief Lock AST channel (and print debugging output)
4653 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4654 int __ast_channel_lock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
4656 int res;
4658 if (option_debug > 3)
4659 ast_log(LOG_DEBUG, "====:::: Locking AST channel %s\n", chan->name);
4661 #ifdef DEBUG_THREADS
4662 res = __ast_pthread_mutex_lock(filename, lineno, func, "(channel lock)", &chan->lock);
4663 #else
4664 res = ast_mutex_lock(&chan->lock);
4665 #endif
4667 if (option_debug > 3) {
4668 #ifdef DEBUG_THREADS
4669 int count = 0;
4670 if ((count = chan->lock.reentrancy))
4671 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4672 #endif
4673 if (!res)
4674 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4675 if (res == EDEADLK) {
4676 /* We had no lock, so okey any way */
4677 if (option_debug > 3)
4678 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan->name);
4680 if (res == EINVAL) {
4681 if (option_debug > 3)
4682 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4685 return res;
4688 /*! \brief Lock AST channel (and print debugging output)
4689 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4690 int __ast_channel_trylock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
4692 int res;
4694 if (option_debug > 2)
4695 ast_log(LOG_DEBUG, "====:::: Trying to lock AST channel %s\n", chan->name);
4696 #ifdef DEBUG_THREADS
4697 res = __ast_pthread_mutex_trylock(filename, lineno, func, "(channel lock)", &chan->lock);
4698 #else
4699 res = ast_mutex_trylock(&chan->lock);
4700 #endif
4702 if (option_debug > 2) {
4703 #ifdef DEBUG_THREADS
4704 int count = 0;
4705 if ((count = chan->lock.reentrancy))
4706 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4707 #endif
4708 if (!res)
4709 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4710 if (res == EBUSY) {
4711 /* We failed to lock */
4712 if (option_debug > 2)
4713 ast_log(LOG_DEBUG, "::::==== Channel %s failed to lock. Not waiting around...\n", chan->name);
4715 if (res == EDEADLK) {
4716 /* We had no lock, so okey any way*/
4717 if (option_debug > 2)
4718 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan->name);
4720 if (res == EINVAL && option_debug > 2)
4721 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4723 return res;
4726 #endif
4729 * Wrappers for various ast_say_*() functions that call the full version
4730 * of the same functions.
4731 * The proper place would be say.c, but that file is optional and one
4732 * must be able to build asterisk even without it (using a loadable 'say'
4733 * implementation that only supplies the 'full' version of the functions.
4736 int ast_say_number(struct ast_channel *chan, int num,
4737 const char *ints, const char *language, const char *options)
4739 return ast_say_number_full(chan, num, ints, language, options, -1, -1);
4742 int ast_say_enumeration(struct ast_channel *chan, int num,
4743 const char *ints, const char *language, const char *options)
4745 return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
4748 int ast_say_digits(struct ast_channel *chan, int num,
4749 const char *ints, const char *lang)
4751 return ast_say_digits_full(chan, num, ints, lang, -1, -1);
4754 int ast_say_digit_str(struct ast_channel *chan, const char *str,
4755 const char *ints, const char *lang)
4757 return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
4760 int ast_say_character_str(struct ast_channel *chan, const char *str,
4761 const char *ints, const char *lang)
4763 return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
4766 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
4767 const char *ints, const char *lang)
4769 return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
4772 int ast_say_digits_full(struct ast_channel *chan, int num,
4773 const char *ints, const char *lang, int audiofd, int ctrlfd)
4775 char buf[256];
4777 snprintf(buf, sizeof(buf), "%d", num);
4778 return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);