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.
21 * \brief Channel Management
23 * \author Mark Spencer <markster@digium.com>
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40 #include "asterisk/zapata.h"
42 #include "asterisk/pbx.h"
43 #include "asterisk/frame.h"
44 #include "asterisk/sched.h"
45 #include "asterisk/options.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/chanspy.h"
48 #include "asterisk/musiconhold.h"
49 #include "asterisk/logger.h"
50 #include "asterisk/say.h"
51 #include "asterisk/file.h"
52 #include "asterisk/cli.h"
53 #include "asterisk/translate.h"
54 #include "asterisk/manager.h"
55 #include "asterisk/chanvars.h"
56 #include "asterisk/linkedlists.h"
57 #include "asterisk/indications.h"
58 #include "asterisk/monitor.h"
59 #include "asterisk/causes.h"
60 #include "asterisk/callerid.h"
61 #include "asterisk/utils.h"
62 #include "asterisk/lock.h"
63 #include "asterisk/app.h"
64 #include "asterisk/transcap.h"
65 #include "asterisk/devicestate.h"
66 #include "asterisk/sha1.h"
67 #include "asterisk/threadstorage.h"
68 #include "asterisk/slinfactory.h"
70 struct channel_spy_trans {
72 struct ast_trans_pvt *path;
75 /*! \brief List of SPY structures
77 struct ast_channel_spy_list {
78 struct channel_spy_trans read_translator;
79 struct channel_spy_trans write_translator;
80 AST_LIST_HEAD_NOLOCK(, ast_channel_spy) list;
83 /*! \brief Definition of the Whisper buffer */
84 struct ast_channel_whisper_buffer {
86 struct ast_slinfactory sf;
87 unsigned int original_format;
88 struct ast_trans_pvt *path;
91 /* uncomment if you have problems with 'monitoring' synchronized files */
93 #define MONITOR_CONSTANT_DELAY
94 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
97 /*! \brief Prevent new channel allocation if shutting down. */
98 static int shutting_down;
100 static int uniqueint;
102 unsigned long global_fin, global_fout;
104 AST_THREADSTORAGE(state2str_threadbuf);
105 #define STATE2STR_BUFSIZE 32
107 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100 /*!< 100ms */
109 /*! \brief List of channel drivers */
111 const struct ast_channel_tech *tech;
112 AST_LIST_ENTRY(chanlist) list;
115 /*! \brief the list of registered channel types */
116 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
118 /*! \brief the list of channels we have. Note that the lock for this list is used for
119 both the channels list and the backends list. */
120 static AST_LIST_HEAD_STATIC(channels, ast_channel);
122 /*! \brief map AST_CAUSE's to readable string representations
126 const struct ast_cause {
131 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
132 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
133 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
134 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
135 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
136 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
137 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
138 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
139 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
140 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
141 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
142 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
143 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
144 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
145 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
146 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
147 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
148 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
149 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
150 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
151 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
152 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
153 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
154 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
155 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
156 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
157 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
158 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
159 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
160 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
161 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
162 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
163 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
164 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
165 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
166 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
167 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
168 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
169 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
170 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
171 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
172 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
173 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
174 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
177 struct ast_variable *ast_channeltype_list(void)
180 struct ast_variable *var=NULL, *prev = NULL;
181 AST_LIST_TRAVERSE(&backends, cl, list) {
183 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description)))
186 var = ast_variable_new(cl->tech->type, cl->tech->description);
193 /*! \brief Show channel types - CLI command */
194 static int show_channeltypes(int fd, int argc, char *argv[])
196 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
200 ast_cli(fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
201 ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
202 if (AST_LIST_LOCK(&channels)) {
203 ast_log(LOG_WARNING, "Unable to lock channel list\n");
206 AST_LIST_TRAVERSE(&backends, cl, list) {
207 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description,
208 (cl->tech->devicestate) ? "yes" : "no",
209 (cl->tech->indicate) ? "yes" : "no",
210 (cl->tech->transfer) ? "yes" : "no");
213 AST_LIST_UNLOCK(&channels);
214 ast_cli(fd, "----------\n%d channel drivers registered.\n", count_chan);
215 return RESULT_SUCCESS;
221 /*! \brief Show details about a channel driver - CLI command */
222 static int show_channeltype(int fd, int argc, char *argv[])
224 struct chanlist *cl = NULL;
227 return RESULT_SHOWUSAGE;
229 if (AST_LIST_LOCK(&channels)) {
230 ast_log(LOG_WARNING, "Unable to lock channel list\n");
231 return RESULT_FAILURE;
234 AST_LIST_TRAVERSE(&backends, cl, list) {
235 if (!strncasecmp(cl->tech->type, argv[3], strlen(cl->tech->type))) {
242 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[3]);
243 AST_LIST_UNLOCK(&channels);
244 return RESULT_FAILURE;
248 "-- Info about channel driver: %s --\n"
249 " Device State: %s\n"
252 " Capabilities: %d\n"
256 " Image Support: %s\n"
257 " Text Support: %s\n",
259 (cl->tech->devicestate) ? "yes" : "no",
260 (cl->tech->indicate) ? "yes" : "no",
261 (cl->tech->transfer) ? "yes" : "no",
262 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
263 (cl->tech->send_digit_begin) ? "yes" : "no",
264 (cl->tech->send_digit_end) ? "yes" : "no",
265 (cl->tech->send_html) ? "yes" : "no",
266 (cl->tech->send_image) ? "yes" : "no",
267 (cl->tech->send_text) ? "yes" : "no"
271 AST_LIST_UNLOCK(&channels);
272 return RESULT_SUCCESS;
275 static char *complete_channeltypes(const char *line, const char *word, int pos, int state)
285 wordlen = strlen(word);
287 AST_LIST_TRAVERSE(&backends, cl, list) {
288 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
289 ret = strdup(cl->tech->type);
297 static const char show_channeltypes_usage[] =
298 "Usage: core show channeltypes\n"
299 " Lists available channel types registered in your Asterisk server.\n";
301 static const char show_channeltype_usage[] =
302 "Usage: core show channeltype <name>\n"
303 " Show details about the specified channel type, <name>.\n";
305 static struct ast_cli_entry cli_channel[] = {
306 { { "core", "show", "channeltypes", NULL },
307 show_channeltypes, "List available channel types",
308 show_channeltypes_usage },
310 { { "core", "show", "channeltype", NULL },
311 show_channeltype, "Give more details on that channel type",
312 show_channeltype_usage, complete_channeltypes },
315 /*! \brief Checks to see if a channel is needing hang up */
316 int ast_check_hangup(struct ast_channel *chan)
318 if (chan->_softhangup) /* yes if soft hangup flag set */
320 if (!chan->tech_pvt) /* yes if no technology private data */
322 if (!chan->whentohangup) /* no if no hangup scheduled */
324 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
326 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
330 static int ast_check_hangup_locked(struct ast_channel *chan)
333 ast_channel_lock(chan);
334 res = ast_check_hangup(chan);
335 ast_channel_unlock(chan);
339 /*! \brief Initiate system shutdown */
340 void ast_begin_shutdown(int hangup)
342 struct ast_channel *c;
345 AST_LIST_LOCK(&channels);
346 AST_LIST_TRAVERSE(&channels, c, chan_list)
347 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
348 AST_LIST_UNLOCK(&channels);
352 /*! \brief returns number of active/allocated channels */
353 int ast_active_channels(void)
355 struct ast_channel *c;
357 AST_LIST_LOCK(&channels);
358 AST_LIST_TRAVERSE(&channels, c, chan_list)
360 AST_LIST_UNLOCK(&channels);
364 /*! \brief Cancel a shutdown in progress */
365 void ast_cancel_shutdown(void)
370 /*! \brief Returns non-zero if Asterisk is being shut down */
371 int ast_shutting_down(void)
373 return shutting_down;
376 /*! \brief Set when to hangup channel */
377 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
379 chan->whentohangup = offset ? time(NULL) + offset : 0;
380 ast_queue_frame(chan, &ast_null_frame);
384 /*! \brief Compare a offset with when to hangup channel */
385 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
389 if (chan->whentohangup == 0) {
390 return (offset == 0) ? 0 : -1;
392 if (offset == 0) /* XXX why is this special ? */
395 whentohangup = offset + time (NULL);
396 if (chan->whentohangup < whentohangup)
398 else if (chan->whentohangup == whentohangup)
406 /*! \brief Register a new telephony channel in Asterisk */
407 int ast_channel_register(const struct ast_channel_tech *tech)
409 struct chanlist *chan;
411 AST_LIST_LOCK(&channels);
413 AST_LIST_TRAVERSE(&backends, chan, list) {
414 if (!strcasecmp(tech->type, chan->tech->type)) {
415 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
416 AST_LIST_UNLOCK(&channels);
421 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
422 AST_LIST_UNLOCK(&channels);
426 AST_LIST_INSERT_HEAD(&backends, chan, list);
429 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
431 if (option_verbose > 1)
432 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
433 chan->tech->description);
435 AST_LIST_UNLOCK(&channels);
439 /*! \brief Unregister channel driver */
440 void ast_channel_unregister(const struct ast_channel_tech *tech)
442 struct chanlist *chan;
445 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
447 AST_LIST_LOCK(&channels);
449 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
450 if (chan->tech == tech) {
451 AST_LIST_REMOVE_CURRENT(&backends, list);
453 if (option_verbose > 1)
454 ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
458 AST_LIST_TRAVERSE_SAFE_END
460 AST_LIST_UNLOCK(&channels);
463 /*! \brief Get handle to channel driver based on name */
464 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
466 struct chanlist *chanls;
467 const struct ast_channel_tech *ret = NULL;
469 if (AST_LIST_LOCK(&channels)) {
470 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
474 AST_LIST_TRAVERSE(&backends, chanls, list) {
475 if (!strcasecmp(name, chanls->tech->type)) {
481 AST_LIST_UNLOCK(&channels);
486 /*! \brief Gives the string form of a given hangup cause */
487 const char *ast_cause2str(int cause)
491 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
492 if (causes[x].cause == cause)
493 return causes[x].desc;
499 /*! \brief Convert a symbolic hangup cause to number */
500 int ast_str2cause(const char *name)
504 for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
505 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
506 return causes[x].cause;
511 /*! \brief Gives the string form of a given channel state.
512 \note This function is not reentrant.
514 const char *ast_state2str(enum ast_channel_state state)
521 case AST_STATE_RESERVED:
523 case AST_STATE_OFFHOOK:
525 case AST_STATE_DIALING:
529 case AST_STATE_RINGING:
535 case AST_STATE_DIALING_OFFHOOK:
536 return "Dialing Offhook";
537 case AST_STATE_PRERING:
540 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
542 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
547 /*! \brief Gives the string form of a given transfer capability */
548 char *ast_transfercapability2str(int transfercapability)
550 switch (transfercapability) {
551 case AST_TRANS_CAP_SPEECH:
553 case AST_TRANS_CAP_DIGITAL:
555 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
556 return "RESTRICTED_DIGITAL";
557 case AST_TRANS_CAP_3_1K_AUDIO:
559 case AST_TRANS_CAP_DIGITAL_W_TONES:
560 return "DIGITAL_W_TONES";
561 case AST_TRANS_CAP_VIDEO:
568 /*! \brief Pick the best audio codec */
569 int ast_best_codec(int fmts)
571 /* This just our opinion, expressed in code. We are asked to choose
572 the best codec to use, given no information */
576 /*! Okay, ulaw is used by all telephony equipment, so start with it */
578 /*! Unless of course, you're a silly European, so then prefer ALAW */
580 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
582 /*! Okay, well, signed linear is easy to translate into other stuff */
584 /*! G.726 is standard ADPCM, in RFC3551 packing order */
586 /*! G.726 is standard ADPCM, in AAL2 packing order */
587 AST_FORMAT_G726_AAL2,
588 /*! ADPCM has great sound quality and is still pretty easy to translate */
590 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
591 translate and sounds pretty good */
593 /*! iLBC is not too bad */
595 /*! Speex is free, but computationally more expensive than GSM */
597 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
600 /*! G.729a is faster than 723 and slightly less expensive */
602 /*! Down to G.723.1 which is proprietary but at least designed for voice */
606 /* Strip out video */
607 fmts &= AST_FORMAT_AUDIO_MASK;
609 /* Find the first preferred codec in the format given */
610 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
613 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
617 static const struct ast_channel_tech null_tech = {
619 .description = "Null channel (should not see this)",
622 /*! \brief Create a new channel structure */
623 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num, const char *cid_name, const char *name_fmt, ...)
625 struct ast_channel *tmp;
628 struct varshead *headp;
631 /* If shutting down, don't allocate any new channels */
633 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
637 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
640 if (!(tmp->sched = sched_context_create())) {
641 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
646 ast_string_field_init(tmp, 128);
648 /* Don't bother initializing the last two FD here, because they
649 will *always* be set just a few lines down (AST_TIMING_FD,
651 for (x = 0; x < AST_MAX_FDS - 2; x++)
655 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
656 if (tmp->timingfd > -1) {
657 /* Check if timing interface supports new
660 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
668 if (pipe(tmp->alertpipe)) {
669 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
670 ast_string_field_free_pools(tmp);
674 flags = fcntl(tmp->alertpipe[0], F_GETFL);
675 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
676 flags = fcntl(tmp->alertpipe[1], F_GETFL);
677 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
679 } else /* Make sure we've got it done right if they don't */
680 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
682 /* Always watch the alertpipe */
683 tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
684 /* And timing pipe */
685 tmp->fds[AST_TIMING_FD] = tmp->timingfd;
686 ast_string_field_set(tmp, name, "**Unknown**");
693 tmp->fin = global_fin;
694 tmp->fout = global_fout;
696 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
697 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
698 ast_atomic_fetchadd_int(&uniqueint, 1));
700 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
701 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
704 if (!ast_strlen_zero(name_fmt)) {
705 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
706 * And they all use slightly different formats for their name string.
707 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
708 * This means, that the stringfields must have a routine that takes the va_lists directly, and
709 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
710 * This new function was written so this can be accomplished.
712 va_start(ap1, name_fmt);
713 va_start(ap2, name_fmt);
714 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
718 /* and now, since the channel structure is built, and has its name, let's call the
719 * manager event generator with this Newchannel event. This is the proper and correct
720 * place to make this call, but you sure do have to pass a lot of data into this func
723 manager_event(EVENT_FLAG_CALL, "Newchannel",
726 "CallerIDNum: %s\r\n"
727 "CallerIDName: %s\r\n"
729 tmp->name, ast_state2str(state),
730 S_OR(cid_num, "<unknown>"),
731 S_OR(cid_name, "<unknown>"),
735 headp = &tmp->varshead;
736 AST_LIST_HEAD_INIT_NOLOCK(headp);
738 ast_mutex_init(&tmp->lock);
740 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
742 strcpy(tmp->context, "default");
743 strcpy(tmp->exten, "s");
746 ast_string_field_set(tmp, language, defaultlanguage);
747 tmp->amaflags = ast_default_amaflags;
748 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
750 tmp->tech = &null_tech;
752 AST_LIST_LOCK(&channels);
753 AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
754 AST_LIST_UNLOCK(&channels);
759 /*! \brief Queue an outgoing media frame */
760 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
763 struct ast_frame *cur;
767 /* Build us a copy and free the original one */
768 if (!(f = ast_frdup(fin))) {
769 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
772 ast_channel_lock(chan);
774 /* See if the last frame on the queue is a hangup, if so don't queue anything */
775 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
777 ast_channel_unlock(chan);
781 /* Count how many frames exist on the queue */
782 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
786 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
787 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
788 if (fin->frametype != AST_FRAME_VOICE) {
789 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
793 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
795 ast_channel_unlock(chan);
799 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
800 if (chan->alertpipe[1] > -1) {
801 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
802 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
803 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
805 } else if (chan->timingfd > -1) {
806 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
808 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
809 pthread_kill(chan->blocker, SIGURG);
811 ast_channel_unlock(chan);
815 /*! \brief Queue a hangup frame for channel */
816 int ast_queue_hangup(struct ast_channel *chan)
818 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
819 /* Yeah, let's not change a lock-critical value without locking */
820 if (!ast_channel_trylock(chan)) {
821 chan->_softhangup |= AST_SOFTHANGUP_DEV;
822 ast_channel_unlock(chan);
824 return ast_queue_frame(chan, &f);
827 /*! \brief Queue a control frame */
828 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
830 struct ast_frame f = { AST_FRAME_CONTROL, };
832 f.subclass = control;
834 return ast_queue_frame(chan, &f);
837 /*! \brief Queue a control frame with payload */
838 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
839 const void *data, size_t datalen)
841 struct ast_frame f = { AST_FRAME_CONTROL, };
843 f.subclass = control;
844 f.data = (void *) data;
847 return ast_queue_frame(chan, &f);
850 /*! \brief Set defer DTMF flag on channel */
851 int ast_channel_defer_dtmf(struct ast_channel *chan)
856 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
857 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
862 /*! \brief Unset defer DTMF flag on channel */
863 void ast_channel_undefer_dtmf(struct ast_channel *chan)
866 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
870 * \brief Helper function to find channels.
872 * It supports these modes:
874 * prev != NULL : get channel next in list after prev
875 * name != NULL : get channel with matching name
876 * name != NULL && namelen != 0 : get channel whose name starts with prefix
877 * exten != NULL : get channel whose exten or macroexten matches
878 * context != NULL && exten != NULL : get channel whose context or macrocontext
880 * It returns with the channel's lock held. If getting the individual lock fails,
881 * unlock and retry quickly up to 10 times, then give up.
883 * \note XXX Note that this code has cost O(N) because of the need to verify
884 * that the object is still on the global list.
886 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
887 * can only be done with the lock held or someone could delete the
888 * object while we work on it. This causes some ugliness in the code.
889 * Note that removing the first ast_log() may be harmful, as it would
890 * shorten the retry period and possibly cause failures.
891 * We should definitely go for a better scheme that is deadlock-free.
893 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
894 const char *name, const int namelen,
895 const char *context, const char *exten)
897 const char *msg = prev ? "deadlock" : "initial deadlock";
899 struct ast_channel *c;
901 for (retries = 0; retries < 10; retries++) {
903 AST_LIST_LOCK(&channels);
904 AST_LIST_TRAVERSE(&channels, c, chan_list) {
905 if (prev) { /* look for next item */
906 if (c != prev) /* not this one */
908 /* found, prepare to return c->next */
909 c = AST_LIST_NEXT(c, chan_list);
911 if (name) { /* want match by name */
912 if ((!namelen && strcasecmp(c->name, name)) ||
913 (namelen && strncasecmp(c->name, name, namelen)))
914 continue; /* name match failed */
916 if (context && strcasecmp(c->context, context) &&
917 strcasecmp(c->macrocontext, context))
918 continue; /* context match failed */
919 if (strcasecmp(c->exten, exten) &&
920 strcasecmp(c->macroexten, exten))
921 continue; /* exten match failed */
923 /* if we get here, c points to the desired record */
926 /* exit if chan not found or mutex acquired successfully */
927 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
928 done = c == NULL || ast_channel_trylock(c) == 0;
931 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
933 AST_LIST_UNLOCK(&channels);
936 usleep(1); /* give other threads a chance before retrying */
939 * c is surely not null, but we don't have the lock so cannot
943 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n",
949 /*! \brief Browse channels in use */
950 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
952 return channel_find_locked(prev, NULL, 0, NULL, NULL);
955 /*! \brief Get channel by name and lock it */
956 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
958 return channel_find_locked(NULL, name, 0, NULL, NULL);
961 /*! \brief Get channel by name prefix and lock it */
962 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
964 return channel_find_locked(NULL, name, namelen, NULL, NULL);
967 /*! \brief Get next channel by name prefix and lock it */
968 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
971 return channel_find_locked(chan, name, namelen, NULL, NULL);
974 /*! \brief Get channel by exten (and optionally context) and lock it */
975 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
977 return channel_find_locked(NULL, NULL, 0, context, exten);
980 /*! \brief Get next channel by exten (and optionally context) and lock it */
981 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
984 return channel_find_locked(chan, NULL, 0, context, exten);
987 /*! \brief Wait, look for hangups and condition arg */
988 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
993 if (cond && ((*cond)(data) == 0))
995 ms = ast_waitfor(chan, ms);
1008 /*! \brief Wait, look for hangups */
1009 int ast_safe_sleep(struct ast_channel *chan, int ms)
1011 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1014 static void free_cid(struct ast_callerid *cid)
1017 free(cid->cid_dnid);
1021 free(cid->cid_name);
1025 free(cid->cid_rdnis);
1026 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1029 /*! \brief Free a channel structure */
1030 void ast_channel_free(struct ast_channel *chan)
1033 struct ast_var_t *vardata;
1034 struct ast_frame *f;
1035 struct varshead *headp;
1036 struct ast_datastore *datastore = NULL;
1037 char name[AST_CHANNEL_NAME];
1039 headp=&chan->varshead;
1041 AST_LIST_LOCK(&channels);
1042 AST_LIST_REMOVE(&channels, chan, chan_list);
1043 /* Lock and unlock the channel just to be sure nobody
1044 has it locked still */
1045 ast_channel_lock(chan);
1046 ast_channel_unlock(chan);
1047 if (chan->tech_pvt) {
1048 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1049 free(chan->tech_pvt);
1053 sched_context_destroy(chan->sched);
1055 ast_copy_string(name, chan->name, sizeof(name));
1057 /* Stop monitoring */
1059 chan->monitor->stop( chan, 0 );
1061 /* If there is native format music-on-hold state, free it */
1062 if (chan->music_state)
1063 ast_moh_cleanup(chan);
1065 /* if someone is whispering on the channel, stop them */
1067 ast_channel_whisper_stop(chan);
1069 /* Free translators */
1070 if (chan->readtrans)
1071 ast_translator_free_path(chan->readtrans);
1072 if (chan->writetrans)
1073 ast_translator_free_path(chan->writetrans);
1075 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1076 free_cid(&chan->cid);
1077 ast_mutex_destroy(&chan->lock);
1078 /* Close pipes if appropriate */
1079 if ((fd = chan->alertpipe[0]) > -1)
1081 if ((fd = chan->alertpipe[1]) > -1)
1083 if ((fd = chan->timingfd) > -1)
1085 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1088 /* Get rid of each of the data stores on the channel */
1089 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1090 /* Free the data store */
1091 ast_channel_datastore_free(datastore);
1092 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1094 /* loop over the variables list, freeing all data and deleting list items */
1095 /* no need to lock the list, as the channel is already locked */
1097 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1098 ast_var_delete(vardata);
1100 /* Destroy the jitterbuffer */
1101 ast_jb_destroy(chan);
1103 ast_string_field_free_pools(chan);
1105 AST_LIST_UNLOCK(&channels);
1107 ast_device_state_changed_literal(name);
1110 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1112 struct ast_datastore *datastore = NULL;
1114 /* Make sure we at least have type so we can identify this */
1119 /* Allocate memory for datastore and clear it */
1120 datastore = ast_calloc(1, sizeof(*datastore));
1121 if (datastore == NULL) {
1125 datastore->info = info;
1127 datastore->uid = ast_strdup(uid);
1132 int ast_channel_datastore_free(struct ast_datastore *datastore)
1136 /* Using the destroy function (if present) destroy the data */
1137 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1138 datastore->info->destroy(datastore->data);
1139 datastore->data = NULL;
1142 /* Free allocated UID memory */
1143 if (datastore->uid != NULL) {
1144 free(datastore->uid);
1145 datastore->uid = NULL;
1148 /* Finally free memory used by ourselves */
1154 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1158 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1163 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1165 struct ast_datastore *datastore2 = NULL;
1168 /* Find our position and remove ourselves */
1169 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1170 if (datastore2 == datastore) {
1171 AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1176 AST_LIST_TRAVERSE_SAFE_END
1181 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1183 struct ast_datastore *datastore = NULL;
1188 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1189 if (datastore->info == info) {
1190 if (uid != NULL && datastore->uid != NULL) {
1191 if (!strcasecmp(uid, datastore->uid)) {
1192 /* Matched by type AND uid */
1196 /* Matched by type at least */
1201 AST_LIST_TRAVERSE_SAFE_END
1206 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1208 /* Link the owner channel to the spy */
1211 if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1212 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1213 spy->type, chan->name);
1217 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1218 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1219 ast_getformatname(spy->read_queue.format));
1223 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1224 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1225 ast_getformatname(spy->write_queue.format));
1229 if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1230 ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1231 (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1232 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1233 ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1238 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1242 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1243 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1245 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1248 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1249 ast_cond_init(&spy->trigger, NULL);
1250 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1251 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1255 ast_log(LOG_DEBUG, "Spy %s added to channel %s\n",
1256 spy->type, chan->name);
1261 /* Clean up a channel's spy information */
1262 static void spy_cleanup(struct ast_channel *chan)
1264 if (!AST_LIST_EMPTY(&chan->spies->list))
1266 if (chan->spies->read_translator.path)
1267 ast_translator_free_path(chan->spies->read_translator.path);
1268 if (chan->spies->write_translator.path)
1269 ast_translator_free_path(chan->spies->write_translator.path);
1275 /* Detach a spy from it's channel */
1276 static void spy_detach(struct ast_channel_spy *spy, struct ast_channel *chan)
1278 ast_mutex_lock(&spy->lock);
1280 /* We only need to poke them if they aren't already done */
1281 if (spy->status != CHANSPY_DONE) {
1282 /* Indicate to the spy to stop */
1283 spy->status = CHANSPY_STOP;
1285 /* Poke the spy if needed */
1286 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1287 ast_cond_signal(&spy->trigger);
1290 /* Print it out while we still have a lock so the structure can't go away (if signalled above) */
1292 ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n", spy->type, chan->name);
1294 ast_mutex_unlock(&spy->lock);
1299 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1301 struct ast_channel_spy *spy = NULL;
1306 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1307 ast_mutex_lock(&spy->lock);
1308 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1309 ast_mutex_unlock(&spy->lock);
1310 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1311 spy_detach(spy, chan);
1313 ast_mutex_unlock(&spy->lock);
1315 AST_LIST_TRAVERSE_SAFE_END
1319 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1324 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1325 ts.tv_sec = tv.tv_sec;
1326 ts.tv_nsec = tv.tv_usec * 1000;
1328 ast_cond_timedwait(&spy->trigger, &spy->lock, &ts);
1331 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1336 AST_LIST_REMOVE(&chan->spies->list, spy, list);
1337 spy_detach(spy, chan);
1341 void ast_channel_spy_free(struct ast_channel_spy *spy)
1343 struct ast_frame *f = NULL;
1345 if (spy->status == CHANSPY_DONE)
1348 /* Switch status to done in case we get called twice */
1349 spy->status = CHANSPY_DONE;
1351 /* Drop any frames in the queue */
1352 while ((f = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list)))
1354 while ((f = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list)))
1357 /* Destroy the condition if in use */
1358 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1359 ast_cond_destroy(&spy->trigger);
1361 /* Destroy our mutex since it is no longer in use */
1362 ast_mutex_destroy(&spy->lock);
1367 static void detach_spies(struct ast_channel *chan)
1369 struct ast_channel_spy *spy = NULL;
1374 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1375 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1376 spy_detach(spy, chan);
1378 AST_LIST_TRAVERSE_SAFE_END
1383 /*! \brief Softly hangup a channel, don't lock */
1384 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1387 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1388 /* Inform channel driver that we need to be hung up, if it cares */
1389 chan->_softhangup |= cause;
1390 ast_queue_frame(chan, &ast_null_frame);
1391 /* Interrupt any poll call or such */
1392 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1393 pthread_kill(chan->blocker, SIGURG);
1397 /*! \brief Softly hangup a channel, lock */
1398 int ast_softhangup(struct ast_channel *chan, int cause)
1401 ast_channel_lock(chan);
1402 res = ast_softhangup_nolock(chan, cause);
1403 ast_channel_unlock(chan);
1407 enum spy_direction {
1412 #define SPY_QUEUE_SAMPLE_LIMIT 4000 /* half of one second */
1414 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1416 struct ast_frame *translated_frame = NULL;
1417 struct ast_channel_spy *spy;
1418 struct channel_spy_trans *trans;
1420 trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1422 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1423 struct ast_channel_spy_queue *queue;
1424 struct ast_frame *duped_fr;
1426 ast_mutex_lock(&spy->lock);
1428 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1430 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1431 if (!translated_frame) {
1432 if (trans->path && (trans->last_format != f->subclass)) {
1433 ast_translator_free_path(trans->path);
1438 ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1439 ast_getformatname(f->subclass), chan->name);
1440 if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1441 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1442 ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1443 ast_mutex_unlock(&spy->lock);
1446 trans->last_format = f->subclass;
1449 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1450 ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1451 ast_getformatname(AST_FORMAT_SLINEAR));
1452 ast_mutex_unlock(&spy->lock);
1456 duped_fr = ast_frdup(translated_frame);
1457 } else if (f->subclass != queue->format) {
1458 ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1459 spy->type, chan->name,
1460 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1461 ast_mutex_unlock(&spy->lock);
1464 duped_fr = ast_frdup(f);
1466 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1468 queue->samples += f->samples;
1470 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1471 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1472 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1473 case CHANSPY_TRIGGER_READ:
1474 if (dir == SPY_WRITE) {
1475 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1476 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1478 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1479 spy->type, chan->name);
1482 case CHANSPY_TRIGGER_WRITE:
1483 if (dir == SPY_READ) {
1484 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1485 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1487 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1488 spy->type, chan->name);
1493 ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1494 spy->type, chan->name);
1495 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1496 ast_cond_signal(&spy->trigger);
1499 ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1500 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1501 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1502 struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1503 queue->samples -= drop->samples;
1508 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1509 case CHANSPY_TRIGGER_READ:
1510 if (dir == SPY_READ)
1511 ast_cond_signal(&spy->trigger);
1513 case CHANSPY_TRIGGER_WRITE:
1514 if (dir == SPY_WRITE)
1515 ast_cond_signal(&spy->trigger);
1520 ast_mutex_unlock(&spy->lock);
1523 if (translated_frame)
1524 ast_frfree(translated_frame);
1527 static void free_translation(struct ast_channel *clone)
1529 if (clone->writetrans)
1530 ast_translator_free_path(clone->writetrans);
1531 if (clone->readtrans)
1532 ast_translator_free_path(clone->readtrans);
1533 clone->writetrans = NULL;
1534 clone->readtrans = NULL;
1535 clone->rawwriteformat = clone->nativeformats;
1536 clone->rawreadformat = clone->nativeformats;
1539 /*! \brief Hangup a channel */
1540 int ast_hangup(struct ast_channel *chan)
1544 /* Don't actually hang up a channel that will masquerade as someone else, or
1545 if someone is going to masquerade as us */
1546 ast_channel_lock(chan);
1548 detach_spies(chan); /* get rid of spies */
1551 if (ast_do_masquerade(chan))
1552 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1556 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1557 ast_channel_unlock(chan);
1560 /* If this channel is one which will be masqueraded into something,
1561 mark it as a zombie already, so we know to free it later */
1563 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1564 ast_channel_unlock(chan);
1567 free_translation(chan);
1568 /* Close audio stream */
1570 ast_closestream(chan->stream);
1571 chan->stream = NULL;
1573 /* Close video stream */
1574 if (chan->vstream) {
1575 ast_closestream(chan->vstream);
1576 chan->vstream = NULL;
1579 sched_context_destroy(chan->sched);
1583 if (chan->generatordata) /* Clear any tone stuff remaining */
1584 if (chan->generator && chan->generator->release)
1585 chan->generator->release(chan, chan->generatordata);
1586 chan->generatordata = NULL;
1587 chan->generator = NULL;
1588 if (chan->cdr) { /* End the CDR if it hasn't already */
1589 ast_cdr_end(chan->cdr);
1590 ast_cdr_detach(chan->cdr); /* Post and Free the CDR */
1593 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1594 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1595 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1596 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1599 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1601 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1602 if (chan->tech->hangup)
1603 res = chan->tech->hangup(chan);
1606 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1609 ast_channel_unlock(chan);
1610 manager_event(EVENT_FLAG_CALL, "Hangup",
1614 "Cause-txt: %s\r\n",
1618 ast_cause2str(chan->hangupcause)
1620 ast_channel_free(chan);
1624 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1628 ast_channel_lock(chan);
1630 /* You can't answer an outbound call */
1631 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1632 ast_channel_unlock(chan);
1636 /* Stop if we're a zombie or need a soft hangup */
1637 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1638 ast_channel_unlock(chan);
1642 switch (chan->_state) {
1643 case AST_STATE_RINGING:
1644 case AST_STATE_RING:
1645 if (chan->tech->answer)
1646 res = chan->tech->answer(chan);
1647 ast_setstate(chan, AST_STATE_UP);
1648 ast_cdr_answer(chan->cdr);
1649 ast_channel_unlock(chan);
1651 ast_safe_sleep(chan, delay);
1655 ast_cdr_answer(chan->cdr);
1661 ast_channel_unlock(chan);
1666 int ast_answer(struct ast_channel *chan)
1668 return __ast_answer(chan, 500);
1671 void ast_deactivate_generator(struct ast_channel *chan)
1673 ast_channel_lock(chan);
1674 if (chan->generatordata) {
1675 if (chan->generator && chan->generator->release)
1676 chan->generator->release(chan, chan->generatordata);
1677 chan->generatordata = NULL;
1678 chan->generator = NULL;
1679 chan->fds[AST_GENERATOR_FD] = -1;
1680 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1681 ast_settimeout(chan, 0, NULL, NULL);
1683 ast_channel_unlock(chan);
1686 static int generator_force(void *data)
1688 /* Called if generator doesn't have data */
1691 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1692 struct ast_channel *chan = data;
1693 tmp = chan->generatordata;
1694 chan->generatordata = NULL;
1695 generate = chan->generator->generate;
1696 res = generate(chan, tmp, 0, 160);
1697 chan->generatordata = tmp;
1700 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1701 ast_deactivate_generator(chan);
1706 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1710 ast_channel_lock(chan);
1712 if (chan->generatordata) {
1713 if (chan->generator && chan->generator->release)
1714 chan->generator->release(chan, chan->generatordata);
1715 chan->generatordata = NULL;
1719 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1724 ast_settimeout(chan, 160, generator_force, chan);
1725 chan->generator = gen;
1728 ast_channel_unlock(chan);
1733 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1734 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1737 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1741 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1742 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1743 int *exception, int *outfd, int *ms)
1745 struct timeval start = { 0 , 0 };
1746 struct pollfd *pfds;
1752 long whentohangup = 0, diff;
1753 struct ast_channel *winner = NULL;
1759 sz = n * AST_MAX_FDS + nfds;
1760 pfds = alloca(sizeof(*pfds) * sz);
1761 fdmap = alloca(sizeof(*fdmap) * sz);
1768 /* Perform any pending masquerades */
1769 for (x=0; x < n; x++) {
1770 ast_channel_lock(c[x]);
1772 if (ast_do_masquerade(c[x])) {
1773 ast_log(LOG_WARNING, "Masquerade failed\n");
1775 ast_channel_unlock(c[x]);
1779 if (c[x]->whentohangup) {
1782 diff = c[x]->whentohangup - now;
1784 /* Should already be hungup */
1785 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1786 ast_channel_unlock(c[x]);
1789 if (!whentohangup || (diff < whentohangup))
1790 whentohangup = diff;
1792 ast_channel_unlock(c[x]);
1794 /* Wait full interval */
1797 rms = whentohangup * 1000; /* timeout in milliseconds */
1798 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1802 * Build the pollfd array, putting the channels' fds first,
1803 * followed by individual fds. Order is important because
1804 * individual fd's must have priority over channel fds.
1807 for (x=0; x<n; x++) {
1808 for (y=0; y<AST_MAX_FDS; y++) {
1809 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1810 fdmap[max].chan = x; /* channel x is linked to this pfds */
1811 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1813 CHECK_BLOCKING(c[x]);
1815 /* Add the individual fds */
1816 for (x=0; x<nfds; x++) {
1817 fdmap[max].chan = -1;
1818 max += ast_add_fd(&pfds[max], fds[x]);
1822 start = ast_tvnow();
1824 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1829 res = poll(pfds, max, kbrms);
1832 } while (!res && (rms > 0));
1834 res = poll(pfds, max, rms);
1837 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1838 if (res < 0) { /* Simulate a timeout if we were interrupted */
1843 if (whentohangup) { /* if we have a timeout, check who expired */
1845 for (x=0; x<n; x++) {
1846 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1847 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1853 if (res == 0) { /* no fd ready, reset timeout and done */
1854 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1858 * Then check if any channel or fd has a pending event.
1859 * Remember to check channels first and fds last, as they
1860 * must have priority on setting 'winner'
1862 for (x = 0; x < max; x++) {
1863 res = pfds[x].revents;
1866 if (fdmap[x].chan >= 0) { /* this is a channel */
1867 winner = c[fdmap[x].chan]; /* override previous winners */
1869 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1871 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1872 winner->fdno = fdmap[x].fdno;
1873 } else { /* this is an fd */
1875 *outfd = pfds[x].fd;
1877 *exception = (res & POLLPRI) ? -1 : 0;
1882 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1889 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1891 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1894 int ast_waitfor(struct ast_channel *c, int ms)
1896 int oldms = ms; /* -1 if no timeout */
1898 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1899 if ((ms < 0) && (oldms < 0))
1904 /* XXX never to be called with ms = -1 */
1905 int ast_waitfordigit(struct ast_channel *c, int ms)
1907 return ast_waitfordigit_full(c, ms, -1, -1);
1910 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1914 if (c->timingfd > -1) {
1920 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1921 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1922 c->timingfunc = func;
1923 c->timingdata = data;
1929 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1932 /* Stop if we're a zombie or need a soft hangup */
1933 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1935 /* Wait for a digit, no more than ms milliseconds total. */
1937 struct ast_channel *rchan;
1941 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1942 if (!rchan && outfd < 0 && ms) {
1943 if (errno == 0 || errno == EINTR)
1945 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1947 } else if (outfd > -1) {
1948 /* The FD we were watching has something waiting */
1952 struct ast_frame *f = ast_read(c);
1956 switch (f->frametype) {
1957 case AST_FRAME_DTMF:
1961 case AST_FRAME_CONTROL:
1962 switch (f->subclass) {
1963 case AST_CONTROL_HANGUP:
1966 case AST_CONTROL_RINGING:
1967 case AST_CONTROL_ANSWER:
1971 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1975 case AST_FRAME_VOICE:
1976 /* Write audio if appropriate */
1978 write(audiofd, f->data, f->datalen);
1986 return 0; /* Time is up */
1989 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1991 struct ast_frame *f = NULL; /* the return value */
1995 /* this function is very long so make sure there is only one return
1996 * point at the end (there is only one exception to this).
1998 ast_channel_lock(chan);
2000 if (ast_do_masquerade(chan))
2001 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2003 f = &ast_null_frame;
2007 /* Stop if we're a zombie or need a soft hangup */
2008 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2009 if (chan->generator)
2010 ast_deactivate_generator(chan);
2013 prestate = chan->_state;
2015 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2016 !ast_strlen_zero(chan->dtmfq)) {
2017 /* We have DTMF that has been deferred. Return it now */
2018 chan->dtmff.subclass = chan->dtmfq[0];
2019 /* Drop first digit from the buffer */
2020 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2022 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY))
2023 chan->dtmff.frametype = AST_FRAME_DTMF_END;
2025 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2026 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2027 chan->emulate_dtmf_digit = f->subclass;
2028 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2029 chan->dtmf_begin_tv = ast_tvnow();
2034 /* Read and ignore anything on the alertpipe, but read only
2035 one sizeof(blah) per frame that we send from it */
2036 if (chan->alertpipe[0] > -1)
2037 read(chan->alertpipe[0], &blah, sizeof(blah));
2040 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2043 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2045 /* IF we can't get event, assume it's an expired as-per the old interface */
2046 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2048 blah = ZT_EVENT_TIMER_EXPIRED;
2050 if (blah == ZT_EVENT_TIMER_PING) {
2051 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2052 /* Acknowledge PONG unless we need it again */
2053 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2054 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2057 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2058 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2059 if (chan->timingfunc) {
2060 /* save a copy of func/data before unlocking the channel */
2061 int (*func)(void *) = chan->timingfunc;
2062 void *data = chan->timingdata;
2063 ast_channel_unlock(chan);
2067 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2068 chan->timingdata = NULL;
2069 ast_channel_unlock(chan);
2071 /* cannot 'goto done' because the channel is already unlocked */
2072 return &ast_null_frame;
2074 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2077 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2078 /* if the AST_GENERATOR_FD is set, call the generator with args
2079 * set to -1 so it can do whatever it needs to.
2081 void *tmp = chan->generatordata;
2082 chan->generatordata = NULL; /* reset to let ast_write get through */
2083 chan->generator->generate(chan, tmp, -1, -1);
2084 chan->generatordata = tmp;
2085 f = &ast_null_frame;
2089 /* Check for pending read queue */
2090 if (!AST_LIST_EMPTY(&chan->readq)) {
2091 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2092 /* Interpret hangup and return NULL */
2093 /* XXX why not the same for frames from the channel ? */
2094 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2099 chan->blocker = pthread_self();
2100 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2101 if (chan->tech->exception)
2102 f = chan->tech->exception(chan);
2104 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2105 f = &ast_null_frame;
2107 /* Clear the exception flag */
2108 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2109 } else if (chan->tech->read)
2110 f = chan->tech->read(chan);
2112 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2116 /* if the channel driver returned more than one frame, stuff the excess
2117 into the readq for the next ast_read call (note that we can safely assume
2118 that the readq is empty, because otherwise we would not have called into
2119 the channel driver and f would be only a single frame)
2121 if (AST_LIST_NEXT(f, frame_list)) {
2122 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2123 AST_LIST_NEXT(f, frame_list) = NULL;
2126 switch (f->frametype) {
2127 case AST_FRAME_CONTROL:
2128 if (f->subclass == AST_CONTROL_ANSWER) {
2129 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2131 ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
2133 f = &ast_null_frame;
2134 } else if (prestate == AST_STATE_UP) {
2136 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
2138 f = &ast_null_frame;
2140 /* Answer the CDR */
2141 ast_setstate(chan, AST_STATE_UP);
2142 ast_cdr_answer(chan->cdr);
2146 case AST_FRAME_DTMF_END:
2147 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2148 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2149 * However, only let emulation be forced if the other end cares about BEGIN frames */
2150 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2151 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2152 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2153 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2155 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2157 f = &ast_null_frame;
2158 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2159 f->frametype = AST_FRAME_DTMF_BEGIN;
2160 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2161 chan->emulate_dtmf_digit = f->subclass;
2162 chan->dtmf_begin_tv = ast_tvnow();
2164 chan->emulate_dtmf_duration = f->len;
2166 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2168 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2170 f->len = ast_tvdiff_ms(ast_tvnow(), chan->dtmf_begin_tv);
2173 case AST_FRAME_DTMF_BEGIN:
2174 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2175 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2177 f = &ast_null_frame;
2179 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2180 chan->dtmf_begin_tv = ast_tvnow();
2183 case AST_FRAME_VOICE:
2184 /* The EMULATE_DTMF flag must be cleared here as opposed to when the samples
2185 * first get to zero, because we want to make sure we pass at least one
2186 * voice frame through before starting the next digit, to ensure a gap
2187 * between DTMF digits. */
2188 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2189 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2190 chan->emulate_dtmf_digit = 0;
2193 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2195 f = &ast_null_frame;
2196 } else if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2197 if ((f->samples / 8) >= chan->emulate_dtmf_duration) { /* XXX 8kHz */
2198 chan->emulate_dtmf_duration = 0;
2199 f->frametype = AST_FRAME_DTMF_END;
2200 f->subclass = chan->emulate_dtmf_digit;
2201 f->len = ast_tvdiff_ms(ast_tvnow(), chan->dtmf_begin_tv);
2203 chan->emulate_dtmf_duration -= f->samples / 8; /* XXX 8kHz */
2205 f = &ast_null_frame;
2207 } else if (!(f->subclass & chan->nativeformats)) {
2208 /* This frame can't be from the current native formats -- drop it on the
2210 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2211 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2213 f = &ast_null_frame;
2216 queue_frame_to_spies(chan, f, SPY_READ);
2218 if (chan->monitor && chan->monitor->read_stream ) {
2219 /* XXX what does this do ? */
2220 #ifndef MONITOR_CONSTANT_DELAY
2221 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2223 jump = chan->outsmpl - chan->insmpl;
2224 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2225 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2226 chan->insmpl += jump + f->samples;
2228 chan->insmpl+= f->samples;
2230 int jump = chan->outsmpl - chan->insmpl;
2231 if (jump - MONITOR_DELAY >= 0) {
2232 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2233 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2234 chan->insmpl += jump;
2236 chan->insmpl += f->samples;
2238 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2239 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2240 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2244 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2245 f = &ast_null_frame;
2247 /* Run generator sitting on the line if timing device not available
2248 * and synchronous generation of outgoing frames is necessary */
2249 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2250 void *tmp = chan->generatordata;
2253 if (chan->timingfunc) {
2254 if (option_debug > 1)
2255 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2256 ast_settimeout(chan, 0, NULL, NULL);
2259 chan->generatordata = NULL; /* reset, to let writes go through */
2260 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2261 chan->generatordata = tmp;
2263 if (option_debug > 1)
2264 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2265 ast_deactivate_generator(chan);
2268 } else if (f->frametype == AST_FRAME_CNG) {
2269 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2270 if (option_debug > 1)
2271 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2272 ast_settimeout(chan, 160, generator_force, chan);
2277 /* Just pass it on! */
2281 /* Make sure we always return NULL in the future */
2282 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2283 if (chan->generator)
2284 ast_deactivate_generator(chan);
2285 /* End the CDR if appropriate */
2287 ast_cdr_end(chan->cdr);
2290 /* High bit prints debugging */
2291 if (chan->fin & DEBUGCHAN_FLAG)
2292 ast_frame_dump(chan->name, f, "<<");
2293 chan->fin = FRAMECOUNT_INC(chan->fin);
2296 ast_channel_unlock(chan);
2300 int ast_internal_timing_enabled(struct ast_channel *chan)
2302 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2303 if (option_debug > 4)
2304 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);
2308 struct ast_frame *ast_read(struct ast_channel *chan)
2310 return __ast_read(chan, 0);
2313 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2315 return __ast_read(chan, 1);
2318 int ast_indicate(struct ast_channel *chan, int condition)
2320 return ast_indicate_data(chan, condition, NULL, 0);
2323 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2327 ast_channel_lock(chan);
2328 /* Stop if we're a zombie or need a soft hangup */
2329 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2330 ast_channel_unlock(chan);
2333 if (chan->tech->indicate)
2334 res = chan->tech->indicate(chan, condition, data, datalen);
2335 ast_channel_unlock(chan);
2336 if (!chan->tech->indicate || res) {
2338 * Device does not support (that) indication, lets fake
2339 * it by doing our own tone generation. (PM2002)
2342 ast_playtones_stop(chan);
2344 const struct ind_tone_zone_sound *ts = NULL;
2345 switch (condition) {
2346 case AST_CONTROL_RINGING:
2347 ts = ast_get_indication_tone(chan->zone, "ring");
2349 case AST_CONTROL_BUSY:
2350 ts = ast_get_indication_tone(chan->zone, "busy");
2352 case AST_CONTROL_CONGESTION:
2353 ts = ast_get_indication_tone(chan->zone, "congestion");
2356 if (ts && ts->data[0]) {
2358 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2359 ast_playtones_start(chan,0,ts->data, 1);
2361 } else if (condition == AST_CONTROL_PROGRESS) {
2362 /* ast_playtones_stop(chan); */
2363 } else if (condition == AST_CONTROL_PROCEEDING) {
2364 /* Do nothing, really */
2365 } else if (condition == AST_CONTROL_HOLD) {
2366 /* Do nothing.... */
2367 } else if (condition == AST_CONTROL_UNHOLD) {
2368 /* Do nothing.... */
2369 } else if (condition == AST_CONTROL_VIDUPDATE) {
2370 /* Do nothing.... */
2373 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2381 int ast_recvchar(struct ast_channel *chan, int timeout)
2384 char *buf = ast_recvtext(chan, timeout);
2386 return -1; /* error or timeout */
2387 c = *(unsigned char *)buf;
2392 char *ast_recvtext(struct ast_channel *chan, int timeout)
2398 struct ast_frame *f;
2399 if (ast_check_hangup(chan))
2401 res = ast_waitfor(chan, timeout);
2402 if (res <= 0) /* timeout or error */
2404 timeout = res; /* update timeout */
2407 break; /* no frame */
2408 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2409 done = 1; /* force a break */
2410 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2411 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2419 int ast_sendtext(struct ast_channel *chan, const char *text)
2422 /* Stop if we're a zombie or need a soft hangup */
2423 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2425 CHECK_BLOCKING(chan);
2426 if (chan->tech->send_text)
2427 res = chan->tech->send_text(chan, text);
2428 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2432 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2436 if (chan->tech->send_digit_begin)
2437 res = chan->tech->send_digit_begin(chan, digit);
2441 * Device does not support DTMF tones, lets fake
2442 * it by doing our own generation. (PM2002)
2444 static const char* dtmf_tones[] = {
2445 "!941+1336/100,!0/100", /* 0 */
2446 "!697+1209/100,!0/100", /* 1 */
2447 "!697+1336/100,!0/100", /* 2 */
2448 "!697+1477/100,!0/100", /* 3 */
2449 "!770+1209/100,!0/100", /* 4 */
2450 "!770+1336/100,!0/100", /* 5 */
2451 "!770+1477/100,!0/100", /* 6 */
2452 "!852+1209/100,!0/100", /* 7 */
2453 "!852+1336/100,!0/100", /* 8 */
2454 "!852+1477/100,!0/100", /* 9 */
2455 "!697+1633/100,!0/100", /* A */
2456 "!770+1633/100,!0/100", /* B */
2457 "!852+1633/100,!0/100", /* C */
2458 "!941+1633/100,!0/100", /* D */
2459 "!941+1209/100,!0/100", /* * */
2460 "!941+1477/100,!0/100" }; /* # */
2461 if (digit >= '0' && digit <='9')
2462 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2463 else if (digit >= 'A' && digit <= 'D')
2464 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2465 else if (digit == '*')
2466 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2467 else if (digit == '#')
2468 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2472 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2479 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2483 if (chan->tech->send_digit_end)
2484 res = chan->tech->send_digit_end(chan, digit, duration);
2486 if (res && chan->generator)
2487 ast_playtones_stop(chan);
2492 int ast_senddigit(struct ast_channel *chan, char digit)
2494 if (!ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2495 ast_senddigit_begin(chan, digit);
2496 ast_safe_sleep(chan, 100); /* XXX 100ms ... probably should be configurable */
2499 return ast_senddigit_end(chan, digit, 100);
2502 int ast_prod(struct ast_channel *chan)
2504 struct ast_frame a = { AST_FRAME_VOICE };
2507 /* Send an empty audio frame to get things moving */
2508 if (chan->_state != AST_STATE_UP) {
2510 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2511 a.subclass = chan->rawwriteformat;
2512 a.data = nothing + AST_FRIENDLY_OFFSET;
2514 if (ast_write(chan, &a))
2515 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2520 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2523 if (!chan->tech->write_video)
2525 res = ast_write(chan, fr);
2531 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2534 struct ast_frame *f = NULL;
2536 /* Stop if we're a zombie or need a soft hangup */
2537 ast_channel_lock(chan);
2538 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2541 /* Handle any pending masquerades */
2542 if (chan->masq && ast_do_masquerade(chan)) {
2543 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2547 res = 0; /* XXX explain, why 0 ? */
2550 if (chan->generatordata) {
2551 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2552 ast_deactivate_generator(chan);
2554 res = 0; /* XXX explain, why 0 ? */
2558 /* High bit prints debugging */
2559 if (chan->fout & DEBUGCHAN_FLAG)
2560 ast_frame_dump(chan->name, fr, ">>");
2561 CHECK_BLOCKING(chan);
2562 switch (fr->frametype) {
2563 case AST_FRAME_CONTROL:
2564 res = (chan->tech->indicate == NULL) ? 0 :
2565 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2567 case AST_FRAME_DTMF_BEGIN:
2568 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2569 ast_channel_unlock(chan);
2570 res = ast_senddigit_begin(chan, fr->subclass);
2571 ast_channel_lock(chan);
2572 CHECK_BLOCKING(chan);
2574 case AST_FRAME_DTMF_END:
2575 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2576 ast_channel_unlock(chan);
2577 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2578 ast_channel_lock(chan);
2579 CHECK_BLOCKING(chan);
2581 case AST_FRAME_TEXT:
2582 if (fr->subclass == AST_FORMAT_T140) {
2583 res = (chan->tech->write_text == NULL) ? 0 :
2584 chan->tech->write_text(chan, fr);
2586 res = (chan->tech->send_text == NULL) ? 0 :
2587 chan->tech->send_text(chan, (char *) fr->data);
2590 case AST_FRAME_HTML:
2591 res = (chan->tech->send_html == NULL) ? 0 :
2592 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2594 case AST_FRAME_VIDEO:
2595 /* XXX Handle translation of video codecs one day XXX */
2596 res = (chan->tech->write_video == NULL) ? 0 :
2597 chan->tech->write_video(chan, fr);
2599 case AST_FRAME_MODEM:
2600 res = (chan->tech->write == NULL) ? 0 :
2601 chan->tech->write(chan, fr);
2603 case AST_FRAME_VOICE:
2604 if (chan->tech->write == NULL)
2605 break; /*! \todo XXX should return 0 maybe ? */
2607 /* If someone is whispering on this channel then we must ensure that we are always getting signed linear frames */
2608 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2609 if (fr->subclass == AST_FORMAT_SLINEAR)
2612 ast_mutex_lock(&chan->whisper->lock);
2613 if (chan->writeformat != AST_FORMAT_SLINEAR) {
2614 /* Rebuild the translation path and set our write format back to signed linear */
2615 chan->whisper->original_format = chan->writeformat;
2616 ast_set_write_format(chan, AST_FORMAT_SLINEAR);
2617 if (chan->whisper->path)
2618 ast_translator_free_path(chan->whisper->path);
2619 chan->whisper->path = ast_translator_build_path(AST_FORMAT_SLINEAR, chan->whisper->original_format);
2621 /* Translate frame using the above translation path */
2622 f = (chan->whisper->path) ? ast_translate(chan->whisper->path, fr, 0) : fr;
2623 ast_mutex_unlock(&chan->whisper->lock);
2626 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2627 if (fr->subclass == chan->rawwriteformat)
2630 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2633 /* If we have no frame of audio, then we have to bail out */
2639 /* If spies are on the channel then queue the frame out to them */
2641 queue_frame_to_spies(chan, f, SPY_WRITE);
2643 /* If Monitor is running on this channel, then we have to write frames out there too */
2644 if (chan->monitor && chan->monitor->write_stream) {
2645 /* XXX must explain this code */
2646 #ifndef MONITOR_CONSTANT_DELAY
2647 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2649 jump = chan->insmpl - chan->outsmpl;
2650 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2651 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2652 chan->outsmpl += jump + f->samples;
2654 chan->outsmpl += f->samples;
2656 int jump = chan->insmpl - chan->outsmpl;
2657 if (jump - MONITOR_DELAY >= 0) {
2658 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2659 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2660 chan->outsmpl += jump;
2662 chan->outsmpl += f->samples;
2664 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2665 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2666 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2670 /* Finally the good part! Write this out to the channel */
2671 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2672 /* frame is assumed to be in SLINEAR, since that is
2673 required for whisper mode */
2674 ast_frame_adjust_volume(f, -2);
2675 if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2676 short buf[f->samples];
2677 struct ast_frame whisper = {
2678 .frametype = AST_FRAME_VOICE,
2679 .subclass = AST_FORMAT_SLINEAR,
2681 .datalen = sizeof(buf),
2682 .samples = f->samples,
2685 ast_mutex_lock(&chan->whisper->lock);
2686 if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2687 ast_frame_slinear_sum(f, &whisper);
2688 ast_mutex_unlock(&chan->whisper->lock);
2690 /* and now put it through the regular translator */
2691 f = (chan->writetrans) ? ast_translate(chan->writetrans, f, 0) : f;
2693 res = f ? chan->tech->write(chan, f) : 0;
2695 case AST_FRAME_NULL:
2701 /* At this point, fr is the incoming frame and f is NULL. Channels do
2702 * not expect to get NULL as a frame pointer and will segfault. Hence,
2703 * we output the original frame passed in. */
2704 res = chan->tech->write(chan, fr);
2710 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2711 /* Consider a write failure to force a soft hangup */
2713 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2715 chan->fout = FRAMECOUNT_INC(chan->fout);
2718 ast_channel_unlock(chan);
2722 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2723 struct ast_trans_pvt **trans, const int direction)
2728 /* Make sure we only consider audio */
2729 fmt &= AST_FORMAT_AUDIO_MASK;
2731 native = chan->nativeformats;
2732 /* Find a translation path from the native format to one of the desired formats */
2735 res = ast_translator_best_choice(&fmt, &native);
2738 res = ast_translator_best_choice(&native, &fmt);
2741 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2742 ast_getformatname(native), ast_getformatname(fmt));
2746 /* Now we have a good choice for both. */
2747 ast_channel_lock(chan);
2749 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2750 /* the channel is already in these formats, so nothing to do */
2751 ast_channel_unlock(chan);
2755 *rawformat = native;
2756 /* User perspective is fmt */
2758 /* Free any read translation we have right now */
2760 ast_translator_free_path(*trans);
2761 /* Build a translation path from the raw format to the desired format */
2764 *trans = ast_translator_build_path(*format, *rawformat);
2767 *trans = ast_translator_build_path(*rawformat, *format);
2768 ast_channel_unlock(chan);
2770 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2771 direction ? "write" : "read", ast_getformatname(fmt));
2775 int ast_set_read_format(struct ast_channel *chan, int fmt)
2777 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2778 &chan->readtrans, 0);
2781 int ast_set_write_format(struct ast_channel *chan, int fmt)
2783 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2784 &chan->writetrans, 1);
2787 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)
2791 struct ast_channel *chan;
2797 outstate = &dummy_outstate; /* make outstate always a valid pointer */
2799 chan = ast_request(type, format, data, &cause);
2801 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2802 /* compute error and return */
2803 if (cause == AST_CAUSE_BUSY)
2804 *outstate = AST_CONTROL_BUSY;
2805 else if (cause == AST_CAUSE_CONGESTION)
2806 *outstate = AST_CONTROL_CONGESTION;
2812 ast_set_variables(chan, oh->vars);
2813 /* XXX why is this necessary, for the parent_channel perhaps ? */
2814 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2815 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2816 if (oh->parent_channel)
2817 ast_channel_inherit_variables(oh->parent_channel, chan);
2819 ast_cdr_setaccount(chan, oh->account);
2821 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2823 if (ast_call(chan, data, 0)) { /* ast_call failed... */
2824 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2826 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
2827 while (timeout && chan->_state != AST_STATE_UP) {
2828 struct ast_frame *f;
2829 res = ast_waitfor(chan, timeout);
2830 if (res <= 0) /* error, timeout, or done */
2836 *outstate = AST_CONTROL_HANGUP;
2840 if (f->frametype == AST_FRAME_CONTROL) {
2841 switch (f->subclass) {
2842 case AST_CONTROL_RINGING: /* record but keep going */
2843 *outstate = f->subclass;
2846 case AST_CONTROL_BUSY:
2847 case AST_CONTROL_CONGESTION:
2848 case AST_CONTROL_ANSWER:
2849 *outstate = f->subclass;
2850 timeout = 0; /* trick to force exit from the while() */
2854 case AST_CONTROL_PROGRESS:
2855 case AST_CONTROL_PROCEEDING:
2856 case AST_CONTROL_HOLD:
2857 case AST_CONTROL_UNHOLD:
2858 case AST_CONTROL_VIDUPDATE:
2859 case -1: /* Ignore -- just stopping indications */
2863 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2872 if (!ast_strlen_zero(oh->context))
2873 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2874 if (!ast_strlen_zero(oh->exten))
2875 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2877 chan->priority = oh->priority;
2879 if (chan->_state == AST_STATE_UP)
2880 *outstate = AST_CONTROL_ANSWER;
2883 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2884 ast_cdr_init(chan->cdr, chan);
2887 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2888 ast_cdr_setapp(chan->cdr,"Dial",tmp);
2889 ast_cdr_update(chan);
2890 ast_cdr_start(chan->cdr);
2891 ast_cdr_end(chan->cdr);
2892 /* If the cause wasn't handled properly */
2893 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2894 ast_cdr_failed(chan->cdr);
2902 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2904 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2907 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2909 struct chanlist *chan;
2910 struct ast_channel *c;
2915 int videoformat = format & AST_FORMAT_VIDEO_MASK;
2916 int textformat = format & AST_FORMAT_TEXT_MASK;
2920 *cause = AST_CAUSE_NOTDEFINED;
2922 if (AST_LIST_LOCK(&channels)) {
2923 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2927 AST_LIST_TRAVERSE(&backends, chan, list) {
2928 if (strcasecmp(type, chan->tech->type))
2931 capabilities = chan->tech->capabilities;
2932 fmt = format & AST_FORMAT_AUDIO_MASK;
2933 res = ast_translator_best_choice(&fmt, &capabilities);
2935 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2936 AST_LIST_UNLOCK(&channels);
2939 AST_LIST_UNLOCK(&channels);
2940 if (!chan->tech->requester)
2943 if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, data, cause)))
2946 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
2950 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2951 *cause = AST_CAUSE_NOSUCHDRIVER;
2952 AST_LIST_UNLOCK(&channels);
2957 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2959 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2960 If the remote end does not answer within the timeout, then do NOT hang up, but
2963 /* Stop if we're a zombie or need a soft hangup */
2964 ast_channel_lock(chan);
2965 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2966 if (chan->tech->call)
2967 res = chan->tech->call(chan, addr, timeout);
2968 ast_set_flag(chan, AST_FLAG_OUTGOING);
2970 ast_channel_unlock(chan);
2975 \brief Transfer a call to dest, if the channel supports transfer
2979 \arg the manager interface
2981 int ast_transfer(struct ast_channel *chan, char *dest)
2985 /* Stop if we're a zombie or need a soft hangup */
2986 ast_channel_lock(chan);
2987 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2988 if (chan->tech->transfer) {
2989 res = chan->tech->transfer(chan, dest);
2995 ast_channel_unlock(chan);
2999 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3001 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3004 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3006 int pos = 0; /* index in the buffer where we accumulate digits */
3009 /* Stop if we're a zombie or need a soft hangup */
3010 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3017 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3021 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3023 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3035 if (!strchr(enders, d))
3037 if (strchr(enders, d) || (pos >= len)) {
3047 int ast_channel_supports_html(struct ast_channel *chan)
3049 return (chan->tech->send_html) ? 1 : 0;
3052 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3054 if (chan->tech->send_html)
3055 return chan->tech->send_html(chan, subclass, data, datalen);
3059 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3061 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3064 /*! \brief Set up translation from one channel to another */
3065 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
3070 /* Set up translation from the 'from' channel to the 'to' channel */
3071 src = from->nativeformats;
3072 dst = to->nativeformats;
3073 if (ast_translator_best_choice(&dst, &src) < 0) {
3074 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", from->name, src, to->name, dst);
3078 /* if the best path is not 'pass through', then
3079 transcoding is needed; if desired, force transcode path
3080 to use SLINEAR between channels, but only if there is
3081 no direct conversion available */
3082 if ((src != dst) && ast_opt_transcode_via_slin &&
3083 (ast_translate_path_steps(dst, src) != 1))
3084 dst = AST_FORMAT_SLINEAR;
3085 if (ast_set_read_format(from, dst) < 0) {
3086 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", from->name, dst);
3089 if (ast_set_write_format(to, dst) < 0) {
3090 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", to->name, dst);
3096 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3098 /* Some callers do not check return code, and we must try to set all call legs correctly */
3101 /* Set up translation from the chan to the peer */
3102 rc = ast_channel_make_compatible_helper(chan, peer);
3107 /* Set up translation from the peer to the chan */
3108 rc = ast_channel_make_compatible_helper(peer, chan);
3113 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3116 struct ast_channel *final_orig = original, *final_clone = clone;
3118 ast_channel_lock(original);
3119 while (ast_channel_trylock(clone)) {
3120 ast_channel_unlock(original);
3122 ast_channel_lock(original);
3125 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3126 and if so, we don't really want to masquerade it, but its proxy */
3127 if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
3128 final_orig = original->_bridge;
3130 if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)) && (clone->_bridge->_bridge != clone))
3131 final_clone = clone->_bridge;
3133 if ((final_orig != original) || (final_clone != clone)) {
3134 ast_channel_lock(final_orig);
3135 while (ast_channel_trylock(final_clone)) {
3136 ast_channel_unlock(final_orig);
3138 ast_channel_lock(final_orig);
3140 ast_channel_unlock(clone);
3141 ast_channel_unlock(original);
3142 original = final_orig;
3143 clone = final_clone;
3146 if (original == clone) {
3147 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3148 ast_channel_unlock(clone);
3149 ast_channel_unlock(original);
3154 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
3155 clone->name, original->name);
3156 if (original->masq) {
3157 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3158 original->masq->name, original->name);
3159 } else if (clone->masqr) {
3160 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3161 clone->name, clone->masqr->name);
3163 original->masq = clone;
3164 clone->masqr = original;
3165 ast_queue_frame(original, &ast_null_frame);
3166 ast_queue_frame(clone, &ast_null_frame);
3168 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3172 ast_channel_unlock(clone);
3173 ast_channel_unlock(original);
3178 void ast_change_name(struct ast_channel *chan, char *newname)
3180 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3181 ast_string_field_set(chan, name, newname);
3184 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3186 struct ast_var_t *current, *newvar;
3187 const char *varname;
3189 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3192 varname = ast_var_full_name(current);
3196 if (varname[0] == '_') {
3198 if (varname[1] == '_')
3204 newvar = ast_var_assign(&varname[1], ast_var_value(current));
3206 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3208 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3212 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
3214 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3216 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3221 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
3228 \brief Clone channel variables from 'clone' channel into 'original' channel
3230 All variables except those related to app_groupcount are cloned.
3231 Variables are actually _removed_ from 'clone' channel, presumably
3232 because it will subsequently be destroyed.
3234 \note Assumes locks will be in place on both channels when called.
3236 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3238 struct ast_var_t *varptr;
3240 /* we need to remove all app_groupcount related variables from the original
3241 channel before merging in the clone's variables; any groups assigned to the
3242 original channel should be released, only those assigned to the clone
3246 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
3247 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
3248 AST_LIST_REMOVE_CURRENT(&original->varshead, entries);
3249 ast_var_delete(varptr);
3252 AST_LIST_TRAVERSE_SAFE_END;
3254 /* Append variables from clone channel into original channel */
3255 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3256 if (AST_LIST_FIRST(&clone->varshead))
3257 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3261 \brief Masquerade a channel
3263 \note Assumes channel will be locked when called
3265 int ast_do_masquerade(struct ast_channel *original)
3270 struct ast_frame *cur;
3271 const struct ast_channel_tech *t;
3273 struct ast_callerid tmpcid;
3274 struct ast_channel *clone = original->masq;
3275 struct ast_channel_spy_list *spy_list = NULL;
3276 struct ast_channel_spy *spy = NULL;
3277 int rformat = original->readformat;
3278 int wformat = original->writeformat;
3284 if (option_debug > 3)
3285 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3286 clone->name, clone->_state, original->name, original->_state);
3288 manager_event(EVENT_FLAG_CALL, "Masquerade", "Clone: %s\r\nCloneState: %s\r\nOriginal: %s\r\nOriginalState: %s\r\n",
3289 clone->name, ast_state2str(clone->_state), original->name, ast_state2str(original->_state));
3291 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3292 the clone channel into the original channel. Start by killing off the original
3293 channel's backend. I'm not sure we're going to keep this function, because
3294 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3296 /* We need the clone's lock, too */
3297 ast_channel_lock(clone);
3299 if (option_debug > 1)
3300 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3302 /* Having remembered the original read/write formats, we turn off any translation on either
3304 free_translation(clone);
3305 free_translation(original);
3308 /* Unlink the masquerade */
3309 original->masq = NULL;
3310 clone->masqr = NULL;
3312 /* Save the original name */
3313 ast_copy_string(orig, original->name, sizeof(orig));
3314 /* Save the new name */
3315 ast_copy_string(newn, clone->name, sizeof(newn));
3316 /* Create the masq name */
3317 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3319 /* Copy the name from the clone channel */
3320 ast_string_field_set(original, name, newn);
3322 /* Mangle the name of the clone channel */
3323 ast_string_field_set(clone, name, masqn);
3325 /* Notify any managers of the change, first the masq then the other */
3326 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3327 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3329 /* Swap the technologies */
3331 original->tech = clone->tech;
3334 t_pvt = original->tech_pvt;
3335 original->tech_pvt = clone->tech_pvt;
3336 clone->tech_pvt = t_pvt;
3338 /* Swap the readq's */
3339 cur = AST_LIST_FIRST(&original->readq);
3340 AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3341 AST_LIST_HEAD_SET_NOLOCK(&clone->readq, cur);
3343 /* Swap the alertpipes */
3344 for (i = 0; i < 2; i++) {
3345 x = original->alertpipe[i];
3346 original->alertpipe[i] = clone->alertpipe[i];
3347 clone->alertpipe[i] = x;
3350 /* Swap the raw formats */
3351 x = original->rawreadformat;
3352 original->rawreadformat = clone->rawreadformat;
3353 clone->rawreadformat = x;
3354 x = original->rawwriteformat;
3355 original->rawwriteformat = clone->rawwriteformat;
3356 clone->rawwriteformat = x;
3358 /* Swap the spies */
3359 spy_list = original->spies;
3360 original->spies = clone->spies;
3361 clone->spies = spy_list;
3363 /* Update channel on respective spy lists if present */
3364 if (original->spies) {
3365 AST_LIST_TRAVERSE(&original->spies->list, spy, list) {
3366 ast_mutex_lock(&spy->lock);
3367 spy->chan = original;
3368 ast_mutex_unlock(&spy->lock);
3372 AST_LIST_TRAVERSE(&clone->spies->list, spy, list) {
3373 ast_mutex_lock(&spy->lock);
3375 ast_mutex_unlock(&spy->lock);
3379 /* Save any pending frames on both sides. Start by counting
3380 * how many we're going to need... */
3382 if (original->alertpipe[1] > -1) {
3383 AST_LIST_TRAVERSE(&clone->readq, cur, frame_list)
3387 /* If we had any, prepend them to the ones already in the queue, and
3388 * load up the alertpipe */
3389 if (AST_LIST_FIRST(&clone->readq)) {
3390 AST_LIST_INSERT_TAIL(&clone->readq, AST_LIST_FIRST(&original->readq), frame_list);
3391 AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3392 AST_LIST_HEAD_SET_NOLOCK(&clone->readq, NULL);
3393 for (i = 0; i < x; i++)
3394 write(original->alertpipe[1], &x, sizeof(x));
3397 clone->_softhangup = AST_SOFTHANGUP_DEV;
3400 /* And of course, so does our current state. Note we need not
3401 call ast_setstate since the event manager doesn't really consider
3402 these separate. We do this early so that the clone has the proper
3403 state of the original channel. */
3404 origstate = original->_state;
3405 original->_state = clone->_state;
3406 clone->_state = origstate;
3408 if (clone->tech->fixup){
3409 res = clone->tech->fixup(original, clone);
3411 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3414 /* Start by disconnecting the original's physical side */
3415 if (clone->tech->hangup)
3416 res = clone->tech->hangup(clone);
3418 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
3419 ast_channel_unlock(clone);
3423 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3424 /* Mangle the name of the clone channel */
3425 ast_string_field_set(clone, name, zombn);
3426 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3428 /* Update the type. */
3429 t_pvt = original->monitor;
3430 original->monitor = clone->monitor;
3431 clone->monitor = t_pvt;
3433 /* Keep the same language. */
3434 ast_string_field_set(original, language, clone->language);
3435 /* Copy the FD's other than the generator fd */
3436 for (x = 0; x < AST_MAX_FDS; x++) {
3437 if (x != AST_GENERATOR_FD)
3438 original->fds[x] = clone->fds[x];
3441 /* move any whisperer over */
3442 ast_channel_whisper_stop(original);
3443 if (ast_test_flag(clone, AST_FLAG_WHISPER)) {
3444 original->whisper = clone->whisper;
3445 ast_set_flag(original, AST_FLAG_WHISPER);
3446 clone->whisper = NULL;
3447 ast_clear_flag(clone, AST_FLAG_WHISPER);
3450 /* Move data stores over */
3451 if (AST_LIST_FIRST(&clone->datastores))
3452 AST_LIST_INSERT_TAIL(&original->datastores, AST_LIST_FIRST(&clone->datastores), entry);
3453 AST_LIST_HEAD_INIT_NOLOCK(&clone->datastores);
3455 clone_variables(original, clone);
3456 AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3457 /* Presense of ADSI capable CPE follows clone */
3458 original->adsicpe = clone->adsicpe;
3459 /* Bridge remains the same */
3460 /* CDR fields remain the same */
3461 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3462 /* Application and data remain the same */
3463 /* Clone exception becomes real one, as with fdno */
3464 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3465 original->fdno = clone->fdno;
3466 /* Schedule context remains the same */
3467 /* Stream stuff stays the same */
3468 /* Keep the original state. The fixup code will need to work with it most likely */
3470 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3472 tmpcid = original->cid;
3473 original->cid = clone->cid;
3474 clone->cid = tmpcid;
3476 /* Restore original timing file descriptor */
3477 original->fds[AST_TIMING_FD] = original->timingfd;
3479 /* Our native formats are different now */
3480 original->nativeformats = clone->nativeformats;
3482 /* Context, extension, priority, app data, jump table, remain the same */
3483 /* pvt switches. pbx stays the same, as does next */
3485 /* Set the write format */
3486 ast_set_write_format(original, wformat);
3488 /* Set the read format */
3489 ast_set_read_format(original, rformat);
3491 /* Copy the music class */
3492 ast_string_field_set(original, musicclass, clone->musicclass);
3495 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3497 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3498 can fix up everything as best as possible */
3499 if (original->tech->fixup) {
3500 res = original->tech->fixup(clone, original);
3502 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3503 original->tech->type, original->name);
3504 ast_channel_unlock(clone);
3508 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3509 original->tech->type, original->name);
3511 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3512 a zombie so nothing tries to touch it. If it's already been marked as a
3513 zombie, then free it now (since it already is considered invalid). */
3514 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3516 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3517 ast_channel_unlock(clone);
3518 manager_event(EVENT_FLAG_CALL, "Hangup",
3522 "Cause-txt: %s\r\n",
3526 ast_cause2str(clone->hangupcause)
3528 ast_channel_free(clone);
3531 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3532 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3533 ast_queue_frame(clone, &ast_null_frame);
3534 ast_channel_unlock(clone);
3537 /* Signal any blocker */
3538 if (ast_test_flag(original, AST_FLAG_BLOCKING))
3539 pthread_kill(original->blocker, SIGURG);
3541 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3545 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3548 if (chan->cid.cid_num)
3549 free(chan->cid.cid_num);
3550 chan->cid.cid_num = ast_strdup(callerid);
3553 if (chan->cid.cid_name)
3554 free(chan->cid.cid_name);
3555 chan->cid.cid_name = ast_strdup(calleridname);
3558 if (chan->cid.cid_ani)
3559 free(chan->cid.cid_ani);
3560 chan->cid.cid_ani = ast_strdup(ani);
3563 ast_cdr_setcid(chan->cdr, chan);
3564 manager_event(EVENT_FLAG_CALL, "Newcallerid",