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$")
30 #include "asterisk/_private.h"
36 #include "asterisk/paths.h" /* use ast_config_AST_SYSTEM_NAME */
37 #include "asterisk/zapata.h"
39 #include "asterisk/pbx.h"
40 #include "asterisk/frame.h"
41 #include "asterisk/sched.h"
42 #include "asterisk/channel.h"
43 #include "asterisk/musiconhold.h"
44 #include "asterisk/say.h"
45 #include "asterisk/file.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/translate.h"
48 #include "asterisk/manager.h"
49 #include "asterisk/chanvars.h"
50 #include "asterisk/linkedlists.h"
51 #include "asterisk/indications.h"
52 #include "asterisk/monitor.h"
53 #include "asterisk/causes.h"
54 #include "asterisk/callerid.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/lock.h"
57 #include "asterisk/app.h"
58 #include "asterisk/transcap.h"
59 #include "asterisk/devicestate.h"
60 #include "asterisk/sha1.h"
61 #include "asterisk/threadstorage.h"
62 #include "asterisk/slinfactory.h"
63 #include "asterisk/audiohook.h"
66 #include <sys/epoll.h>
69 struct ast_epoll_data {
70 struct ast_channel *chan;
74 /* uncomment if you have problems with 'monitoring' synchronized files */
76 #define MONITOR_CONSTANT_DELAY
77 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
80 /*! \brief Prevent new channel allocation if shutting down. */
81 static int shutting_down;
85 unsigned long global_fin, global_fout;
87 AST_THREADSTORAGE(state2str_threadbuf);
88 #define STATE2STR_BUFSIZE 32
90 /*! Default amount of time to use when emulating a digit as a begin and end
92 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
94 /*! Minimum allowed digit length - 80ms */
95 #define AST_MIN_DTMF_DURATION 80
97 /*! Minimum amount of time between the end of the last digit and the beginning
98 * of a new one - 45ms */
99 #define AST_MIN_DTMF_GAP 45
101 /*! \brief List of channel drivers */
103 const struct ast_channel_tech *tech;
104 AST_LIST_ENTRY(chanlist) list;
107 /*! \brief the list of registered channel types */
108 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
110 /*! \brief the list of channels we have. Note that the lock for this list is used for
111 both the channels list and the backends list. */
112 static AST_RWLIST_HEAD_STATIC(channels, ast_channel);
114 /*! \brief map AST_CAUSE's to readable string representations
118 const struct ast_cause {
123 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
124 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
125 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
126 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
127 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
128 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
129 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
130 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
131 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
132 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
133 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
134 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
135 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
136 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
137 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
138 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
139 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
140 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
141 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
142 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
143 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
144 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
145 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
146 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
147 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
148 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
149 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
150 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
151 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
152 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
153 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
154 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
155 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
156 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
157 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
158 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
159 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
160 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
161 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
162 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
163 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
164 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
165 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
166 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
169 struct ast_variable *ast_channeltype_list(void)
172 struct ast_variable *var=NULL, *prev = NULL;
173 AST_LIST_TRAVERSE(&backends, cl, list) {
175 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
178 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
185 /*! \brief Show channel types - CLI command */
186 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
188 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
194 e->command = "core show channeltypes";
196 "Usage: core show channeltypes\n"
197 " Lists available channel types registered in your\n"
198 " Asterisk server.\n";
205 return CLI_SHOWUSAGE;
207 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
208 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
210 if (AST_RWLIST_RDLOCK(&channels)) {
211 ast_log(LOG_WARNING, "Unable to lock channel list\n");
215 AST_LIST_TRAVERSE(&backends, cl, list) {
216 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
217 (cl->tech->devicestate) ? "yes" : "no",
218 (cl->tech->indicate) ? "yes" : "no",
219 (cl->tech->transfer) ? "yes" : "no");
223 AST_RWLIST_UNLOCK(&channels);
225 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
232 static char *complete_channeltypes(struct ast_cli_args *a)
242 wordlen = strlen(a->word);
244 AST_LIST_TRAVERSE(&backends, cl, list) {
245 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
246 ret = ast_strdup(cl->tech->type);
254 /*! \brief Show details about a channel driver - CLI command */
255 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
257 struct chanlist *cl = NULL;
261 e->command = "core show channeltype";
263 "Usage: core show channeltype <name>\n"
264 " Show details about the specified channel type, <name>.\n";
267 return complete_channeltypes(a);
271 return CLI_SHOWUSAGE;
273 if (AST_RWLIST_RDLOCK(&channels)) {
274 ast_log(LOG_WARNING, "Unable to lock channel list\n");
278 AST_LIST_TRAVERSE(&backends, cl, list) {
279 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
285 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
286 AST_RWLIST_UNLOCK(&channels);
291 "-- Info about channel driver: %s --\n"
292 " Device State: %s\n"
295 " Capabilities: %d\n"
299 " Image Support: %s\n"
300 " Text Support: %s\n",
302 (cl->tech->devicestate) ? "yes" : "no",
303 (cl->tech->indicate) ? "yes" : "no",
304 (cl->tech->transfer) ? "yes" : "no",
305 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
306 (cl->tech->send_digit_begin) ? "yes" : "no",
307 (cl->tech->send_digit_end) ? "yes" : "no",
308 (cl->tech->send_html) ? "yes" : "no",
309 (cl->tech->send_image) ? "yes" : "no",
310 (cl->tech->send_text) ? "yes" : "no"
314 AST_RWLIST_UNLOCK(&channels);
318 static struct ast_cli_entry cli_channel[] = {
319 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
320 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
323 /*! \brief Checks to see if a channel is needing hang up */
324 int ast_check_hangup(struct ast_channel *chan)
326 if (chan->_softhangup) /* yes if soft hangup flag set */
328 if (!chan->tech_pvt) /* yes if no technology private data */
330 if (!chan->whentohangup) /* no if no hangup scheduled */
332 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
334 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
338 static int ast_check_hangup_locked(struct ast_channel *chan)
341 ast_channel_lock(chan);
342 res = ast_check_hangup(chan);
343 ast_channel_unlock(chan);
347 /*! \brief Initiate system shutdown */
348 void ast_begin_shutdown(int hangup)
350 struct ast_channel *c;
353 AST_RWLIST_RDLOCK(&channels);
354 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
355 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
356 AST_RWLIST_UNLOCK(&channels);
360 /*! \brief returns number of active/allocated channels */
361 int ast_active_channels(void)
363 struct ast_channel *c;
365 AST_RWLIST_RDLOCK(&channels);
366 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
368 AST_RWLIST_UNLOCK(&channels);
372 /*! \brief Cancel a shutdown in progress */
373 void ast_cancel_shutdown(void)
378 /*! \brief Returns non-zero if Asterisk is being shut down */
379 int ast_shutting_down(void)
381 return shutting_down;
384 /*! \brief Set when to hangup channel */
385 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
387 chan->whentohangup = offset ? time(NULL) + offset : 0;
388 ast_queue_frame(chan, &ast_null_frame);
392 /*! \brief Compare a offset with when to hangup channel */
393 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
397 if (!chan->whentohangup)
398 return (offset == 0) ? 0 : -1;
400 if (!offset) /* XXX why is this special? */
403 whentohangup = offset + time(NULL);
405 if (chan->whentohangup < whentohangup)
407 else if (chan->whentohangup == whentohangup)
413 /*! \brief Register a new telephony channel in Asterisk */
414 int ast_channel_register(const struct ast_channel_tech *tech)
416 struct chanlist *chan;
418 AST_RWLIST_WRLOCK(&channels);
420 AST_LIST_TRAVERSE(&backends, chan, list) {
421 if (!strcasecmp(tech->type, chan->tech->type)) {
422 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
423 AST_RWLIST_UNLOCK(&channels);
428 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
429 AST_RWLIST_UNLOCK(&channels);
433 AST_LIST_INSERT_HEAD(&backends, chan, list);
435 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
437 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
439 AST_RWLIST_UNLOCK(&channels);
443 /*! \brief Unregister channel driver */
444 void ast_channel_unregister(const struct ast_channel_tech *tech)
446 struct chanlist *chan;
448 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
450 AST_RWLIST_WRLOCK(&channels);
452 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
453 if (chan->tech == tech) {
454 AST_LIST_REMOVE_CURRENT(list);
456 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
460 AST_LIST_TRAVERSE_SAFE_END;
462 AST_RWLIST_UNLOCK(&channels);
465 /*! \brief Get handle to channel driver based on name */
466 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
468 struct chanlist *chanls;
469 const struct ast_channel_tech *ret = NULL;
471 if (AST_RWLIST_RDLOCK(&channels)) {
472 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
476 AST_LIST_TRAVERSE(&backends, chanls, list) {
477 if (!strcasecmp(name, chanls->tech->type)) {
483 AST_RWLIST_UNLOCK(&channels);
488 /*! \brief Gives the string form of a given hangup cause */
489 const char *ast_cause2str(int cause)
493 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
494 if (causes[x].cause == cause)
495 return causes[x].desc;
501 /*! \brief Convert a symbolic hangup cause to number */
502 int ast_str2cause(const char *name)
506 for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
507 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
508 return causes[x].cause;
513 /*! \brief Gives the string form of a given channel state.
514 \note This function is not reentrant.
516 const char *ast_state2str(enum ast_channel_state state)
523 case AST_STATE_RESERVED:
525 case AST_STATE_OFFHOOK:
527 case AST_STATE_DIALING:
531 case AST_STATE_RINGING:
537 case AST_STATE_DIALING_OFFHOOK:
538 return "Dialing Offhook";
539 case AST_STATE_PRERING:
542 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
544 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
549 /*! \brief Gives the string form of a given transfer capability */
550 char *ast_transfercapability2str(int transfercapability)
552 switch (transfercapability) {
553 case AST_TRANS_CAP_SPEECH:
555 case AST_TRANS_CAP_DIGITAL:
557 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
558 return "RESTRICTED_DIGITAL";
559 case AST_TRANS_CAP_3_1K_AUDIO:
561 case AST_TRANS_CAP_DIGITAL_W_TONES:
562 return "DIGITAL_W_TONES";
563 case AST_TRANS_CAP_VIDEO:
570 /*! \brief Pick the best audio codec */
571 int ast_best_codec(int fmts)
573 /* This just our opinion, expressed in code. We are asked to choose
574 the best codec to use, given no information */
576 static const int prefs[] =
578 /*! Okay, ulaw is used by all telephony equipment, so start with it */
580 /*! Unless of course, you're a silly European, so then prefer ALAW */
582 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
584 /*! Okay, well, signed linear is easy to translate into other stuff */
585 AST_FORMAT_SLINEAR16,
587 /*! G.726 is standard ADPCM, in RFC3551 packing order */
589 /*! G.726 is standard ADPCM, in AAL2 packing order */
590 AST_FORMAT_G726_AAL2,
591 /*! ADPCM has great sound quality and is still pretty easy to translate */
593 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
594 translate and sounds pretty good */
596 /*! iLBC is not too bad */
598 /*! Speex is free, but computationally more expensive than GSM */
600 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
603 /*! G.729a is faster than 723 and slightly less expensive */
605 /*! Down to G.723.1 which is proprietary but at least designed for voice */
609 /* Strip out video */
610 fmts &= AST_FORMAT_AUDIO_MASK;
612 /* Find the first preferred codec in the format given */
613 for (x = 0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++) {
618 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
623 static const struct ast_channel_tech null_tech = {
625 .description = "Null channel (should not see this)",
628 /*! \brief Create a new channel structure */
629 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num, const char *cid_name, const char *acctcode, const char *exten, const char *context, const int amaflag, const char *name_fmt, ...)
631 struct ast_channel *tmp;
634 struct varshead *headp;
637 /* If shutting down, don't allocate any new channels */
639 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
643 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
646 if (!(tmp->sched = sched_context_create())) {
647 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
652 if ((ast_string_field_init(tmp, 128))) {
653 sched_context_destroy(tmp->sched);
659 tmp->epfd = epoll_create(25);
662 for (x = 0; x < AST_MAX_FDS; x++) {
665 tmp->epfd_data[x] = NULL;
670 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
671 if (tmp->timingfd > -1) {
672 /* Check if timing interface supports new
675 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
683 if (pipe(tmp->alertpipe)) {
684 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
686 if (tmp->timingfd > -1)
687 close(tmp->timingfd);
689 sched_context_destroy(tmp->sched);
690 ast_string_field_free_memory(tmp);
694 flags = fcntl(tmp->alertpipe[0], F_GETFL);
695 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
696 flags = fcntl(tmp->alertpipe[1], F_GETFL);
697 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
699 } else /* Make sure we've got it done right if they don't */
700 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
702 /* Always watch the alertpipe */
703 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
704 /* And timing pipe */
705 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
706 ast_string_field_set(tmp, name, "**Unknown**");
713 tmp->fin = global_fin;
714 tmp->fout = global_fout;
716 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
717 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
718 ast_atomic_fetchadd_int(&uniqueint, 1));
720 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
721 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
724 tmp->cid.cid_name = ast_strdup(cid_name);
725 tmp->cid.cid_num = ast_strdup(cid_num);
727 if (!ast_strlen_zero(name_fmt)) {
728 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
729 * And they all use slightly different formats for their name string.
730 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
731 * This means, that the stringfields must have a routine that takes the va_lists directly, and
732 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
733 * This new function was written so this can be accomplished.
735 va_start(ap1, name_fmt);
736 va_start(ap2, name_fmt);
737 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
742 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
744 /* These 4 variables need to be set up for the cdr_init() to work right */
746 tmp->amaflags = amaflag;
748 tmp->amaflags = ast_default_amaflags;
750 if (!ast_strlen_zero(acctcode))
751 ast_string_field_set(tmp, accountcode, acctcode);
753 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
755 if (!ast_strlen_zero(context))
756 ast_copy_string(tmp->context, context, sizeof(tmp->context));
758 strcpy(tmp->context, "default");
760 if (!ast_strlen_zero(exten))
761 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
763 strcpy(tmp->exten, "s");
767 tmp->cdr = ast_cdr_alloc();
768 ast_cdr_init(tmp->cdr, tmp);
769 ast_cdr_start(tmp->cdr);
771 headp = &tmp->varshead;
772 AST_LIST_HEAD_INIT_NOLOCK(headp);
774 ast_mutex_init(&tmp->lock_dont_use);
776 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
778 ast_string_field_set(tmp, language, defaultlanguage);
780 tmp->tech = &null_tech;
782 AST_RWLIST_WRLOCK(&channels);
783 AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
784 AST_RWLIST_UNLOCK(&channels);
787 * and now, since the channel structure is built, and has its name, let's
788 * call the manager event generator with this Newchannel event. This is the
789 * proper and correct place to make this call, but you sure do have to pass
790 * a lot of data into this func to do it here!
792 if (!ast_strlen_zero(name_fmt)) {
793 manager_event(EVENT_FLAG_CALL, "Newchannel",
795 "ChannelState: %d\r\n"
796 "ChannelStateDesc: %s\r\n"
797 "CallerIDNum: %s\r\n"
798 "CallerIDName: %s\r\n"
799 "AccountCode: %s\r\n"
803 ast_state2str(state),
813 /*! \brief Queue an outgoing media frame */
814 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
817 struct ast_frame *cur;
821 /* Build us a copy and free the original one */
822 if (!(f = ast_frdup(fin))) {
823 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
826 ast_channel_lock(chan);
828 /* See if the last frame on the queue is a hangup, if so don't queue anything */
829 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
831 ast_channel_unlock(chan);
835 /* Count how many frames exist on the queue */
836 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
840 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
841 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
842 if (fin->frametype != AST_FRAME_VOICE) {
843 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
846 ast_debug(1, "Dropping voice to exceptionally long queue on %s\n", chan->name);
848 ast_channel_unlock(chan);
852 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
853 if (chan->alertpipe[1] > -1) {
854 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
855 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
856 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
858 } else if (chan->timingfd > -1) {
859 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
861 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
862 pthread_kill(chan->blocker, SIGURG);
864 ast_channel_unlock(chan);
868 /*! \brief Queue a hangup frame for channel */
869 int ast_queue_hangup(struct ast_channel *chan)
871 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
872 /* Yeah, let's not change a lock-critical value without locking */
873 if (!ast_channel_trylock(chan)) {
874 chan->_softhangup |= AST_SOFTHANGUP_DEV;
875 ast_channel_unlock(chan);
877 return ast_queue_frame(chan, &f);
880 /*! \brief Queue a control frame */
881 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
883 struct ast_frame f = { AST_FRAME_CONTROL, };
885 f.subclass = control;
887 return ast_queue_frame(chan, &f);
890 /*! \brief Queue a control frame with payload */
891 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
892 const void *data, size_t datalen)
894 struct ast_frame f = { AST_FRAME_CONTROL, };
896 f.subclass = control;
897 f.data = (void *) data;
900 return ast_queue_frame(chan, &f);
903 /*! \brief Set defer DTMF flag on channel */
904 int ast_channel_defer_dtmf(struct ast_channel *chan)
909 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
910 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
915 /*! \brief Unset defer DTMF flag on channel */
916 void ast_channel_undefer_dtmf(struct ast_channel *chan)
919 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
923 * \brief Helper function to find channels.
925 * It supports these modes:
927 * prev != NULL : get channel next in list after prev
928 * name != NULL : get channel with matching name
929 * name != NULL && namelen != 0 : get channel whose name starts with prefix
930 * exten != NULL : get channel whose exten or macroexten matches
931 * context != NULL && exten != NULL : get channel whose context or macrocontext
933 * It returns with the channel's lock held. If getting the individual lock fails,
934 * unlock and retry quickly up to 10 times, then give up.
936 * \note XXX Note that this code has cost O(N) because of the need to verify
937 * that the object is still on the global list.
939 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
940 * can only be done with the lock held or someone could delete the
941 * object while we work on it. This causes some ugliness in the code.
942 * Note that removing the first ast_log() may be harmful, as it would
943 * shorten the retry period and possibly cause failures.
944 * We should definitely go for a better scheme that is deadlock-free.
946 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
947 const char *name, const int namelen,
948 const char *context, const char *exten)
950 const char *msg = prev ? "deadlock" : "initial deadlock";
952 struct ast_channel *c;
953 const struct ast_channel *_prev = prev;
955 for (retries = 0; retries < 10; retries++) {
957 AST_RWLIST_RDLOCK(&channels);
958 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
960 if (prev) { /* look for next item */
961 if (c != prev) /* not this one */
963 /* found, prepare to return c->next */
964 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
965 /* If prev was the last item on the channel list, then we just
966 * want to return NULL, instead of trying to deref NULL in the
970 /* We want prev to be NULL in case we end up doing more searching through
971 * the channel list to find the channel (ie: name searching). If we didn't
972 * set this to NULL the logic would just blow up
973 * XXX Need a better explanation for this ...
976 if (name) { /* want match by name */
977 if ((!namelen && strcasecmp(c->name, name) && strcmp(c->uniqueid, name)) ||
978 (namelen && strncasecmp(c->name, name, namelen)))
979 continue; /* name match failed */
981 if (context && strcasecmp(c->context, context) &&
982 strcasecmp(c->macrocontext, context))
983 continue; /* context match failed */
984 if (strcasecmp(c->exten, exten) &&
985 strcasecmp(c->macroexten, exten))
986 continue; /* exten match failed */
988 /* if we get here, c points to the desired record */
991 /* exit if chan not found or mutex acquired successfully */
992 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
993 done = c == NULL || ast_channel_trylock(c) == 0;
995 ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
997 /* We are about to fail due to a deadlock, so report this
998 * while we still have the list lock.
1000 ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
1001 /* As we have deadlocked, we will skip this channel and
1002 * see if there is another match.
1003 * NOTE: No point doing this for a full-name match,
1004 * as there can be no more matches.
1006 if (!(name && !namelen)) {
1012 AST_RWLIST_UNLOCK(&channels);
1015 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1016 * starting from the beginning of the list we can restore our saved pointer to the previous
1017 * channel and start from there.
1020 usleep(1); /* give other threads a chance before retrying */
1026 /*! \brief Browse channels in use */
1027 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1029 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1032 /*! \brief Get channel by name and lock it */
1033 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1035 return channel_find_locked(NULL, name, 0, NULL, NULL);
1038 /*! \brief Get channel by name prefix and lock it */
1039 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1041 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1044 /*! \brief Get next channel by name prefix and lock it */
1045 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1048 return channel_find_locked(chan, name, namelen, NULL, NULL);
1051 /*! \brief Get channel by exten (and optionally context) and lock it */
1052 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1054 return channel_find_locked(NULL, NULL, 0, context, exten);
1057 /*! \brief Get next channel by exten (and optionally context) and lock it */
1058 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1059 const char *context)
1061 return channel_find_locked(chan, NULL, 0, context, exten);
1064 /*! \brief Wait, look for hangups and condition arg */
1065 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1067 struct ast_frame *f;
1070 if (cond && ((*cond)(data) == 0))
1072 ms = ast_waitfor(chan, ms);
1085 /*! \brief Wait, look for hangups */
1086 int ast_safe_sleep(struct ast_channel *chan, int ms)
1088 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1091 static void free_cid(struct ast_callerid *cid)
1094 ast_free(cid->cid_dnid);
1096 ast_free(cid->cid_num);
1098 ast_free(cid->cid_name);
1100 ast_free(cid->cid_ani);
1102 ast_free(cid->cid_rdnis);
1103 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1106 /*! \brief Free a channel structure */
1107 void ast_channel_free(struct ast_channel *chan)
1113 struct ast_var_t *vardata;
1114 struct ast_frame *f;
1115 struct varshead *headp;
1116 struct ast_datastore *datastore = NULL;
1117 char name[AST_CHANNEL_NAME];
1119 headp=&chan->varshead;
1121 AST_RWLIST_WRLOCK(&channels);
1122 if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1123 AST_RWLIST_UNLOCK(&channels);
1124 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1126 /* Lock and unlock the channel just to be sure nobody
1127 has it locked still */
1128 ast_channel_lock(chan);
1129 ast_channel_unlock(chan);
1130 if (chan->tech_pvt) {
1131 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1132 ast_free(chan->tech_pvt);
1136 sched_context_destroy(chan->sched);
1138 ast_copy_string(name, chan->name, sizeof(name));
1140 /* Stop monitoring */
1142 chan->monitor->stop( chan, 0 );
1144 /* If there is native format music-on-hold state, free it */
1145 if (chan->music_state)
1146 ast_moh_cleanup(chan);
1148 /* Free translators */
1149 if (chan->readtrans)
1150 ast_translator_free_path(chan->readtrans);
1151 if (chan->writetrans)
1152 ast_translator_free_path(chan->writetrans);
1154 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1155 free_cid(&chan->cid);
1156 ast_mutex_destroy(&chan->lock_dont_use);
1157 /* Close pipes if appropriate */
1158 if ((fd = chan->alertpipe[0]) > -1)
1160 if ((fd = chan->alertpipe[1]) > -1)
1162 if ((fd = chan->timingfd) > -1)
1165 for (i = 0; i < AST_MAX_FDS; i++) {
1166 if (chan->epfd_data[i])
1167 free(chan->epfd_data[i]);
1171 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1174 /* Get rid of each of the data stores on the channel */
1175 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1176 /* Free the data store */
1177 ast_channel_datastore_free(datastore);
1178 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1180 /* loop over the variables list, freeing all data and deleting list items */
1181 /* no need to lock the list, as the channel is already locked */
1183 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1184 ast_var_delete(vardata);
1186 ast_app_group_discard(chan);
1188 /* Destroy the jitterbuffer */
1189 ast_jb_destroy(chan);
1191 ast_string_field_free_memory(chan);
1193 AST_RWLIST_UNLOCK(&channels);
1195 ast_device_state_changed_literal(name);
1198 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1200 struct ast_datastore *datastore = NULL;
1202 /* Make sure we at least have type so we can identify this */
1207 /* Allocate memory for datastore and clear it */
1208 datastore = ast_calloc(1, sizeof(*datastore));
1213 datastore->info = info;
1215 datastore->uid = ast_strdup(uid);
1220 int ast_channel_datastore_free(struct ast_datastore *datastore)
1224 /* Using the destroy function (if present) destroy the data */
1225 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1226 datastore->info->destroy(datastore->data);
1227 datastore->data = NULL;
1230 /* Free allocated UID memory */
1231 if (datastore->uid != NULL) {
1232 ast_free((void *) datastore->uid);
1233 datastore->uid = NULL;
1236 /* Finally free memory used by ourselves */
1237 ast_free(datastore);
1242 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1244 struct ast_datastore *datastore = NULL, *datastore2;
1246 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1247 if (datastore->inheritance > 0) {
1248 datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1250 datastore2->data = datastore->info->duplicate(datastore->data);
1251 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1252 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1259 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1263 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1268 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1270 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1273 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1275 struct ast_datastore *datastore = NULL;
1280 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1281 if (datastore->info == info) {
1282 if (uid != NULL && datastore->uid != NULL) {
1283 if (!strcasecmp(uid, datastore->uid)) {
1284 /* Matched by type AND uid */
1288 /* Matched by type at least */
1293 AST_LIST_TRAVERSE_SAFE_END
1298 /*! Set the file descriptor on the channel */
1299 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
1302 struct epoll_event ev;
1303 struct ast_epoll_data *aed = NULL;
1305 if (chan->fds[which] > -1) {
1306 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
1307 aed = chan->epfd_data[which];
1310 /* If this new fd is valid, add it to the epoll */
1312 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
1315 chan->epfd_data[which] = aed;
1319 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1321 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
1323 /* We don't have to keep around this epoll data structure now */
1325 chan->epfd_data[which] = NULL;
1328 chan->fds[which] = fd;
1332 /*! Add a channel to an optimized waitfor */
1333 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
1336 struct epoll_event ev;
1339 if (chan0->epfd == -1)
1342 /* Iterate through the file descriptors on chan1, adding them to chan0 */
1343 for (i = 0; i < AST_MAX_FDS; i++) {
1344 if (chan1->fds[i] == -1)
1346 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1347 ev.data.ptr = chan1->epfd_data[i];
1348 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
1355 /*! Delete a channel from an optimized waitfor */
1356 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
1359 struct epoll_event ev;
1362 if (chan0->epfd == -1)
1365 for (i = 0; i < AST_MAX_FDS; i++) {
1366 if (chan1->fds[i] == -1)
1368 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
1375 /*! \brief Softly hangup a channel, don't lock */
1376 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1378 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1379 /* Inform channel driver that we need to be hung up, if it cares */
1380 chan->_softhangup |= cause;
1381 ast_queue_frame(chan, &ast_null_frame);
1382 /* Interrupt any poll call or such */
1383 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1384 pthread_kill(chan->blocker, SIGURG);
1388 /*! \brief Softly hangup a channel, lock */
1389 int ast_softhangup(struct ast_channel *chan, int cause)
1392 ast_channel_lock(chan);
1393 res = ast_softhangup_nolock(chan, cause);
1394 ast_channel_unlock(chan);
1398 static void free_translation(struct ast_channel *clone)
1400 if (clone->writetrans)
1401 ast_translator_free_path(clone->writetrans);
1402 if (clone->readtrans)
1403 ast_translator_free_path(clone->readtrans);
1404 clone->writetrans = NULL;
1405 clone->readtrans = NULL;
1406 clone->rawwriteformat = clone->nativeformats;
1407 clone->rawreadformat = clone->nativeformats;
1410 /*! \brief Hangup a channel */
1411 int ast_hangup(struct ast_channel *chan)
1414 struct ast_cdr *cdr = NULL;
1416 /* Don't actually hang up a channel that will masquerade as someone else, or
1417 if someone is going to masquerade as us */
1418 ast_channel_lock(chan);
1420 if (chan->audiohooks) {
1421 ast_audiohook_detach_list(chan->audiohooks);
1422 chan->audiohooks = NULL;
1425 ast_autoservice_stop(chan);
1428 if (ast_do_masquerade(chan))
1429 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1433 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1434 ast_channel_unlock(chan);
1437 /* If this channel is one which will be masqueraded into something,
1438 mark it as a zombie already, so we know to free it later */
1440 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1441 ast_channel_unlock(chan);
1444 free_translation(chan);
1445 /* Close audio stream */
1447 ast_closestream(chan->stream);
1448 chan->stream = NULL;
1450 /* Close video stream */
1451 if (chan->vstream) {
1452 ast_closestream(chan->vstream);
1453 chan->vstream = NULL;
1456 sched_context_destroy(chan->sched);
1460 if (chan->generatordata) /* Clear any tone stuff remaining */
1461 if (chan->generator && chan->generator->release)
1462 chan->generator->release(chan, chan->generatordata);
1463 chan->generatordata = NULL;
1464 chan->generator = NULL;
1465 if (chan->cdr) { /* End the CDR if it hasn't already */
1466 ast_cdr_end(chan->cdr);
1470 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1471 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1472 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1473 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1476 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1477 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1478 if (chan->tech->hangup)
1479 res = chan->tech->hangup(chan);
1481 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1484 ast_channel_unlock(chan);
1485 manager_event(EVENT_FLAG_CALL, "Hangup",
1488 "CallerIDNum: %s\r\n"
1489 "CallerIDName: %s\r\n"
1491 "Cause-txt: %s\r\n",
1494 S_OR(chan->cid.cid_num, "<unknown>"),
1495 S_OR(chan->cid.cid_name, "<unknown>"),
1497 ast_cause2str(chan->hangupcause)
1499 ast_channel_free(chan);
1502 ast_cdr_detach(cdr);
1507 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1511 ast_channel_lock(chan);
1513 /* You can't answer an outbound call */
1514 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1515 ast_channel_unlock(chan);
1519 /* Stop if we're a zombie or need a soft hangup */
1520 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1521 ast_channel_unlock(chan);
1525 switch (chan->_state) {
1526 case AST_STATE_RINGING:
1527 case AST_STATE_RING:
1528 if (chan->tech->answer)
1529 res = chan->tech->answer(chan);
1530 ast_setstate(chan, AST_STATE_UP);
1531 ast_cdr_answer(chan->cdr);
1532 ast_channel_unlock(chan);
1534 ast_safe_sleep(chan, delay);
1538 ast_cdr_answer(chan->cdr);
1543 chan->visible_indication = 0;
1544 ast_channel_unlock(chan);
1549 int ast_answer(struct ast_channel *chan)
1551 return __ast_answer(chan, 500);
1554 void ast_deactivate_generator(struct ast_channel *chan)
1556 ast_channel_lock(chan);
1557 if (chan->generatordata) {
1558 if (chan->generator && chan->generator->release)
1559 chan->generator->release(chan, chan->generatordata);
1560 chan->generatordata = NULL;
1561 chan->generator = NULL;
1562 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
1563 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1564 ast_settimeout(chan, 0, NULL, NULL);
1566 ast_channel_unlock(chan);
1569 static int generator_force(const void *data)
1571 /* Called if generator doesn't have data */
1574 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1575 struct ast_channel *chan = (struct ast_channel *)data;
1576 tmp = chan->generatordata;
1577 chan->generatordata = NULL;
1578 generate = chan->generator->generate;
1579 res = generate(chan, tmp, 0, 160);
1580 chan->generatordata = tmp;
1582 ast_debug(1, "Auto-deactivating generator\n");
1583 ast_deactivate_generator(chan);
1588 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1592 ast_channel_lock(chan);
1594 if (chan->generatordata) {
1595 if (chan->generator && chan->generator->release)
1596 chan->generator->release(chan, chan->generatordata);
1597 chan->generatordata = NULL;
1601 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1606 ast_settimeout(chan, 160, generator_force, chan);
1607 chan->generator = gen;
1610 ast_channel_unlock(chan);
1615 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1616 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1619 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1623 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1625 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
1626 int *exception, int *outfd, int *ms)
1628 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1629 int *exception, int *outfd, int *ms)
1632 struct timeval start = { 0 , 0 };
1633 struct pollfd *pfds;
1639 long whentohangup = 0, diff;
1640 struct ast_channel *winner = NULL;
1646 sz = n * AST_MAX_FDS + nfds;
1647 pfds = alloca(sizeof(*pfds) * sz);
1648 fdmap = alloca(sizeof(*fdmap) * sz);
1655 /* Perform any pending masquerades */
1656 for (x = 0; x < n; x++) {
1657 ast_channel_lock(c[x]);
1658 if (c[x]->masq && ast_do_masquerade(c[x])) {
1659 ast_log(LOG_WARNING, "Masquerade failed\n");
1661 ast_channel_unlock(c[x]);
1664 if (c[x]->whentohangup) {
1667 diff = c[x]->whentohangup - now;
1669 /* Should already be hungup */
1670 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1671 ast_channel_unlock(c[x]);
1674 if (!whentohangup || (diff < whentohangup))
1675 whentohangup = diff;
1677 ast_channel_unlock(c[x]);
1679 /* Wait full interval */
1682 rms = whentohangup * 1000; /* timeout in milliseconds */
1683 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1687 * Build the pollfd array, putting the channels' fds first,
1688 * followed by individual fds. Order is important because
1689 * individual fd's must have priority over channel fds.
1692 for (x = 0; x < n; x++) {
1693 for (y = 0; y < AST_MAX_FDS; y++) {
1694 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1695 fdmap[max].chan = x; /* channel x is linked to this pfds */
1696 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1698 CHECK_BLOCKING(c[x]);
1700 /* Add the individual fds */
1701 for (x = 0; x < nfds; x++) {
1702 fdmap[max].chan = -1;
1703 max += ast_add_fd(&pfds[max], fds[x]);
1707 start = ast_tvnow();
1709 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1714 res = poll(pfds, max, kbrms);
1717 } while (!res && (rms > 0));
1719 res = poll(pfds, max, rms);
1721 for (x = 0; x < n; x++)
1722 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1723 if (res < 0) { /* Simulate a timeout if we were interrupted */
1728 if (whentohangup) { /* if we have a timeout, check who expired */
1730 for (x = 0; x < n; x++) {
1731 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1732 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1738 if (res == 0) { /* no fd ready, reset timeout and done */
1739 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1743 * Then check if any channel or fd has a pending event.
1744 * Remember to check channels first and fds last, as they
1745 * must have priority on setting 'winner'
1747 for (x = 0; x < max; x++) {
1748 res = pfds[x].revents;
1751 if (fdmap[x].chan >= 0) { /* this is a channel */
1752 winner = c[fdmap[x].chan]; /* override previous winners */
1754 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1756 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1757 winner->fdno = fdmap[x].fdno;
1758 } else { /* this is an fd */
1760 *outfd = pfds[x].fd;
1762 *exception = (res & POLLPRI) ? -1 : 0;
1767 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1775 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
1777 struct timeval start = { 0 , 0 };
1779 struct epoll_event ev[1];
1780 long whentohangup = 0, rms = *ms;
1782 struct ast_channel *winner = NULL;
1783 struct ast_epoll_data *aed = NULL;
1785 ast_channel_lock(chan);
1787 /* See if this channel needs to be masqueraded */
1788 if (chan->masq && ast_do_masquerade(chan)) {
1789 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
1791 ast_channel_unlock(chan);
1795 /* Figure out their timeout */
1796 if (chan->whentohangup) {
1798 if ((whentohangup = chan->whentohangup - now) < 1) {
1799 /* They should already be hungup! */
1800 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1801 ast_channel_unlock(chan);
1804 /* If this value is smaller then the current one... make it priority */
1805 whentohangup *= 1000;
1806 if (rms > whentohangup)
1810 ast_channel_unlock(chan);
1812 /* Time to make this channel block... */
1813 CHECK_BLOCKING(chan);
1816 start = ast_tvnow();
1818 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
1819 res = epoll_wait(chan->epfd, ev, 1, rms);
1822 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1824 /* Simulate a timeout if we were interrupted */
1831 /* If this channel has a timeout see if it expired */
1832 if (chan->whentohangup) {
1834 if (now >= chan->whentohangup) {
1835 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1840 /* No fd ready, reset timeout and be done for now */
1846 /* See what events are pending */
1847 aed = ev[0].data.ptr;
1848 chan->fdno = aed->which;
1849 if (ev[0].events & EPOLLPRI)
1850 ast_set_flag(chan, AST_FLAG_EXCEPTION);
1852 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1855 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1863 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
1865 struct timeval start = { 0 , 0 };
1867 struct epoll_event ev[25] = { { 0, } };
1868 long whentohangup = 0, diff, rms = *ms;
1870 struct ast_channel *winner = NULL;
1872 for (i = 0; i < n; i++) {
1873 ast_channel_lock(c[i]);
1874 if (c[i]->masq && ast_do_masquerade(c[i])) {
1875 ast_log(LOG_WARNING, "Masquerade failed\n");
1877 ast_channel_unlock(c[i]);
1880 if (c[i]->whentohangup) {
1883 if ((diff = c[i]->whentohangup - now) < 1) {
1884 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1885 ast_channel_unlock(c[i]);
1888 if (!whentohangup || (diff < whentohangup))
1889 whentohangup = diff;
1891 ast_channel_unlock(c[i]);
1892 CHECK_BLOCKING(c[i]);
1897 rms = whentohangup * 1000;
1898 if (*ms >= 0 && *ms < rms)
1903 start = ast_tvnow();
1905 res = epoll_wait(c[0]->epfd, ev, 25, rms);
1907 for (i = 0; i < n; i++)
1908 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
1918 for (i = 0; i < n; i++) {
1919 if (c[i]->whentohangup && now >= c[i]->whentohangup) {
1920 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1932 for (i = 0; i < res; i++) {
1933 struct ast_epoll_data *aed = ev[i].data.ptr;
1935 if (!ev[i].events || !aed)
1939 if (ev[i].events & EPOLLPRI)
1940 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1942 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1943 winner->fdno = aed->which;
1947 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1955 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1956 int *exception, int *outfd, int *ms)
1958 /* Clear all provided values in one place. */
1964 /* If no epoll file descriptor is available resort to classic nandfds */
1965 if (!n || nfds || c[0]->epfd == -1)
1966 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
1967 else if (!nfds && n == 1)
1968 return ast_waitfor_nandfds_simple(c[0], ms);
1970 return ast_waitfor_nandfds_complex(c, n, ms);
1974 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1976 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1979 int ast_waitfor(struct ast_channel *c, int ms)
1981 int oldms = ms; /* -1 if no timeout */
1983 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1984 if ((ms < 0) && (oldms < 0))
1989 /* XXX never to be called with ms = -1 */
1990 int ast_waitfordigit(struct ast_channel *c, int ms)
1992 return ast_waitfordigit_full(c, ms, -1, -1);
1995 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
1999 if (c->timingfd > -1) {
2004 ast_debug(1, "Scheduling timer at %d sample intervals\n", samples);
2005 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
2006 c->timingfunc = func;
2007 c->timingdata = data;
2013 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2015 /* Stop if we're a zombie or need a soft hangup */
2016 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2019 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2020 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2022 /* Wait for a digit, no more than ms milliseconds total. */
2025 struct ast_channel *rchan;
2029 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2031 if (!rchan && outfd < 0 && ms) {
2032 if (errno == 0 || errno == EINTR)
2034 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2035 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2037 } else if (outfd > -1) {
2038 /* The FD we were watching has something waiting */
2039 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2040 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2044 struct ast_frame *f = ast_read(c);
2048 switch (f->frametype) {
2049 case AST_FRAME_DTMF_BEGIN:
2051 case AST_FRAME_DTMF_END:
2054 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2056 case AST_FRAME_CONTROL:
2057 switch (f->subclass) {
2058 case AST_CONTROL_HANGUP:
2060 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2062 case AST_CONTROL_RINGING:
2063 case AST_CONTROL_ANSWER:
2067 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2071 case AST_FRAME_VOICE:
2072 /* Write audio if appropriate */
2074 write(audiofd, f->data, f->datalen);
2083 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2085 return 0; /* Time is up */
2088 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2090 manager_event(EVENT_FLAG_DTMF,
2098 chan->name, chan->uniqueid, digit, direction, begin, end);
2101 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2103 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2104 void *tmp = chan->generatordata;
2107 if (chan->timingfunc) {
2108 if (option_debug > 1)
2109 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2110 ast_settimeout(chan, 0, NULL, NULL);
2113 chan->generatordata = NULL; /* reset, to let writes go through */
2114 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2115 chan->generatordata = tmp;
2117 if (option_debug > 1)
2118 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2119 ast_deactivate_generator(chan);
2122 } else if (f->frametype == AST_FRAME_CNG) {
2123 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2124 if (option_debug > 1)
2125 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2126 ast_settimeout(chan, 160, generator_force, chan);
2131 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2133 struct ast_frame *f = NULL; /* the return value */
2138 /* this function is very long so make sure there is only one return
2139 * point at the end (there are only two exceptions to this).
2141 while(ast_channel_trylock(chan)) {
2143 /*cannot goto done since the channel is not locked*/
2144 return &ast_null_frame;
2149 if (ast_do_masquerade(chan))
2150 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2152 f = &ast_null_frame;
2156 /* Stop if we're a zombie or need a soft hangup */
2157 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2158 if (chan->generator)
2159 ast_deactivate_generator(chan);
2162 prestate = chan->_state;
2164 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2165 !ast_strlen_zero(chan->dtmfq) &&
2166 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2167 /* We have DTMF that has been deferred. Return it now */
2168 chan->dtmff.subclass = chan->dtmfq[0];
2169 /* Drop first digit from the buffer */
2170 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2172 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2173 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2174 chan->dtmff.frametype = AST_FRAME_DTMF_END;
2176 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %d queued on %s\n", f->subclass, AST_DEFAULT_EMULATE_DTMF_DURATION, chan->name);
2177 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2178 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2179 chan->emulate_dtmf_digit = f->subclass;
2180 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2182 chan->dtmf_tv = ast_tvnow();
2186 /* Read and ignore anything on the alertpipe, but read only
2187 one sizeof(blah) per frame that we send from it */
2188 if (chan->alertpipe[0] > -1)
2189 read(chan->alertpipe[0], &blah, sizeof(blah));
2192 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2195 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2197 /* IF we can't get event, assume it's an expired as-per the old interface */
2198 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2200 blah = ZT_EVENT_TIMER_EXPIRED;
2202 if (blah == ZT_EVENT_TIMER_PING) {
2203 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2204 /* Acknowledge PONG unless we need it again */
2205 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2206 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2209 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2210 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2211 if (chan->timingfunc) {
2212 chan->timingfunc(chan->timingdata);
2215 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2216 chan->timingdata = NULL;
2218 ast_channel_unlock(chan);
2219 /* cannot 'goto done' because the channel is already unlocked */
2220 return &ast_null_frame;
2222 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2225 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2226 /* if the AST_GENERATOR_FD is set, call the generator with args
2227 * set to -1 so it can do whatever it needs to.
2229 void *tmp = chan->generatordata;
2230 chan->generatordata = NULL; /* reset to let ast_write get through */
2231 chan->generator->generate(chan, tmp, -1, -1);
2232 chan->generatordata = tmp;
2233 f = &ast_null_frame;
2237 /* Check for pending read queue */
2238 if (!AST_LIST_EMPTY(&chan->readq)) {
2239 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2240 /* Interpret hangup and return NULL */
2241 /* XXX why not the same for frames from the channel ? */
2242 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2247 chan->blocker = pthread_self();
2248 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2249 if (chan->tech->exception)
2250 f = chan->tech->exception(chan);
2252 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2253 f = &ast_null_frame;
2255 /* Clear the exception flag */
2256 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2257 } else if (chan->tech->read)
2258 f = chan->tech->read(chan);
2260 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2264 /* if the channel driver returned more than one frame, stuff the excess
2265 into the readq for the next ast_read call (note that we can safely assume
2266 that the readq is empty, because otherwise we would not have called into
2267 the channel driver and f would be only a single frame)
2269 if (AST_LIST_NEXT(f, frame_list)) {
2270 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2271 AST_LIST_NEXT(f, frame_list) = NULL;
2274 switch (f->frametype) {
2275 case AST_FRAME_CONTROL:
2276 if (f->subclass == AST_CONTROL_ANSWER) {
2277 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2278 ast_debug(1, "Ignoring answer on an inbound call!\n");
2280 f = &ast_null_frame;
2281 } else if (prestate == AST_STATE_UP) {
2282 ast_debug(1, "Dropping duplicate answer!\n");
2284 f = &ast_null_frame;
2286 /* Answer the CDR */
2287 ast_setstate(chan, AST_STATE_UP);
2288 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2289 to keep from throwing off the basic order of the universe,
2290 we will try to keep this cdr from getting posted. */
2291 chan->cdr = ast_cdr_alloc();
2292 ast_cdr_init(chan->cdr, chan);
2293 ast_cdr_start(chan->cdr);
2296 ast_cdr_answer(chan->cdr);
2300 case AST_FRAME_DTMF_END:
2301 send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2302 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2303 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2304 * However, only let emulation be forced if the other end cares about BEGIN frames */
2305 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2306 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2307 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2308 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2309 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2311 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2313 f = &ast_null_frame;
2314 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2315 if (!ast_tvzero(chan->dtmf_tv) &&
2316 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2317 /* If it hasn't been long enough, defer this digit */
2318 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2319 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2320 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2322 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2324 f = &ast_null_frame;
2326 /* There was no begin, turn this into a begin and send the end later */
2327 f->frametype = AST_FRAME_DTMF_BEGIN;
2328 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2329 chan->emulate_dtmf_digit = f->subclass;
2330 chan->dtmf_tv = ast_tvnow();
2332 if (f->len > AST_MIN_DTMF_DURATION)
2333 chan->emulate_dtmf_duration = f->len;
2335 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2337 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2338 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2340 if (chan->audiohooks) {
2341 struct ast_frame *old_frame = f;
2343 * \todo XXX It is possible to write a digit to the audiohook twice
2344 * if the digit was originally read while the channel was in autoservice. */
2345 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2347 ast_frfree(old_frame);
2350 struct timeval now = ast_tvnow();
2351 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2352 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2353 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2355 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2356 } else if (!f->len) {
2357 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2358 f->len = AST_MIN_DTMF_DURATION;
2360 if (f->len < AST_MIN_DTMF_DURATION) {
2361 ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f->subclass, f->len, AST_MIN_DTMF_DURATION, chan->name);
2362 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2363 chan->emulate_dtmf_digit = f->subclass;
2364 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2366 f = &ast_null_frame;
2368 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2369 chan->dtmf_tv = now;
2371 if (chan->audiohooks) {
2372 struct ast_frame *old_frame = f;
2373 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2375 ast_frfree(old_frame);
2379 case AST_FRAME_DTMF_BEGIN:
2380 send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2381 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2382 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY) ||
2383 (!ast_tvzero(chan->dtmf_tv) &&
2384 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2385 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2387 f = &ast_null_frame;
2389 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2390 chan->dtmf_tv = ast_tvnow();
2391 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2394 case AST_FRAME_NULL:
2395 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2396 struct timeval now = ast_tvnow();
2397 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2398 chan->emulate_dtmf_duration = 0;
2401 f->frametype = AST_FRAME_DTMF_END;
2402 f->subclass = chan->emulate_dtmf_digit;
2403 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2404 chan->dtmf_tv = now;
2405 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2406 chan->emulate_dtmf_digit = 0;
2407 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2411 case AST_FRAME_VOICE:
2412 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2413 * is reached , because we want to make sure we pass at least one
2414 * voice frame through before starting the next digit, to ensure a gap
2415 * between DTMF digits. */
2416 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2417 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2418 chan->emulate_dtmf_digit = 0;
2421 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2423 ast_read_generator_actions(chan, f);
2425 f = &ast_null_frame;
2428 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2429 struct timeval now = ast_tvnow();
2430 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2431 chan->emulate_dtmf_duration = 0;
2434 f->frametype = AST_FRAME_DTMF_END;
2435 f->subclass = chan->emulate_dtmf_digit;
2436 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2437 chan->dtmf_tv = now;
2438 if (chan->audiohooks) {
2439 struct ast_frame *old_frame = f;
2440 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2442 ast_frfree(old_frame);
2444 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2446 /* Drop voice frames while we're still in the middle of the digit */
2448 f = &ast_null_frame;
2450 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2451 /* This frame can't be from the current native formats -- drop it on the
2453 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2454 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2456 f = &ast_null_frame;
2457 } else if ((f->frametype == AST_FRAME_VOICE)) {
2458 /* Send frame to audiohooks if present */
2459 if (chan->audiohooks) {
2460 struct ast_frame *old_frame = f;
2461 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2463 ast_frfree(old_frame);
2465 if (chan->monitor && chan->monitor->read_stream ) {
2466 /* XXX what does this do ? */
2467 #ifndef MONITOR_CONSTANT_DELAY
2468 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2470 jump = chan->outsmpl - chan->insmpl;
2471 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2472 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2473 chan->insmpl += jump + f->samples;
2475 chan->insmpl+= f->samples;
2477 int jump = chan->outsmpl - chan->insmpl;
2478 if (jump - MONITOR_DELAY >= 0) {
2479 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2480 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2481 chan->insmpl += jump;
2483 chan->insmpl += f->samples;
2485 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2486 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2487 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2491 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2492 f = &ast_null_frame;
2494 /* Run generator sitting on the line if timing device not available
2495 * and synchronous generation of outgoing frames is necessary */
2496 ast_read_generator_actions(chan, f);
2499 /* Just pass it on! */
2503 /* Make sure we always return NULL in the future */
2504 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2505 if (chan->generator)
2506 ast_deactivate_generator(chan);
2507 /* End the CDR if appropriate */
2509 ast_cdr_end(chan->cdr);
2512 /* High bit prints debugging */
2513 if (chan->fin & DEBUGCHAN_FLAG)
2514 ast_frame_dump(chan->name, f, "<<");
2515 chan->fin = FRAMECOUNT_INC(chan->fin);
2518 if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2519 chan->generator->digit(chan, f->subclass);
2521 ast_channel_unlock(chan);
2525 int ast_internal_timing_enabled(struct ast_channel *chan)
2527 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2528 ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2532 struct ast_frame *ast_read(struct ast_channel *chan)
2534 return __ast_read(chan, 0);
2537 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2539 return __ast_read(chan, 1);
2542 int ast_indicate(struct ast_channel *chan, int condition)
2544 return ast_indicate_data(chan, condition, NULL, 0);
2547 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2551 ast_channel_lock(chan);
2552 /* Stop if we're a zombie or need a soft hangup */
2553 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2554 ast_channel_unlock(chan);
2557 if (chan->tech->indicate)
2558 res = chan->tech->indicate(chan, condition, data, datalen);
2559 ast_channel_unlock(chan);
2560 if (!chan->tech->indicate || res) {
2562 * Device does not support (that) indication, lets fake
2563 * it by doing our own tone generation. (PM2002)
2566 ast_playtones_stop(chan);
2568 const struct ind_tone_zone_sound *ts = NULL;
2569 switch (condition) {
2570 case AST_CONTROL_RINGING:
2571 ts = ast_get_indication_tone(chan->zone, "ring");
2573 case AST_CONTROL_BUSY:
2574 ts = ast_get_indication_tone(chan->zone, "busy");
2576 case AST_CONTROL_CONGESTION:
2577 ts = ast_get_indication_tone(chan->zone, "congestion");
2580 if (ts && ts->data[0]) {
2581 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2582 ast_playtones_start(chan,0,ts->data, 1);
2584 chan->visible_indication = condition;
2585 } else if (condition == AST_CONTROL_PROGRESS) {
2586 /* ast_playtones_stop(chan); */
2587 } else if (condition == AST_CONTROL_PROCEEDING) {
2588 /* Do nothing, really */
2589 } else if (condition == AST_CONTROL_HOLD) {
2590 /* Do nothing.... */
2591 } else if (condition == AST_CONTROL_UNHOLD) {
2592 /* Do nothing.... */
2593 } else if (condition == AST_CONTROL_VIDUPDATE) {
2594 /* Do nothing.... */
2597 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2602 chan->visible_indication = condition;
2607 int ast_recvchar(struct ast_channel *chan, int timeout)
2610 char *buf = ast_recvtext(chan, timeout);
2612 return -1; /* error or timeout */
2613 c = *(unsigned char *)buf;
2618 char *ast_recvtext(struct ast_channel *chan, int timeout)
2624 struct ast_frame *f;
2625 if (ast_check_hangup(chan))
2627 res = ast_waitfor(chan, timeout);
2628 if (res <= 0) /* timeout or error */
2630 timeout = res; /* update timeout */
2633 break; /* no frame */
2634 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2635 done = 1; /* force a break */
2636 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2637 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2645 int ast_sendtext(struct ast_channel *chan, const char *text)
2648 /* Stop if we're a zombie or need a soft hangup */
2649 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2651 CHECK_BLOCKING(chan);
2652 if (chan->tech->send_text)
2653 res = chan->tech->send_text(chan, text);
2654 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2658 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2660 /* Device does not support DTMF tones, lets fake
2661 * it by doing our own generation. */
2662 static const char* dtmf_tones[] = {
2681 if (!chan->tech->send_digit_begin)
2684 if (!chan->tech->send_digit_begin(chan, digit))
2687 if (digit >= '0' && digit <='9')
2688 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2689 else if (digit >= 'A' && digit <= 'D')
2690 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2691 else if (digit == '*')
2692 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2693 else if (digit == '#')
2694 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2697 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2703 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2707 if (chan->tech->send_digit_end)
2708 res = chan->tech->send_digit_end(chan, digit, duration);
2710 if (res && chan->generator)
2711 ast_playtones_stop(chan);
2716 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
2718 if (chan->tech->send_digit_begin) {
2719 ast_senddigit_begin(chan, digit);
2720 ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2723 return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2726 int ast_prod(struct ast_channel *chan)
2728 struct ast_frame a = { AST_FRAME_VOICE };
2731 /* Send an empty audio frame to get things moving */
2732 if (chan->_state != AST_STATE_UP) {
2733 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2734 a.subclass = chan->rawwriteformat;
2735 a.data = nothing + AST_FRIENDLY_OFFSET;
2737 if (ast_write(chan, &a))
2738 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2743 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2746 if (!chan->tech->write_video)
2748 res = ast_write(chan, fr);
2754 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2757 struct ast_frame *f = NULL, *f2 = NULL;
2760 /*Deadlock avoidance*/
2761 while(ast_channel_trylock(chan)) {
2762 /*cannot goto done since the channel is not locked*/
2764 ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
2769 /* Stop if we're a zombie or need a soft hangup */
2770 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2773 /* Handle any pending masquerades */
2774 if (chan->masq && ast_do_masquerade(chan)) {
2775 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2779 res = 0; /* XXX explain, why 0 ? */
2782 if (chan->generatordata) {
2783 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2784 ast_deactivate_generator(chan);
2786 if (fr->frametype == AST_FRAME_DTMF_END) {
2787 /* There is a generator running while we're in the middle of a digit.
2788 * It's probably inband DTMF, so go ahead and pass it so it can
2789 * stop the generator */
2790 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2791 ast_channel_unlock(chan);
2792 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2793 ast_channel_lock(chan);
2794 CHECK_BLOCKING(chan);
2795 } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2796 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2797 res = (chan->tech->indicate == NULL) ? 0 :
2798 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2800 res = 0; /* XXX explain, why 0 ? */
2804 /* High bit prints debugging */
2805 if (chan->fout & DEBUGCHAN_FLAG)
2806 ast_frame_dump(chan->name, fr, ">>");
2807 CHECK_BLOCKING(chan);
2808 switch (fr->frametype) {
2809 case AST_FRAME_CONTROL:
2810 res = (chan->tech->indicate == NULL) ? 0 :
2811 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2813 case AST_FRAME_DTMF_BEGIN:
2814 if (chan->audiohooks) {
2815 struct ast_frame *old_frame = fr;
2816 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2817 if (old_frame != fr)
2820 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
2821 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2822 ast_channel_unlock(chan);
2823 res = ast_senddigit_begin(chan, fr->subclass);
2824 ast_channel_lock(chan);
2825 CHECK_BLOCKING(chan);
2827 case AST_FRAME_DTMF_END:
2828 if (chan->audiohooks) {
2829 struct ast_frame *old_frame = fr;
2830 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2831 if (old_frame != fr)
2834 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
2835 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2836 ast_channel_unlock(chan);
2837 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2838 ast_channel_lock(chan);
2839 CHECK_BLOCKING(chan);
2841 case AST_FRAME_TEXT:
2842 if (fr->subclass == AST_FORMAT_T140) {
2843 res = (chan->tech->write_text == NULL) ? 0 :
2844 chan->tech->write_text(chan, fr);
2846 res = (chan->tech->send_text == NULL) ? 0 :
2847 chan->tech->send_text(chan, (char *) fr->data);
2850 case AST_FRAME_HTML:
2851 res = (chan->tech->send_html == NULL) ? 0 :
2852 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2854 case AST_FRAME_VIDEO:
2855 /* XXX Handle translation of video codecs one day XXX */
2856 res = (chan->tech->write_video == NULL) ? 0 :
2857 chan->tech->write_video(chan, fr);
2859 case AST_FRAME_MODEM:
2860 res = (chan->tech->write == NULL) ? 0 :
2861 chan->tech->write(chan, fr);
2863 case AST_FRAME_VOICE:
2864 if (chan->tech->write == NULL)
2865 break; /*! \todo XXX should return 0 maybe ? */
2867 /* If audiohooks are present, write the frame out */
2868 if (chan->audiohooks) {
2869 struct ast_frame *old_frame = fr;
2870 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2871 if (old_frame != fr)
2875 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2876 if (fr->subclass == chan->rawwriteformat)
2879 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2886 /* If Monitor is running on this channel, then we have to write frames out there too */
2887 if (chan->monitor && chan->monitor->write_stream) {
2888 /* XXX must explain this code */
2889 #ifndef MONITOR_CONSTANT_DELAY
2890 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2892 jump = chan->insmpl - chan->outsmpl;
2893 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2894 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2895 chan->outsmpl += jump + f->samples;
2897 chan->outsmpl += f->samples;
2899 int jump = chan->insmpl - chan->outsmpl;
2900 if (jump - MONITOR_DELAY >= 0) {
2901 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2902 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2903 chan->outsmpl += jump;
2905 chan->outsmpl += f->samples;
2907 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2908 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2909 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2914 res = chan->tech->write(chan,f);
2918 case AST_FRAME_NULL:
2924 /* At this point, fr is the incoming frame and f is NULL. Channels do
2925 * not expect to get NULL as a frame pointer and will segfault. Hence,
2926 * we output the original frame passed in. */
2927 res = chan->tech->write(chan, fr);
2935 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2936 /* Consider a write failure to force a soft hangup */
2938 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2940 chan->fout = FRAMECOUNT_INC(chan->fout);
2943 ast_channel_unlock(chan);
2947 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2948 struct ast_trans_pvt **trans, const int direction)
2953 /* Make sure we only consider audio */
2954 fmt &= AST_FORMAT_AUDIO_MASK;
2956 native = chan->nativeformats;
2957 /* Find a translation path from the native format to one of the desired formats */
2960 res = ast_translator_best_choice(&fmt, &native);
2963 res = ast_translator_best_choice(&native, &fmt);
2966 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2967 ast_getformatname(native), ast_getformatname(fmt));
2971 /* Now we have a good choice for both. */
2972 ast_channel_lock(chan);
2974 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2975 /* the channel is already in these formats, so nothing to do */
2976 ast_channel_unlock(chan);
2980 *rawformat = native;
2981 /* User perspective is fmt */
2983 /* Free any read translation we have right now */
2985 ast_translator_free_path(*trans);
2986 /* Build a translation path from the raw format to the desired format */
2989 *trans = ast_translator_build_path(*format, *rawformat);
2992 *trans = ast_translator_build_path(*rawformat, *format);
2993 ast_channel_unlock(chan);
2994 ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
2995 direction ? "write" : "read", ast_getformatname(fmt));
2999 int ast_set_read_format(struct ast_channel *chan, int fmt)
3001 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
3002 &chan->readtrans, 0);
3005 int ast_set_write_format(struct ast_channel *chan, int fmt)
3007 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
3008 &chan->writetrans, 1);
3011 const char *ast_channel_reason2str(int reason)
3013 switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
3016 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
3017 case AST_CONTROL_HANGUP:
3019 case AST_CONTROL_RING:
3020 return "Local Ring";
3021 case AST_CONTROL_RINGING:
3022 return "Remote end Ringing";
3023 case AST_CONTROL_ANSWER:
3024 return "Remote end has Answered";
3025 case AST_CONTROL_BUSY:
3026 return "Remote end is Busy";
3027 case AST_CONTROL_CONGESTION:
3028 return "Congestion (circuits busy)";
3030 return "Unknown Reason!!";
3034 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)
3038 struct ast_channel *chan;
3040 int last_subclass = 0;
3045 outstate = &dummy_outstate; /* make outstate always a valid pointer */
3047 chan = ast_request(type, format, data, &cause);
3049 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
3050 /* compute error and return */
3051 if (cause == AST_CAUSE_BUSY)
3052 *outstate = AST_CONTROL_BUSY;
3053 else if (cause == AST_CAUSE_CONGESTION)
3054 *outstate = AST_CONTROL_CONGESTION;
3060 ast_set_variables(chan, oh->vars);
3061 /* XXX why is this necessary, for the parent_channel perhaps ? */
3062 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
3063 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
3064 if (oh->parent_channel) {
3065 ast_channel_inherit_variables(oh->parent_channel, chan);
3066 ast_channel_datastore_inherit(oh->parent_channel, chan);
3069 ast_cdr_setaccount(chan, oh->account);
3071 ast_set_callerid(chan, cid_num, cid_name, cid_num);
3075 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
3076 to keep from throwing off the basic order of the universe,
3077 we will try to keep this cdr from getting posted. */
3078 chan->cdr = ast_cdr_alloc();
3079 ast_cdr_init(chan->cdr, chan);
3080 ast_cdr_start(chan->cdr);
3082 if (ast_call(chan, data, 0)) { /* ast_call failed... */
3083 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
3085 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
3086 while (timeout && chan->_state != AST_STATE_UP) {
3087 struct ast_frame *f;
3088 res = ast_waitfor(chan, timeout);
3089 if (res <= 0) /* error, timeout, or done */
3095 *outstate = AST_CONTROL_HANGUP;
3099 if (f->frametype == AST_FRAME_CONTROL) {
3100 switch (f->subclass) {
3101 case AST_CONTROL_RINGING: /* record but keep going */
3102 *outstate = f->subclass;
3105 case AST_CONTROL_BUSY:
3106 case AST_CONTROL_CONGESTION:
3107 case AST_CONTROL_ANSWER:
3108 *outstate = f->subclass;
3109 timeout = 0; /* trick to force exit from the while() */
3113 case AST_CONTROL_PROGRESS:
3114 case AST_CONTROL_PROCEEDING:
3115 case AST_CONTROL_HOLD:
3116 case AST_CONTROL_UNHOLD:
3117 case AST_CONTROL_VIDUPDATE:
3118 case -1: /* Ignore -- just stopping indications */
3122 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
3124 last_subclass = f->subclass;
3132 if (!ast_strlen_zero(oh->context))
3133 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
3134 if (!ast_strlen_zero(oh->exten))
3135 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
3137 chan->priority = oh->priority;
3139 if (chan->_state == AST_STATE_UP)
3140 *outstate = AST_CONTROL_ANSWER;
3143 if ( AST_CONTROL_RINGING == last_subclass )
3144 chan->hangupcause = AST_CAUSE_NO_ANSWER;
3145 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
3146 ast_cdr_init(chan->cdr, chan);
3149 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
3150 ast_cdr_setapp(chan->cdr,"Dial",tmp);
3151 ast_cdr_update(chan);
3152 ast_cdr_start(chan->cdr);
3153 ast_cdr_end(chan->cdr);
3154 /* If the cause wasn't handled properly */
3155 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
3156 ast_cdr_failed(chan->cdr);
3164 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
3166 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
3169 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
3171 struct chanlist *chan;
3172 struct ast_channel *c;
3177 int videoformat = format & AST_FORMAT_VIDEO_MASK;
3178 int textformat = format & AST_FORMAT_TEXT_MASK;
3182 *cause = AST_CAUSE_NOTDEFINED;
3184 if (AST_RWLIST_RDLOCK(&channels)) {
3185 ast_log(LOG_WARNING, "Unable to lock channel list\n");
3189 AST_LIST_TRAVERSE(&backends, chan, list) {
3190 if (strcasecmp(type, chan->tech->type))
3193 capabilities = chan->tech->capabilities;
3194 fmt = format & AST_FORMAT_AUDIO_MASK;
3195 res = ast_translator_best_choice(&fmt, &capabilities);
3197 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native 0x%x) to 0x%x\n", type, chan->tech->capabilities, format);
3198 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3199 AST_RWLIST_UNLOCK(&channels);
3202 AST_RWLIST_UNLOCK(&channels);
3203 if (!chan->tech->requester)
3206 if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, data, cause)))
3209 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3213 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
3214 *cause = AST_CAUSE_NOSUCHDRIVER;
3215 AST_RWLIST_UNLOCK(&channels);
3220 int ast_call(struct ast_channel *chan, char *addr, int timeout)
3222 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3223 If the remote end does not answer within the timeout, then do NOT hang up, but
3226 /* Stop if we're a zombie or need a soft hangup */
3227 ast_channel_lock(chan);
3228 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3229 if (chan->tech->call)
3230 res = chan->tech->call(chan, addr, timeout);
3231 ast_set_flag(chan, AST_FLAG_OUTGOING);
3233 ast_channel_unlock(chan);
3238 \brief Transfer a call to dest, if the channel supports transfer
3242 \arg the manager interface
3244 int ast_transfer(struct ast_channel *chan, char *dest)
3248 /* Stop if we're a zombie or need a soft hangup */
3249 ast_channel_lock(chan);
3250 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3251 if (chan->tech->transfer) {
3252 res = chan->tech->transfer(chan, dest);
3258 ast_channel_unlock(chan);
3262 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3264 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3267 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3269 int pos = 0; /* index in the buffer where we accumulate digits */
3272 /* Stop if we're a zombie or need a soft hangup */
3273 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3280 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3284 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3286 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3298 if (!strchr(enders, d))
3300 if (strchr(enders, d) || (pos >= len)) {
3310 int ast_channel_supports_html(struct ast_channel *chan)
3312 return (chan->tech->send_html) ? 1 : 0;
3315 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3317 if (chan->tech->send_html)
3318 return chan->tech->send_html(chan, subclass, data, datalen);
3322 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3324 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3327 /*! \brief Set up translation from one channel to another */
3328 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
3333 if (from->readformat == to->writeformat && from->writeformat == to->readformat) {
3334 /* Already compatible! Moving on ... */
3338 /* Set up translation from the 'from' channel to the 'to' channel */
3339 src = from->nativeformats;
3340 dst = to->nativeformats;
3341 if (ast_translator_best_choice(&dst, &src) < 0) {
3342 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", from->name, src, to->name, dst);
3346 /* if the best path is not 'pass through', then
3347 transcoding is needed; if desired, force transcode path
3348 to use SLINEAR between channels, but only if there is
3349 no direct conversion available */
3350 if ((src != dst) && ast_opt_transcode_via_slin &&
3351 (ast_translate_path_steps(dst, src) != 1))
3352 dst = AST_FORMAT_SLINEAR;
3353 if (ast_set_read_format(from, dst) < 0) {
3354 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", from->name, dst);
3357 if (ast_set_write_format(to, dst) < 0) {
3358 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", to->name, dst);
3364 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3366 /* Some callers do not check return code, and we must try to set all call legs correctly */
3369 /* Set up translation from the chan to the peer */
3370 rc = ast_channel_make_compatible_helper(chan, peer);
3375 /* Set up translation from the peer to the chan */
3376 rc = ast_channel_make_compatible_helper(peer, chan);
3381 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3384 struct ast_channel *final_orig, *final_clone, *base;
3387 final_orig = original;
3388 final_clone = clone;
3390 ast_channel_lock(original);
3391 while (ast_channel_trylock(clone)) {
3392 ast_channel_unlock(original);
3394 ast_channel_lock(original);
3397 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3398 and if so, we don't really want to masquerade it, but its proxy */
3399 if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
3400 final_orig = original->_bridge;
3402 if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)) && (clone->_bridge->_bridge != clone))
3403 final_clone = clone->_bridge;
3405 if (final_clone->tech->get_base_channel && (base = final_clone->tech->get_base_channel(final_clone))) {
3409 if ((final_orig != original) || (final_clone != clone)) {
3410 /* Lots and lots of deadlock avoidance. The main one we're competing with
3411 * is ast_write(), which locks channels recursively, when working with a
3413 if (ast_channel_trylock(final_orig)) {
3414 ast_channel_unlock(clone);
3415 ast_channel_unlock(original);
3418 if (ast_channel_trylock(final_clone)) {
3419 ast_channel_unlock(final_orig);
3420 ast_channel_unlock(clone);
3421 ast_channel_unlock(original);
3424 ast_channel_unlock(clone);
3425 ast_channel_unlock(original);
3426 original = final_orig;
3427 clone = final_clone;
3430 if (original == clone) {
3431 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3432 ast_channel_unlock(clone);
3433 ast_channel_unlock(original);
3437 ast_debug(1, "Planning to masquerade channel %s into the structure of %s\n",
3438 clone->name, original->name);
3439 if (original->masq) {
3440 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3441 original->masq->name, original->name);
3442 } else if (clone->masqr) {
3443 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3444 clone->name, clone->masqr->name);
3446 original->masq = clone;
3447 clone->masqr = original;
3448 ast_queue_frame(original, &ast_null_frame);
3449 ast_queue_frame(clone, &ast_null_frame);
3450 ast_debug(1, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3454 ast_channel_unlock(clone);
3455 ast_channel_unlock(original);
3460 void ast_change_name(struct ast_channel *chan, char *newname)
3462 manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3463 ast_string_field_set(chan, name, newname);
3466 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3468 struct ast_var_t *current, *newvar;
3469 const char *varname;
3471 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3474 varname = ast_var_full_name(current);
3478 if (varname[0] == '_') {
3480 if (varname[1] == '_')
3486 newvar = ast_var_assign(&varname[1], ast_var_value(current));
3488 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3489 ast_debug(1, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3493 newvar = ast_var_assign(varname, ast_var_value(current));
3495 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3496 ast_debug(1, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3500 ast_debug(1, "Not copying variable %s.\n", ast_var_name(current));
3507 \brief Clone channel variables from 'clone' channel into 'original' channel
3509 All variables except those related to app_groupcount are cloned.
3510 Variables are actually _removed_ from 'clone' channel, presumably
3511 because it will subsequently be destroyed.
3513 \note Assumes locks will be in place on both channels when called.
3515 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3517 struct ast_var_t *current, *newvar;
3518 /* Append variables from clone channel into original channel */
3519 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3520 if (AST_LIST_FIRST(&clone->varshead))
3521 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3523 /* then, dup the varshead list into the clone */
3525 AST_LIST_TRAVERSE(&original->varshead, current, entries) {
3526 newvar = ast_var_assign(current->name, current->value);
3528 AST_LIST_INSERT_TAIL(&clone->varshead, newvar, entries);
3533 \brief Masquerade a channel
3535 \note Assumes channel will be locked when called
3537 int ast_do_masquerade(struct ast_channel *original)
3542 struct ast_frame *cur;
3543 const struct ast_channel_tech *t;
3545 struct ast_callerid tmpcid;
3546 struct ast_channel *clone = original->masq;
3547 struct ast_cdr *cdr;
3548 int rformat = original->readformat;
3549 int wformat = original->writeformat;
3550 char newn[AST_CHANNEL_NAME];
3551 char orig[AST_CHANNEL_NAME];
3552 char masqn[AST_CHANNEL_NAME];
3553 char zombn[AST_CHANNEL_NAME];
3555 ast_debug(4, "Actually Masquerading %s(%d) into the stru