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 */
38 #include "asterisk/pbx.h"
39 #include "asterisk/frame.h"
40 #include "asterisk/sched.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/musiconhold.h"
43 #include "asterisk/say.h"
44 #include "asterisk/file.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/translate.h"
47 #include "asterisk/manager.h"
48 #include "asterisk/chanvars.h"
49 #include "asterisk/linkedlists.h"
50 #include "asterisk/indications.h"
51 #include "asterisk/monitor.h"
52 #include "asterisk/causes.h"
53 #include "asterisk/callerid.h"
54 #include "asterisk/utils.h"
55 #include "asterisk/lock.h"
56 #include "asterisk/app.h"
57 #include "asterisk/transcap.h"
58 #include "asterisk/devicestate.h"
59 #include "asterisk/sha1.h"
60 #include "asterisk/threadstorage.h"
61 #include "asterisk/slinfactory.h"
62 #include "asterisk/audiohook.h"
63 #include "asterisk/timing.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;
108 /*! \brief Structure to hold channel context backtrace data */
109 struct ast_chan_trace_data {
111 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
114 /*! \brief Structure to save contexts where an ast_chan has been into */
115 struct ast_chan_trace {
116 char context[AST_MAX_CONTEXT];
117 char exten[AST_MAX_EXTENSION];
119 AST_LIST_ENTRY(ast_chan_trace) entry;
123 /*! \brief the list of registered channel types */
124 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
126 /*! \brief the list of channels we have. Note that the lock for this list is used for
127 both the channels list and the backends list. */
128 static AST_RWLIST_HEAD_STATIC(channels, ast_channel);
130 /*! \brief map AST_CAUSE's to readable string representations
134 static const struct {
139 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
140 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
141 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
142 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
143 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
144 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
145 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
146 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
147 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
148 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
149 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
150 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
151 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
152 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
153 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
154 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
155 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
156 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
157 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
158 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
159 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
160 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
161 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
162 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
163 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
164 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
165 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
166 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
167 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
168 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
169 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
170 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
171 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
172 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
173 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
174 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
175 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
176 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
177 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
178 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
179 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
180 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
181 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
182 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
185 struct ast_variable *ast_channeltype_list(void)
188 struct ast_variable *var=NULL, *prev = NULL;
189 AST_LIST_TRAVERSE(&backends, cl, list) {
191 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
194 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
201 /*! \brief Show channel types - CLI command */
202 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
204 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
210 e->command = "core show channeltypes";
212 "Usage: core show channeltypes\n"
213 " Lists available channel types registered in your\n"
214 " Asterisk server.\n";
221 return CLI_SHOWUSAGE;
223 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
224 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
226 AST_RWLIST_RDLOCK(&channels);
228 AST_LIST_TRAVERSE(&backends, cl, list) {
229 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
230 (cl->tech->devicestate) ? "yes" : "no",
231 (cl->tech->indicate) ? "yes" : "no",
232 (cl->tech->transfer) ? "yes" : "no");
236 AST_RWLIST_UNLOCK(&channels);
238 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
245 static char *complete_channeltypes(struct ast_cli_args *a)
255 wordlen = strlen(a->word);
257 AST_LIST_TRAVERSE(&backends, cl, list) {
258 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
259 ret = ast_strdup(cl->tech->type);
267 /*! \brief Show details about a channel driver - CLI command */
268 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
270 struct chanlist *cl = NULL;
274 e->command = "core show channeltype";
276 "Usage: core show channeltype <name>\n"
277 " Show details about the specified channel type, <name>.\n";
280 return complete_channeltypes(a);
284 return CLI_SHOWUSAGE;
286 AST_RWLIST_RDLOCK(&channels);
288 AST_LIST_TRAVERSE(&backends, cl, list) {
289 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
295 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
296 AST_RWLIST_UNLOCK(&channels);
301 "-- Info about channel driver: %s --\n"
302 " Device State: %s\n"
305 " Capabilities: %d\n"
309 " Image Support: %s\n"
310 " Text Support: %s\n",
312 (cl->tech->devicestate) ? "yes" : "no",
313 (cl->tech->indicate) ? "yes" : "no",
314 (cl->tech->transfer) ? "yes" : "no",
315 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
316 (cl->tech->send_digit_begin) ? "yes" : "no",
317 (cl->tech->send_digit_end) ? "yes" : "no",
318 (cl->tech->send_html) ? "yes" : "no",
319 (cl->tech->send_image) ? "yes" : "no",
320 (cl->tech->send_text) ? "yes" : "no"
324 AST_RWLIST_UNLOCK(&channels);
328 static struct ast_cli_entry cli_channel[] = {
329 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
330 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
334 /*! \brief Destructor for the channel trace datastore */
335 static void ast_chan_trace_destroy_cb(void *data)
337 struct ast_chan_trace *trace;
338 struct ast_chan_trace_data *traced = data;
339 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
345 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
346 const struct ast_datastore_info ast_chan_trace_datastore_info = {
348 .destroy = ast_chan_trace_destroy_cb
351 /*! \brief Put the channel backtrace in a string */
352 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
355 struct ast_chan_trace *trace;
356 struct ast_chan_trace_data *traced;
357 struct ast_datastore *store;
359 ast_channel_lock(chan);
360 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
362 ast_channel_unlock(chan);
365 traced = store->data;
367 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
368 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
369 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
375 ast_channel_unlock(chan);
379 /* !\brief Whether or not context tracing is enabled */
380 int ast_channel_trace_is_enabled(struct ast_channel *chan)
382 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
385 return ((struct ast_chan_trace_data *)store->data)->enabled;
388 /*! \brief Update the context backtrace data if tracing is enabled */
389 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
391 struct ast_chan_trace *trace;
392 if (!traced->enabled)
394 /* If the last saved context does not match the current one
395 OR we have not saved any context so far, then save the current context */
396 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) ||
397 (AST_LIST_EMPTY(&traced->trace))) {
398 /* Just do some debug logging */
399 if (AST_LIST_EMPTY(&traced->trace))
400 ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
402 ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
403 /* alloc or bail out */
404 trace = ast_malloc(sizeof(*trace));
407 /* save the current location and store it in the trace list */
408 ast_copy_string(trace->context, chan->context, sizeof(trace->context));
409 ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
410 trace->priority = chan->priority;
411 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
416 /*! \brief Update the context backtrace if tracing is enabled */
417 int ast_channel_trace_update(struct ast_channel *chan)
419 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
422 return ast_channel_trace_data_update(chan, store->data);
425 /*! \brief Enable context tracing in the channel */
426 int ast_channel_trace_enable(struct ast_channel *chan)
428 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
429 struct ast_chan_trace_data *traced;
431 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
434 traced = ast_calloc(1, sizeof(*traced));
436 ast_datastore_free(store);
439 store->data = traced;
440 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
441 ast_channel_datastore_add(chan, store);
443 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
444 ast_channel_trace_data_update(chan, store->data);
448 /*! \brief Disable context tracing in the channel */
449 int ast_channel_trace_disable(struct ast_channel *chan)
451 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
454 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
457 #endif /* CHANNEL_TRACE */
459 /*! \brief Checks to see if a channel is needing hang up */
460 int ast_check_hangup(struct ast_channel *chan)
462 if (chan->_softhangup) /* yes if soft hangup flag set */
464 if (ast_tvzero(chan->whentohangup)) /* no if no hangup scheduled */
466 if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0) /* no if hangup time has not come yet. */
468 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
472 static int ast_check_hangup_locked(struct ast_channel *chan)
475 ast_channel_lock(chan);
476 res = ast_check_hangup(chan);
477 ast_channel_unlock(chan);
481 /*! \brief Initiate system shutdown */
482 void ast_begin_shutdown(int hangup)
484 struct ast_channel *c;
487 AST_RWLIST_RDLOCK(&channels);
488 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
489 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
491 AST_RWLIST_UNLOCK(&channels);
495 /*! \brief returns number of active/allocated channels */
496 int ast_active_channels(void)
498 struct ast_channel *c;
500 AST_RWLIST_RDLOCK(&channels);
501 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
503 AST_RWLIST_UNLOCK(&channels);
507 /*! \brief Cancel a shutdown in progress */
508 void ast_cancel_shutdown(void)
513 /*! \brief Returns non-zero if Asterisk is being shut down */
514 int ast_shutting_down(void)
516 return shutting_down;
519 /*! \brief Set when to hangup channel */
520 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
522 chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
523 ast_queue_frame(chan, &ast_null_frame);
527 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
529 struct timeval when = { offset, };
530 ast_channel_setwhentohangup_tv(chan, when);
533 /*! \brief Compare a offset with when to hangup channel */
534 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
536 struct timeval whentohangup;
538 if (ast_tvzero(chan->whentohangup))
539 return ast_tvzero(offset) ? 0 : -1;
541 if (ast_tvzero(offset))
544 whentohangup = ast_tvadd(offset, ast_tvnow());
546 return ast_tvdiff_ms(whentohangup, chan->whentohangup);
549 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
551 struct timeval when = { offset, };
552 return ast_channel_cmpwhentohangup_tv(chan, when);
555 /*! \brief Register a new telephony channel in Asterisk */
556 int ast_channel_register(const struct ast_channel_tech *tech)
558 struct chanlist *chan;
560 AST_RWLIST_WRLOCK(&channels);
562 AST_LIST_TRAVERSE(&backends, chan, list) {
563 if (!strcasecmp(tech->type, chan->tech->type)) {
564 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
565 AST_RWLIST_UNLOCK(&channels);
570 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
571 AST_RWLIST_UNLOCK(&channels);
575 AST_LIST_INSERT_HEAD(&backends, chan, list);
577 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
579 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
581 AST_RWLIST_UNLOCK(&channels);
585 /*! \brief Unregister channel driver */
586 void ast_channel_unregister(const struct ast_channel_tech *tech)
588 struct chanlist *chan;
590 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
592 AST_RWLIST_WRLOCK(&channels);
594 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
595 if (chan->tech == tech) {
596 AST_LIST_REMOVE_CURRENT(list);
598 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
602 AST_LIST_TRAVERSE_SAFE_END;
604 AST_RWLIST_UNLOCK(&channels);
607 /*! \brief Get handle to channel driver based on name */
608 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
610 struct chanlist *chanls;
611 const struct ast_channel_tech *ret = NULL;
613 AST_RWLIST_RDLOCK(&channels);
615 AST_LIST_TRAVERSE(&backends, chanls, list) {
616 if (!strcasecmp(name, chanls->tech->type)) {
622 AST_RWLIST_UNLOCK(&channels);
627 /*! \brief Gives the string form of a given hangup cause */
628 const char *ast_cause2str(int cause)
632 for (x = 0; x < ARRAY_LEN(causes); x++) {
633 if (causes[x].cause == cause)
634 return causes[x].desc;
640 /*! \brief Convert a symbolic hangup cause to number */
641 int ast_str2cause(const char *name)
645 for (x = 0; x < ARRAY_LEN(causes); x++)
646 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
647 return causes[x].cause;
652 /*! \brief Gives the string form of a given channel state.
653 \note This function is not reentrant.
655 const char *ast_state2str(enum ast_channel_state state)
662 case AST_STATE_RESERVED:
664 case AST_STATE_OFFHOOK:
666 case AST_STATE_DIALING:
670 case AST_STATE_RINGING:
676 case AST_STATE_DIALING_OFFHOOK:
677 return "Dialing Offhook";
678 case AST_STATE_PRERING:
681 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
683 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
688 /*! \brief Gives the string form of a given transfer capability */
689 char *ast_transfercapability2str(int transfercapability)
691 switch (transfercapability) {
692 case AST_TRANS_CAP_SPEECH:
694 case AST_TRANS_CAP_DIGITAL:
696 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
697 return "RESTRICTED_DIGITAL";
698 case AST_TRANS_CAP_3_1K_AUDIO:
700 case AST_TRANS_CAP_DIGITAL_W_TONES:
701 return "DIGITAL_W_TONES";
702 case AST_TRANS_CAP_VIDEO:
709 /*! \brief Pick the best audio codec */
710 int ast_best_codec(int fmts)
712 /* This just our opinion, expressed in code. We are asked to choose
713 the best codec to use, given no information */
715 static const int prefs[] =
717 /*! Okay, ulaw is used by all telephony equipment, so start with it */
719 /*! Unless of course, you're a silly European, so then prefer ALAW */
723 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
725 /*! Okay, well, signed linear is easy to translate into other stuff */
726 AST_FORMAT_SLINEAR16,
728 /*! G.726 is standard ADPCM, in RFC3551 packing order */
730 /*! G.726 is standard ADPCM, in AAL2 packing order */
731 AST_FORMAT_G726_AAL2,
732 /*! ADPCM has great sound quality and is still pretty easy to translate */
734 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
735 translate and sounds pretty good */
737 /*! iLBC is not too bad */
739 /*! Speex is free, but computationally more expensive than GSM */
741 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
744 /*! G.729a is faster than 723 and slightly less expensive */
746 /*! Down to G.723.1 which is proprietary but at least designed for voice */
750 /* Strip out video */
751 fmts &= AST_FORMAT_AUDIO_MASK;
753 /* Find the first preferred codec in the format given */
754 for (x = 0; x < ARRAY_LEN(prefs); x++) {
759 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
764 static const struct ast_channel_tech null_tech = {
766 .description = "Null channel (should not see this)",
769 /*! \brief Create a new channel structure */
770 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, ...)
772 struct ast_channel *tmp;
775 struct varshead *headp;
778 /* If shutting down, don't allocate any new channels */
780 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
784 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
787 if (!(tmp->sched = sched_context_create())) {
788 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
793 if ((ast_string_field_init(tmp, 128))) {
794 sched_context_destroy(tmp->sched);
799 if (!(tmp->cid.cid_name = ast_strdup(cid_name)) || !(tmp->cid.cid_num = ast_strdup(cid_num))) {
800 ast_string_field_free_memory(tmp);
801 sched_context_destroy(tmp->sched);
807 tmp->epfd = epoll_create(25);
810 for (x = 0; x < AST_MAX_FDS; x++) {
813 tmp->epfd_data[x] = NULL;
817 if ((tmp->timer = ast_timer_open())) {
819 tmp->timingfd = ast_timer_fd(tmp->timer);
825 if (pipe(tmp->alertpipe)) {
826 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
829 ast_timer_close(tmp->timer);
832 sched_context_destroy(tmp->sched);
833 ast_string_field_free_memory(tmp);
837 flags = fcntl(tmp->alertpipe[0], F_GETFL);
838 if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
839 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
840 close(tmp->alertpipe[0]);
841 close(tmp->alertpipe[1]);
842 goto alertpipe_failed;
844 flags = fcntl(tmp->alertpipe[1], F_GETFL);
845 if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
846 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
847 close(tmp->alertpipe[0]);
848 close(tmp->alertpipe[1]);
849 goto alertpipe_failed;
852 } else /* Make sure we've got it done right if they don't */
853 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
855 /* Always watch the alertpipe */
856 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
857 /* And timing pipe */
858 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
859 ast_string_field_set(tmp, name, "**Unknown**");
866 tmp->fin = global_fin;
867 tmp->fout = global_fout;
869 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
870 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
871 ast_atomic_fetchadd_int(&uniqueint, 1));
873 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
874 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
877 if (!ast_strlen_zero(name_fmt)) {
878 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
879 * And they all use slightly different formats for their name string.
880 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
881 * This means, that the stringfields must have a routine that takes the va_lists directly, and
882 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
883 * This new function was written so this can be accomplished.
885 va_start(ap1, name_fmt);
886 va_start(ap2, name_fmt);
887 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
892 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
894 /* These 4 variables need to be set up for the cdr_init() to work right */
896 tmp->amaflags = amaflag;
898 tmp->amaflags = ast_default_amaflags;
900 if (!ast_strlen_zero(acctcode))
901 ast_string_field_set(tmp, accountcode, acctcode);
903 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
905 if (!ast_strlen_zero(context))
906 ast_copy_string(tmp->context, context, sizeof(tmp->context));
908 strcpy(tmp->context, "default");
910 if (!ast_strlen_zero(exten))
911 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
913 strcpy(tmp->exten, "s");
917 tmp->cdr = ast_cdr_alloc();
918 ast_cdr_init(tmp->cdr, tmp);
919 ast_cdr_start(tmp->cdr);
921 headp = &tmp->varshead;
922 AST_LIST_HEAD_INIT_NOLOCK(headp);
924 ast_mutex_init(&tmp->lock_dont_use);
926 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
928 ast_string_field_set(tmp, language, defaultlanguage);
930 tmp->tech = &null_tech;
932 AST_RWLIST_WRLOCK(&channels);
933 AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
934 AST_RWLIST_UNLOCK(&channels);
937 * and now, since the channel structure is built, and has its name, let's
938 * call the manager event generator with this Newchannel event. This is the
939 * proper and correct place to make this call, but you sure do have to pass
940 * a lot of data into this func to do it here!
942 if (!ast_strlen_zero(name_fmt)) {
943 manager_event(EVENT_FLAG_CALL, "Newchannel",
945 "ChannelState: %d\r\n"
946 "ChannelStateDesc: %s\r\n"
947 "CallerIDNum: %s\r\n"
948 "CallerIDName: %s\r\n"
949 "AccountCode: %s\r\n"
955 ast_state2str(state),
967 /*! \brief Queue an outgoing media frame */
968 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head)
971 struct ast_frame *cur;
975 /* Build us a copy and free the original one */
976 if (!(f = ast_frdup(fin))) {
980 ast_channel_lock(chan);
982 /* See if the last frame on the queue is a hangup, if so don't queue anything */
983 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
985 ast_channel_unlock(chan);
989 /* Count how many frames exist on the queue */
990 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
994 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
995 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
996 if (fin->frametype != AST_FRAME_VOICE) {
997 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
998 ast_assert(fin->frametype == AST_FRAME_VOICE);
1000 ast_debug(1, "Dropping voice to exceptionally long queue on %s\n", chan->name);
1002 ast_channel_unlock(chan);
1008 AST_LIST_INSERT_HEAD(&chan->readq, f, frame_list);
1010 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
1013 if (chan->alertpipe[1] > -1) {
1014 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah)) {
1015 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
1016 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
1018 } else if (chan->timingfd > -1) {
1019 ast_timer_enable_continuous(chan->timer);
1020 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1021 pthread_kill(chan->blocker, SIGURG);
1024 ast_channel_unlock(chan);
1029 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1031 return __ast_queue_frame(chan, fin, 0);
1034 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1036 return __ast_queue_frame(chan, fin, 1);
1039 /*! \brief Queue a hangup frame for channel */
1040 int ast_queue_hangup(struct ast_channel *chan)
1042 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
1043 /* Yeah, let's not change a lock-critical value without locking */
1044 if (!ast_channel_trylock(chan)) {
1045 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1046 ast_channel_unlock(chan);
1048 return ast_queue_frame(chan, &f);
1051 /*! \brief Queue a hangup frame for channel */
1052 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1054 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
1057 f.data.uint32 = cause;
1059 /* Yeah, let's not change a lock-critical value without locking */
1060 if (!ast_channel_trylock(chan)) {
1061 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1063 f.data.uint32 = chan->hangupcause;
1065 ast_channel_unlock(chan);
1068 return ast_queue_frame(chan, &f);
1071 /*! \brief Queue a control frame */
1072 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1074 struct ast_frame f = { AST_FRAME_CONTROL, };
1076 f.subclass = control;
1078 return ast_queue_frame(chan, &f);
1081 /*! \brief Queue a control frame with payload */
1082 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1083 const void *data, size_t datalen)
1085 struct ast_frame f = { AST_FRAME_CONTROL, };
1087 f.subclass = control;
1088 f.data.ptr = (void *) data;
1089 f.datalen = datalen;
1091 return ast_queue_frame(chan, &f);
1094 /*! \brief Set defer DTMF flag on channel */
1095 int ast_channel_defer_dtmf(struct ast_channel *chan)
1100 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1101 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1106 /*! \brief Unset defer DTMF flag on channel */
1107 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1110 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1114 * \brief Helper function to find channels.
1116 * It supports these modes:
1118 * prev != NULL : get channel next in list after prev
1119 * name != NULL : get channel with matching name
1120 * name != NULL && namelen != 0 : get channel whose name starts with prefix
1121 * exten != NULL : get channel whose exten or macroexten matches
1122 * context != NULL && exten != NULL : get channel whose context or macrocontext
1124 * It returns with the channel's lock held. If getting the individual lock fails,
1125 * unlock and retry quickly up to 10 times, then give up.
1127 * \note XXX Note that this code has cost O(N) because of the need to verify
1128 * that the object is still on the global list.
1130 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
1131 * can only be done with the lock held or someone could delete the
1132 * object while we work on it. This causes some ugliness in the code.
1133 * Note that removing the first ast_log() may be harmful, as it would
1134 * shorten the retry period and possibly cause failures.
1135 * We should definitely go for a better scheme that is deadlock-free.
1137 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
1138 const char *name, const int namelen,
1139 const char *context, const char *exten)
1141 const char *msg = prev ? "deadlock" : "initial deadlock";
1143 struct ast_channel *c;
1144 const struct ast_channel *_prev = prev;
1146 for (retries = 0; retries < 200; retries++) {
1148 /* Reset prev on each retry. See note below for the reason. */
1150 AST_RWLIST_RDLOCK(&channels);
1151 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
1152 if (prev) { /* look for last item, first, before any evaluation */
1153 if (c != prev) /* not this one */
1155 /* found, prepare to return c->next */
1156 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
1158 * We're done searching through the list for the previous item.
1159 * Any item after this point, we want to evaluate for a match.
1160 * If we didn't set prev to NULL here, then we would only
1161 * return matches for the first matching item (since the above
1162 * "if (c != prev)" would not permit any other potential
1163 * matches to reach the additional matching logic, below).
1164 * Instead, it would just iterate until it once again found the
1165 * original match, then iterate down to the end of the list and
1170 if (name) { /* want match by name */
1171 if ((!namelen && strcasecmp(c->name, name) && strcmp(c->uniqueid, name)) ||
1172 (namelen && strncasecmp(c->name, name, namelen)))
1173 continue; /* name match failed */
1175 if (context && strcasecmp(c->context, context) &&
1176 strcasecmp(c->macrocontext, context))
1177 continue; /* context match failed */
1178 if (strcasecmp(c->exten, exten) &&
1179 strcasecmp(c->macroexten, exten))
1180 continue; /* exten match failed */
1182 /* if we get here, c points to the desired record */
1185 /* exit if chan not found or mutex acquired successfully */
1186 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1187 done = c == NULL || ast_channel_trylock(c) == 0;
1189 ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
1190 if (retries == 199) {
1191 /* We are about to fail due to a deadlock, so report this
1192 * while we still have the list lock.
1194 ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
1195 /* As we have deadlocked, we will skip this channel and
1196 * see if there is another match.
1197 * NOTE: No point doing this for a full-name match,
1198 * as there can be no more matches.
1200 if (!(name && !namelen)) {
1206 AST_RWLIST_UNLOCK(&channels);
1209 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1210 * starting from the beginning of the list we can restore our saved pointer to the previous
1211 * channel and start from there.
1214 usleep(1); /* give other threads a chance before retrying */
1220 /*! \brief Browse channels in use */
1221 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1223 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1226 /*! \brief Get channel by name and lock it */
1227 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1229 return channel_find_locked(NULL, name, 0, NULL, NULL);
1232 /*! \brief Get channel by name prefix and lock it */
1233 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1235 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1238 /*! \brief Get next channel by name prefix and lock it */
1239 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1242 return channel_find_locked(chan, name, namelen, NULL, NULL);
1245 /*! \brief Get channel by exten (and optionally context) and lock it */
1246 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1248 return channel_find_locked(NULL, NULL, 0, context, exten);
1251 /*! \brief Get next channel by exten (and optionally context) and lock it */
1252 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1253 const char *context)
1255 return channel_find_locked(chan, NULL, 0, context, exten);
1258 /*! \brief Search for a channel based on the passed channel matching callback (first match) and return it, locked */
1259 struct ast_channel *ast_channel_search_locked(int (*is_match)(struct ast_channel *, void *), void *data)
1261 struct ast_channel *c = NULL;
1263 AST_RWLIST_RDLOCK(&channels);
1264 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
1265 ast_channel_lock(c);
1266 if (is_match(c, data)) {
1269 ast_channel_unlock(c);
1271 AST_RWLIST_UNLOCK(&channels);
1276 /*! \brief Wait, look for hangups and condition arg */
1277 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1279 struct ast_frame *f;
1282 if (cond && ((*cond)(data) == 0))
1284 ms = ast_waitfor(chan, ms);
1297 /*! \brief Wait, look for hangups */
1298 int ast_safe_sleep(struct ast_channel *chan, int ms)
1300 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1303 static void free_cid(struct ast_callerid *cid)
1306 ast_free(cid->cid_dnid);
1308 ast_free(cid->cid_num);
1310 ast_free(cid->cid_name);
1312 ast_free(cid->cid_ani);
1314 ast_free(cid->cid_rdnis);
1315 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1320 * \brief Initialize the given party id structure.
1322 * \param init Party id structure to initialize.
1326 static void ast_party_id_init(struct ast_party_id *init)
1328 init->number = NULL;
1330 init->number_type = 0; /* Unknown */
1331 init->number_presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1336 * \brief Copy the source party id information to the destination party id.
1338 * \param dest Destination party id
1339 * \param src Source party id
1343 static void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1346 /* Don't copy to self */
1351 ast_free(dest->number);
1353 dest->number = ast_strdup(src->number);
1356 ast_free(dest->name);
1358 dest->name = ast_strdup(src->name);
1360 dest->number_type = src->number_type;
1361 dest->number_presentation = src->number_presentation;
1366 * \brief Initialize the given party id structure using the given guide
1367 * for a set update operation.
1370 * The initialization is needed to allow a set operation to know if a
1371 * value needs to be updated. Simple integers need the guide's original
1372 * value in case the set operation is not trying to set a new value.
1373 * String values are simply set to NULL pointers if they are not going
1376 * \param init Party id structure to initialize.
1377 * \param guide Source party id to use as a guide in initializing.
1381 static void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1383 init->number = NULL;
1385 init->number_type = guide->number_type;
1386 init->number_presentation = guide->number_presentation;
1391 * \brief Set the source party id information into the destination party id.
1393 * \param dest Destination party id
1394 * \param src Source party id
1398 static void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src)
1401 /* Don't set to self */
1405 if (src->name && src->name != dest->name) {
1407 ast_free(dest->name);
1409 dest->name = ast_strdup(src->name);
1412 if (src->number && src->number != dest->number) {
1414 ast_free(dest->number);
1416 dest->number = ast_strdup(src->number);
1419 dest->number_type = src->number_type;
1420 dest->number_presentation = src->number_presentation;
1425 * \brief Destroy the party id contents
1427 * \param doomed The party id to destroy.
1431 static void ast_party_id_free(struct ast_party_id *doomed)
1433 if (doomed->number) {
1434 ast_free(doomed->number);
1435 doomed->number = NULL;
1439 ast_free(doomed->name);
1440 doomed->name = NULL;
1444 void ast_party_caller_copy(struct ast_callerid *dest, const struct ast_callerid *src)
1447 /* Don't copy to self */
1452 /* Copy caller-id specific information ONLY from struct ast_callerid */
1455 ast_free(dest->cid_num);
1457 dest->cid_num = ast_strdup(src->cid_num);
1461 ast_free(dest->cid_name);
1463 dest->cid_name = ast_strdup(src->cid_name);
1465 dest->cid_ton = src->cid_ton;
1466 dest->cid_pres = src->cid_pres;
1471 ast_free(dest->cid_ani);
1473 dest->cid_ani = ast_strdup(src->cid_ani);
1475 dest->cid_ani2 = src->cid_ani2;
1479 /* The src and dest parameter types will become struct ast_party_caller ptrs. */
1480 /* This is future code */
1482 ast_party_id_copy(&dest->id, &src->id);
1485 ast_free(dest->ani);
1487 dest->ani = ast_strdup(src->ani);
1489 dest->ani2 = src->ani2;
1493 void ast_party_connected_line_init(struct ast_party_connected_line *init)
1495 ast_party_id_init(&init->id);
1498 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
1501 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
1504 /* Don't copy to self */
1508 ast_party_id_copy(&dest->id, &src->id);
1511 ast_free(dest->ani);
1513 dest->ani = ast_strdup(src->ani);
1515 dest->ani2 = src->ani2;
1516 dest->source = src->source;
1519 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
1521 ast_party_id_set_init(&init->id, &guide->id);
1523 init->ani2 = guide->ani2;
1524 init->source = guide->source;
1527 void ast_party_connected_line_set(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
1529 ast_party_id_set(&dest->id, &src->id);
1531 if (src->ani && src->ani != dest->ani) {
1533 ast_free(dest->ani);
1535 dest->ani = ast_strdup(src->ani);
1538 dest->ani2 = src->ani2;
1539 dest->source = src->source;
1542 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_callerid *cid)
1544 connected->id.number = cid->cid_num;
1545 connected->id.name = cid->cid_name;
1546 connected->id.number_type = cid->cid_ton;
1547 connected->id.number_presentation = cid->cid_pres;
1549 connected->ani = cid->cid_ani;
1550 connected->ani2 = cid->cid_ani2;
1551 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
1554 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
1556 ast_party_id_free(&doomed->id);
1559 ast_free(doomed->ani);
1564 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
1567 /* Don't copy to self */
1571 ast_party_id_copy(&dest->from, &src->from);
1572 ast_party_id_copy(&dest->to, &src->to);
1573 dest->count = src->count;
1574 dest->reason = src->reason;
1577 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
1579 ast_party_id_set_init(&init->from, &guide->from);
1580 ast_party_id_set_init(&init->to, &guide->to);
1581 init->count = guide->count;
1582 init->reason = guide->reason;
1585 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
1587 ast_party_id_free(&doomed->from);
1588 ast_party_id_free(&doomed->to);
1591 /*! \brief Free a channel structure */
1592 void ast_channel_free(struct ast_channel *chan)
1598 struct ast_var_t *vardata;
1599 struct ast_frame *f;
1600 struct varshead *headp;
1601 struct ast_datastore *datastore = NULL;
1602 char name[AST_CHANNEL_NAME], *dashptr;
1604 headp=&chan->varshead;
1606 AST_RWLIST_WRLOCK(&channels);
1607 if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1608 AST_RWLIST_UNLOCK(&channels);
1609 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1611 /* Lock and unlock the channel just to be sure nobody has it locked still
1612 due to a reference retrieved from the channel list. */
1613 ast_channel_lock(chan);
1614 ast_channel_unlock(chan);
1616 /* Get rid of each of the data stores on the channel */
1617 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1618 /* Free the data store */
1619 ast_datastore_free(datastore);
1621 /* Lock and unlock the channel just to be sure nobody has it locked still
1622 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1623 ast_channel_lock(chan);
1624 ast_channel_unlock(chan);
1626 if (chan->tech_pvt) {
1627 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1628 ast_free(chan->tech_pvt);
1632 sched_context_destroy(chan->sched);
1634 ast_copy_string(name, chan->name, sizeof(name));
1635 if ((dashptr = strrchr(name, '-'))) {
1639 /* Stop monitoring */
1641 chan->monitor->stop( chan, 0 );
1643 /* If there is native format music-on-hold state, free it */
1644 if (chan->music_state)
1645 ast_moh_cleanup(chan);
1647 /* Free translators */
1648 if (chan->readtrans)
1649 ast_translator_free_path(chan->readtrans);
1650 if (chan->writetrans)
1651 ast_translator_free_path(chan->writetrans);
1653 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1655 free_cid(&chan->cid);
1656 ast_party_connected_line_free(&chan->connected);
1657 ast_party_redirecting_free(&chan->redirecting);
1659 /* Close pipes if appropriate */
1660 if ((fd = chan->alertpipe[0]) > -1)
1662 if ((fd = chan->alertpipe[1]) > -1)
1665 ast_timer_close(chan->timer);
1668 for (i = 0; i < AST_MAX_FDS; i++) {
1669 if (chan->epfd_data[i])
1670 free(chan->epfd_data[i]);
1674 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1677 /* loop over the variables list, freeing all data and deleting list items */
1678 /* no need to lock the list, as the channel is already locked */
1680 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1681 ast_var_delete(vardata);
1683 ast_app_group_discard(chan);
1685 /* Destroy the jitterbuffer */
1686 ast_jb_destroy(chan);
1689 ast_cdr_discard(chan->cdr);
1694 chan->zone = ast_tone_zone_unref(chan->zone);
1697 ast_mutex_destroy(&chan->lock_dont_use);
1699 ast_string_field_free_memory(chan);
1701 AST_RWLIST_UNLOCK(&channels);
1703 /* Queue an unknown state, because, while we know that this particular
1704 * instance is dead, we don't know the state of all other possible
1706 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, name);
1709 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1711 return ast_datastore_alloc(info, uid);
1714 int ast_channel_datastore_free(struct ast_datastore *datastore)
1716 return ast_datastore_free(datastore);
1719 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1721 struct ast_datastore *datastore = NULL, *datastore2;
1723 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1724 if (datastore->inheritance > 0) {
1725 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
1727 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
1728 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1729 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1736 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1740 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1745 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1747 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1750 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1752 struct ast_datastore *datastore = NULL;
1757 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1758 if (datastore->info != info) {
1763 /* matched by type only */
1767 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
1768 /* Matched by type AND uid */
1772 AST_LIST_TRAVERSE_SAFE_END;
1777 /*! Set the file descriptor on the channel */
1778 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
1781 struct epoll_event ev;
1782 struct ast_epoll_data *aed = NULL;
1784 if (chan->fds[which] > -1) {
1785 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
1786 aed = chan->epfd_data[which];
1789 /* If this new fd is valid, add it to the epoll */
1791 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
1794 chan->epfd_data[which] = aed;
1798 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1800 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
1802 /* We don't have to keep around this epoll data structure now */
1804 chan->epfd_data[which] = NULL;
1807 chan->fds[which] = fd;
1811 /*! Add a channel to an optimized waitfor */
1812 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
1815 struct epoll_event ev;
1818 if (chan0->epfd == -1)
1821 /* Iterate through the file descriptors on chan1, adding them to chan0 */
1822 for (i = 0; i < AST_MAX_FDS; i++) {
1823 if (chan1->fds[i] == -1)
1825 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1826 ev.data.ptr = chan1->epfd_data[i];
1827 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
1834 /*! Delete a channel from an optimized waitfor */
1835 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
1838 struct epoll_event ev;
1841 if (chan0->epfd == -1)
1844 for (i = 0; i < AST_MAX_FDS; i++) {
1845 if (chan1->fds[i] == -1)
1847 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
1854 /*! \brief Softly hangup a channel, don't lock */
1855 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1857 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1858 /* Inform channel driver that we need to be hung up, if it cares */
1859 chan->_softhangup |= cause;
1860 ast_queue_frame(chan, &ast_null_frame);
1861 /* Interrupt any poll call or such */
1862 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1863 pthread_kill(chan->blocker, SIGURG);
1867 /*! \brief Softly hangup a channel, lock */
1868 int ast_softhangup(struct ast_channel *chan, int cause)
1872 ast_channel_lock(chan);
1873 res = ast_softhangup_nolock(chan, cause);
1874 ast_channel_unlock(chan);
1879 static void free_translation(struct ast_channel *clonechan)
1881 if (clonechan->writetrans)
1882 ast_translator_free_path(clonechan->writetrans);
1883 if (clonechan->readtrans)
1884 ast_translator_free_path(clonechan->readtrans);
1885 clonechan->writetrans = NULL;
1886 clonechan->readtrans = NULL;
1887 clonechan->rawwriteformat = clonechan->nativeformats;
1888 clonechan->rawreadformat = clonechan->nativeformats;
1891 /*! \brief Hangup a channel */
1892 int ast_hangup(struct ast_channel *chan)
1896 /* Don't actually hang up a channel that will masquerade as someone else, or
1897 if someone is going to masquerade as us */
1898 ast_channel_lock(chan);
1900 if (chan->audiohooks) {
1901 ast_audiohook_detach_list(chan->audiohooks);
1902 chan->audiohooks = NULL;
1905 ast_autoservice_stop(chan);
1908 if (ast_do_masquerade(chan))
1909 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1913 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1914 ast_channel_unlock(chan);
1917 /* If this channel is one which will be masqueraded into something,
1918 mark it as a zombie already, so we know to free it later */
1920 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1921 ast_channel_unlock(chan);
1924 free_translation(chan);
1925 /* Close audio stream */
1927 ast_closestream(chan->stream);
1928 chan->stream = NULL;
1930 /* Close video stream */
1931 if (chan->vstream) {
1932 ast_closestream(chan->vstream);
1933 chan->vstream = NULL;
1936 sched_context_destroy(chan->sched);
1940 if (chan->generatordata) /* Clear any tone stuff remaining */
1941 if (chan->generator && chan->generator->release)
1942 chan->generator->release(chan, chan->generatordata);
1943 chan->generatordata = NULL;
1944 chan->generator = NULL;
1945 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1946 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1947 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1948 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1949 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
1951 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1952 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1953 if (chan->tech->hangup)
1954 res = chan->tech->hangup(chan);
1956 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1959 ast_channel_unlock(chan);
1960 manager_event(EVENT_FLAG_CALL, "Hangup",
1963 "CallerIDNum: %s\r\n"
1964 "CallerIDName: %s\r\n"
1966 "Cause-txt: %s\r\n",
1969 S_OR(chan->cid.cid_num, "<unknown>"),
1970 S_OR(chan->cid.cid_name, "<unknown>"),
1972 ast_cause2str(chan->hangupcause)
1975 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
1976 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
1977 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
1979 ast_cdr_end(chan->cdr);
1980 ast_cdr_detach(chan->cdr);
1984 ast_channel_free(chan);
1989 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
1993 ast_channel_lock(chan);
1995 /* You can't answer an outbound call */
1996 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1997 ast_channel_unlock(chan);
2001 /* Stop if we're a zombie or need a soft hangup */
2002 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2003 ast_channel_unlock(chan);
2007 ast_channel_unlock(chan);
2009 switch (chan->_state) {
2010 case AST_STATE_RINGING:
2011 case AST_STATE_RING:
2012 ast_channel_lock(chan);
2013 if (chan->tech->answer) {
2014 res = chan->tech->answer(chan);
2016 ast_setstate(chan, AST_STATE_UP);
2018 ast_cdr_answer(chan->cdr);
2020 ast_channel_unlock(chan);
2023 /* Calling ast_cdr_answer when it it has previously been called
2024 * is essentially a no-op, so it is safe.
2027 ast_cdr_answer(chan->cdr);
2034 ast_indicate(chan, -1);
2035 chan->visible_indication = 0;
2040 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2043 enum ast_channel_state old_state;
2045 old_state = chan->_state;
2046 if ((res = ast_raw_answer(chan, cdr_answer))) {
2050 switch (old_state) {
2051 case AST_STATE_RINGING:
2052 case AST_STATE_RING:
2053 /* wait for media to start flowing, but don't wait any longer
2054 * than 'delay' or 500 milliseconds, whichever is longer
2057 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2058 struct ast_frame *cur, *new;
2059 int ms = MAX(delay, 500);
2060 unsigned int done = 0;
2062 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2065 ms = ast_waitfor(chan, ms);
2067 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
2072 ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
2075 cur = ast_read(chan);
2076 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2077 (cur->subclass == AST_CONTROL_HANGUP))) {
2082 ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
2086 if ((new = ast_frisolate(cur)) != cur) {
2090 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2092 /* if a specific delay period was requested, continue
2093 * until that delay has passed. don't stop just because
2094 * incoming media has arrived.
2100 switch (new->frametype) {
2101 /* all of these frametypes qualify as 'media' */
2102 case AST_FRAME_VOICE:
2103 case AST_FRAME_VIDEO:
2104 case AST_FRAME_TEXT:
2105 case AST_FRAME_DTMF_BEGIN:
2106 case AST_FRAME_DTMF_END:
2107 case AST_FRAME_IMAGE:
2108 case AST_FRAME_HTML:
2109 case AST_FRAME_MODEM:
2112 case AST_FRAME_CONTROL:
2114 case AST_FRAME_NULL:
2125 ast_channel_lock(chan);
2126 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2127 ast_queue_frame_head(chan, cur);
2130 ast_channel_unlock(chan);
2141 int ast_answer(struct ast_channel *chan)
2143 return __ast_answer(chan, 0, 1);
2146 void ast_deactivate_generator(struct ast_channel *chan)
2148 ast_channel_lock(chan);
2149 if (chan->generatordata) {
2150 if (chan->generator && chan->generator->release)
2151 chan->generator->release(chan, chan->generatordata);
2152 chan->generatordata = NULL;
2153 chan->generator = NULL;
2154 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2155 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2156 ast_settimeout(chan, 0, NULL, NULL);
2158 ast_channel_unlock(chan);
2161 static int generator_force(const void *data)
2163 /* Called if generator doesn't have data */
2166 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2167 struct ast_channel *chan = (struct ast_channel *)data;
2169 ast_channel_lock(chan);
2170 tmp = chan->generatordata;
2171 chan->generatordata = NULL;
2172 if (chan->generator)
2173 generate = chan->generator->generate;
2174 ast_channel_unlock(chan);
2176 if (!tmp || !generate)
2179 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
2181 chan->generatordata = tmp;
2184 ast_debug(1, "Auto-deactivating generator\n");
2185 ast_deactivate_generator(chan);
2191 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2195 ast_channel_lock(chan);
2197 if (chan->generatordata) {
2198 if (chan->generator && chan->generator->release)
2199 chan->generator->release(chan, chan->generatordata);
2200 chan->generatordata = NULL;
2204 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2209 ast_settimeout(chan, 50, generator_force, chan);
2210 chan->generator = gen;
2213 ast_channel_unlock(chan);
2218 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2219 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2222 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2226 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2228 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2229 int *exception, int *outfd, int *ms)
2231 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2232 int *exception, int *outfd, int *ms)
2235 struct timeval start = { 0 , 0 };
2236 struct pollfd *pfds = NULL;
2241 struct timeval now = { 0, 0 };
2242 struct timeval whentohangup = { 0, 0 }, diff;
2243 struct ast_channel *winner = NULL;
2249 if ((sz = n * AST_MAX_FDS + nfds)) {
2250 pfds = alloca(sizeof(*pfds) * sz);
2251 fdmap = alloca(sizeof(*fdmap) * sz);
2259 /* Perform any pending masquerades */
2260 for (x = 0; x < n; x++) {
2261 ast_channel_lock(c[x]);
2262 if (c[x]->masq && ast_do_masquerade(c[x])) {
2263 ast_log(LOG_WARNING, "Masquerade failed\n");
2265 ast_channel_unlock(c[x]);
2268 if (!ast_tvzero(c[x]->whentohangup)) {
2269 if (ast_tvzero(whentohangup))
2271 diff = ast_tvsub(c[x]->whentohangup, now);
2272 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
2273 /* Should already be hungup */
2274 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2275 ast_channel_unlock(c[x]);
2278 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
2279 whentohangup = diff;
2281 ast_channel_unlock(c[x]);
2283 /* Wait full interval */
2285 if (!ast_tvzero(whentohangup)) {
2286 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
2287 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
2291 * Build the pollfd array, putting the channels' fds first,
2292 * followed by individual fds. Order is important because
2293 * individual fd's must have priority over channel fds.
2296 for (x = 0; x < n; x++) {
2297 for (y = 0; y < AST_MAX_FDS; y++) {
2298 fdmap[max].fdno = y; /* fd y is linked to this pfds */
2299 fdmap[max].chan = x; /* channel x is linked to this pfds */
2300 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
2302 CHECK_BLOCKING(c[x]);
2304 /* Add the individual fds */
2305 for (x = 0; x < nfds; x++) {
2306 fdmap[max].chan = -1;
2307 max += ast_add_fd(&pfds[max], fds[x]);
2311 start = ast_tvnow();
2313 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
2318 res = ast_poll(pfds, max, kbrms);
2321 } while (!res && (rms > 0));
2323 res = ast_poll(pfds, max, rms);
2325 for (x = 0; x < n; x++)
2326 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
2327 if (res < 0) { /* Simulate a timeout if we were interrupted */
2332 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
2334 for (x = 0; x < n; x++) {
2335 if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
2336 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2342 if (res == 0) { /* no fd ready, reset timeout and done */
2343 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
2347 * Then check if any channel or fd has a pending event.
2348 * Remember to check channels first and fds last, as they
2349 * must have priority on setting 'winner'
2351 for (x = 0; x < max; x++) {
2352 res = pfds[x].revents;
2355 if (fdmap[x].chan >= 0) { /* this is a channel */
2356 winner = c[fdmap[x].chan]; /* override previous winners */
2358 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2360 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2361 winner->fdno = fdmap[x].fdno;
2362 } else { /* this is an fd */
2364 *outfd = pfds[x].fd;
2366 *exception = (res & POLLPRI) ? -1 : 0;
2371 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2379 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
2381 struct timeval start = { 0 , 0 };
2383 struct epoll_event ev[1];
2384 long diff, rms = *ms;
2385 struct ast_channel *winner = NULL;
2386 struct ast_epoll_data *aed = NULL;
2388 ast_channel_lock(chan);
2390 /* See if this channel needs to be masqueraded */
2391 if (chan->masq && ast_do_masquerade(chan)) {
2392 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
2394 ast_channel_unlock(chan);
2398 /* Figure out their timeout */
2399 if (!ast_tvzero(chan->whentohangup)) {
2400 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
2401 /* They should already be hungup! */
2402 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2403 ast_channel_unlock(chan);
2406 /* If this value is smaller then the current one... make it priority */
2411 ast_channel_unlock(chan);
2413 /* Time to make this channel block... */
2414 CHECK_BLOCKING(chan);
2417 start = ast_tvnow();
2419 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
2420 res = epoll_wait(chan->epfd, ev, 1, rms);
2423 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2425 /* Simulate a timeout if we were interrupted */
2432 /* If this channel has a timeout see if it expired */
2433 if (!ast_tvzero(chan->whentohangup)) {
2434 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
2435 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2440 /* No fd ready, reset timeout and be done for now */
2446 /* See what events are pending */
2447 aed = ev[0].data.ptr;
2448 chan->fdno = aed->which;
2449 if (ev[0].events & EPOLLPRI)
2450 ast_set_flag(chan, AST_FLAG_EXCEPTION);
2452 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2455 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2463 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2465 struct timeval start = { 0 , 0 };
2467 struct epoll_event ev[25] = { { 0, } };
2468 struct timeval now = { 0, 0 };
2469 long whentohangup = 0, diff = 0, rms = *ms;
2470 struct ast_channel *winner = NULL;
2472 for (i = 0; i < n; i++) {
2473 ast_channel_lock(c[i]);
2474 if (c[i]->masq && ast_do_masquerade(c[i])) {
2475 ast_log(LOG_WARNING, "Masquerade failed\n");
2477 ast_channel_unlock(c[i]);
2480 if (!ast_tvzero(c[i]->whentohangup)) {
2481 if (whentohangup == 0)
2483 if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
2484 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2485 ast_channel_unlock(c[i]);
2488 if (!whentohangup || whentohangup > diff)
2489 whentohangup = diff;
2491 ast_channel_unlock(c[i]);
2492 CHECK_BLOCKING(c[i]);
2498 if (*ms >= 0 && *ms < rms)
2503 start = ast_tvnow();
2505 res = epoll_wait(c[0]->epfd, ev, 25, rms);
2507 for (i = 0; i < n; i++)
2508 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2518 for (i = 0; i < n; i++) {
2519 if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
2520 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2532 for (i = 0; i < res; i++) {
2533 struct ast_epoll_data *aed = ev[i].data.ptr;
2535 if (!ev[i].events || !aed)
2539 if (ev[i].events & EPOLLPRI)
2540 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2542 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2543 winner->fdno = aed->which;
2547 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2555 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2556 int *exception, int *outfd, int *ms)
2558 /* Clear all provided values in one place. */
2564 /* If no epoll file descriptor is available resort to classic nandfds */
2565 if (!n || nfds || c[0]->epfd == -1)
2566 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2567 else if (!nfds && n == 1)
2568 return ast_waitfor_nandfds_simple(c[0], ms);
2570 return ast_waitfor_nandfds_complex(c, n, ms);
2574 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2576 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2579 int ast_waitfor(struct ast_channel *c, int ms)
2581 int oldms = ms; /* -1 if no timeout */
2583 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2584 if ((ms < 0) && (oldms < 0))
2589 /* XXX never to be called with ms = -1 */
2590 int ast_waitfordigit(struct ast_channel *c, int ms)
2592 return ast_waitfordigit_full(c, ms, -1, -1);
2595 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
2598 unsigned int real_rate = rate, max_rate;
2600 ast_channel_lock(c);
2602 if (c->timingfd == -1) {
2603 ast_channel_unlock(c);
2612 if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
2613 real_rate = max_rate;
2616 ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
2618 res = ast_timer_set_rate(c->timer, real_rate);
2620 c->timingfunc = func;
2621 c->timingdata = data;
2623 ast_channel_unlock(c);
2628 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2630 /* Stop if we're a zombie or need a soft hangup */
2631 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2634 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2635 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2637 /* Wait for a digit, no more than ms milliseconds total. */
2640 struct ast_channel *rchan;
2644 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2646 if (!rchan && outfd < 0 && ms) {
2647 if (errno == 0 || errno == EINTR)
2649 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2650 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2652 } else if (outfd > -1) {
2653 /* The FD we were watching has something waiting */
2654 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2655 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2659 struct ast_frame *f = ast_read(c);
2663 switch (f->frametype) {
2664 case AST_FRAME_DTMF_BEGIN:
2666 case AST_FRAME_DTMF_END:
2669 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2671 case AST_FRAME_CONTROL:
2672 switch (f->subclass) {
2673 case AST_CONTROL_HANGUP:
2675 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2677 case AST_CONTROL_RINGING:
2678 case AST_CONTROL_ANSWER:
2679 case AST_CONTROL_SRCUPDATE:
2680 case AST_CONTROL_CONNECTED_LINE:
2681 case AST_CONTROL_REDIRECTING:
2685 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2689 case AST_FRAME_VOICE:
2690 /* Write audio if appropriate */
2692 if (write(audiofd, f->data.ptr, f->datalen) < 0) {
2693 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
2704 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2706 return 0; /* Time is up */
2709 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2711 manager_event(EVENT_FLAG_DTMF,
2719 chan->name, chan->uniqueid, digit, direction, begin, end);
2722 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2724 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2725 void *tmp = chan->generatordata;
2726 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2730 if (chan->timingfunc) {
2731 ast_debug(1, "Generator got voice, switching to phase locked mode\n");
2732 ast_settimeout(chan, 0, NULL, NULL);
2735 chan->generatordata = NULL; /* reset, to let writes go through */
2737 if (f->subclass != chan->writeformat) {
2739 factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass));
2740 samples = (int) ( ((float) f->samples) * factor );
2742 samples = f->samples;
2745 if (chan->generator->generate) {
2746 generate = chan->generator->generate;
2748 /* This unlock is here based on two assumptions that hold true at this point in the
2749 * code. 1) this function is only called from within __ast_read() and 2) all generators
2750 * call ast_write() in their generate callback.
2752 * The reason this is added is so that when ast_write is called, the lock that occurs
2753 * there will not recursively lock the channel. Doing this will cause intended deadlock
2754 * avoidance not to work in deeper functions
2756 ast_channel_unlock(chan);
2757 res = generate(chan, tmp, f->datalen, samples);
2758 ast_channel_lock(chan);
2759 chan->generatordata = tmp;
2761 ast_debug(1, "Auto-deactivating generator\n");
2762 ast_deactivate_generator(chan);
2765 } else if (f->frametype == AST_FRAME_CNG) {
2766 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2767 ast_debug(1, "Generator got CNG, switching to timed mode\n");
2768 ast_settimeout(chan, 50, generator_force, chan);
2773 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
2775 struct ast_frame *fr = &chan->dtmff;
2777 fr->frametype = AST_FRAME_DTMF_END;
2778 fr->subclass = f->subclass;
2781 /* The only time this function will be called is for a frame that just came
2782 * out of the channel driver. So, we want to stick it on the tail of the
2785 ast_queue_frame(chan, fr);
2789 * \brief Determine whether or not we should ignore DTMF in the readq
2791 static inline int should_skip_dtmf(struct ast_channel *chan)
2793 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
2794 /* We're in the middle of emulating a digit, or DTMF has been
2795 * explicitly deferred. Skip this digit, then. */
2799 if (!ast_tvzero(chan->dtmf_tv) &&
2800 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2801 /* We're not in the middle of a digit, but it hasn't been long enough
2802 * since the last digit, so we'll have to skip DTMF for now. */
2809 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2811 struct ast_frame *f = NULL; /* the return value */
2814 int count = 0, cause = 0;
2816 /* this function is very long so make sure there is only one return
2817 * point at the end (there are only two exceptions to this).
2819 while(ast_channel_trylock(chan)) {
2821 /*cannot goto done since the channel is not locked*/
2822 return &ast_null_frame;
2827 if (ast_do_masquerade(chan))
2828 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2830 f = &ast_null_frame;
2834 if (chan->fdno == -1) {
2836 ast_log(LOG_ERROR, "ast_read() called with no recorded file descriptor.\n");
2838 ast_debug(2, "ast_read() called with no recorded file descriptor.\n");
2840 f = &ast_null_frame;
2844 /* Stop if we're a zombie or need a soft hangup */
2845 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2846 if (chan->generator)
2847 ast_deactivate_generator(chan);
2850 prestate = chan->_state;
2852 /* Read and ignore anything on the alertpipe, but read only
2853 one sizeof(blah) per frame that we send from it */
2854 if (chan->alertpipe[0] > -1) {
2855 int flags = fcntl(chan->alertpipe[0], F_GETFL);
2856 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
2857 * which immediately causes a deadlock scenario. Detect and prevent this. */
2858 if ((flags & O_NONBLOCK) == 0) {
2859 ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
2860 if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2861 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
2862 f = &ast_null_frame;
2866 if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
2867 if (errno != EINTR && errno != EAGAIN)
2868 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
2872 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
2873 enum ast_timer_event res;
2875 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2877 res = ast_timer_get_event(chan->timer);
2880 case AST_TIMING_EVENT_EXPIRED:
2881 ast_timer_ack(chan->timer, 1);
2883 if (chan->timingfunc) {
2884 /* save a copy of func/data before unlocking the channel */
2885 int (*func)(const void *) = chan->timingfunc;
2886 void *data = chan->timingdata;
2888 ast_channel_unlock(chan);
2891 ast_timer_set_rate(chan->timer, 0);
2893 ast_channel_unlock(chan);
2896 /* cannot 'goto done' because the channel is already unlocked */
2897 return &ast_null_frame;
2899 case AST_TIMING_EVENT_CONTINUOUS:
2900 if (AST_LIST_EMPTY(&chan->readq) ||
2901 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2902 ast_timer_disable_continuous(chan->timer);
2907 } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2908 /* if the AST_GENERATOR_FD is set, call the generator with args
2909 * set to -1 so it can do whatever it needs to.
2911 void *tmp = chan->generatordata;
2912 chan->generatordata = NULL; /* reset to let ast_write get through */
2913 chan->generator->generate(chan, tmp, -1, -1);
2914 chan->generatordata = tmp;
2915 f = &ast_null_frame;
2920 /* Check for pending read queue */
2921 if (!AST_LIST_EMPTY(&chan->readq)) {
2922 int skip_dtmf = should_skip_dtmf(chan);
2924 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
2925 /* We have to be picky about which frame we pull off of the readq because
2926 * there are cases where we want to leave DTMF frames on the queue until
2927 * some later time. */
2929 if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
2933 AST_LIST_REMOVE_CURRENT(frame_list);
2936 AST_LIST_TRAVERSE_SAFE_END
2939 /* There were no acceptable frames on the readq. */
2940 f = &ast_null_frame;
2941 if (chan->alertpipe[0] > -1) {
2943 /* Restore the state of the alertpipe since we aren't ready for any
2944 * of the frames in the readq. */
2945 if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
2946 ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
2951 /* Interpret hangup and return NULL */
2952 /* XXX why not the same for frames from the channel ? */
2953 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2954 cause = f->data.uint32;
2959 chan->blocker = pthread_self();
2960 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2961 if (chan->tech->exception)
2962 f = chan->tech->exception(chan);
2964 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2965 f = &ast_null_frame;
2967 /* Clear the exception flag */
2968 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2969 } else if (chan->tech->read)
2970 f = chan->tech->read(chan);
2972 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2976 * Reset the recorded file descriptor that triggered this read so that we can
2977 * easily detect when ast_read() is called without properly using ast_waitfor().
2982 /* if the channel driver returned more than one frame, stuff the excess
2983 into the readq for the next ast_read call (note that we can safely assume
2984 that the readq is empty, because otherwise we would not have called into
2985 the channel driver and f would be only a single frame)
2987 if (AST_LIST_NEXT(f, frame_list)) {
2988 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2989 AST_LIST_NEXT(f, frame_list) = NULL;
2992 switch (f->frametype) {
2993 case AST_FRAME_CONTROL:
2994 if (f->subclass == AST_CONTROL_ANSWER) {
2995 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2996 ast_debug(1, "Ignoring answer on an inbound call!\n");
2998 f = &ast_null_frame;
2999 } else if (prestate == AST_STATE_UP) {
3000 ast_debug(1, "Dropping duplicate answer!\n");
3002 f = &ast_null_frame;
3004 /* Answer the CDR */
3005 ast_setstate(chan, AST_STATE_UP);
3006 /* removed a call to ast_cdr_answer(chan->cdr) from here. */
3010 case AST_FRAME_DTMF_END:
3011 send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
3012 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
3013 /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
3014 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
3015 queue_dtmf_readq(chan, f);
3017 f = &ast_null_frame;
3018 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
3019 if (!ast_tvzero(chan->dtmf_tv) &&
3020 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3021 /* If it hasn't been long enough, defer this digit */
3022 queue_dtmf_readq(chan, f);
3024 f = &ast_null_frame;
3026 /* There was no begin, turn this into a begin and send the end later */
3027 f->frametype = AST_FRAME_DTMF_BEGIN;
3028 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
3029 chan->emulate_dtmf_digit = f->subclass;
3030 chan->dtmf_tv = ast_tvnow();
3032 if (f->len > AST_MIN_DTMF_DURATION)
3033 chan->emulate_dtmf_duration = f->len;
3035 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
3037 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
3038 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
3040 if (chan->audiohooks) {
3041 struct ast_frame *old_frame = f;
3043 * \todo XXX It is possible to write a digit to the audiohook twice
3044 * if the digit was originally read while the channel was in autoservice. */
3045 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3047 ast_frfree(old_frame);
3050 struct timeval now = ast_tvnow();
3051 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
3052 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
3053 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
3055 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3056 } else if (!f->len) {
3057 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
3058 f->len = AST_MIN_DTMF_DURATION;
3060 if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
3061 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);
3062 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
3063 chan->emulate_dtmf_digit = f->subclass;
3064 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
3066 f = &ast_null_frame;
3068 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
3069 if (f->len < AST_MIN_DTMF_DURATION) {
3070 f->len = AST_MIN_DTMF_DURATION;
3072 chan->dtmf_tv = now;
3074 if (chan->audiohooks) {
3075 struct ast_frame *old_frame = f;
3076 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3078 ast_frfree(old_frame);
3082 case AST_FRAME_DTMF_BEGIN:
3083 send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
3084 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
3085 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
3086 (!ast_tvzero(chan->dtmf_tv) &&
3087 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
3088 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
3090 f = &ast_null_frame;
3092 ast_set_flag(chan, AST_FLAG_IN_DTMF);
3093 chan->dtmf_tv = ast_tvnow();
3094 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
3097 case AST_FRAME_NULL:
3098 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
3099 * is reached , because we want to make sure we pass at least one
3100 * voice frame through before starting the next digit, to ensure a gap
3101 * between DTMF digits. */
3102 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
3103 struct timeval now = ast_tvnow();
3104 if (!chan->emulate_dtmf_duration) {
3105 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
3106 chan->emulate_dtmf_digit = 0;
3107 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
3108 chan->emulate_dtmf_duration = 0;
3111 f->frametype = AST_FRAME_DTMF_END;
3112 f->subclass = chan->emulate_dtmf_digit;
3113 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3114 chan->dtmf_tv = now;
3115 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
3116 chan->emulate_dtmf_digit = 0;
3117 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
3118 if (chan->audiohooks) {
3119 struct ast_frame *old_frame = f;
3120 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3121 if (old_frame != f) {
3122 ast_frfree(old_frame);
3128 case AST_FRAME_VOICE:
3129 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
3130 * is reached , because we want to make sure we pass at least one
3131 * voice frame through before starting the next digit, to ensure a gap
3132 * between DTMF digits. */
3133 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
3134 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
3135 chan->emulate_dtmf_digit = 0;
3138 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
3140 ast_read_generator_actions(chan, f);
3142 f = &ast_null_frame;
3145 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
3146 struct timeval now = ast_tvnow();
3147 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
3148 chan->emulate_dtmf_duration = 0;
3151 f->frametype = AST_FRAME_DTMF_END;
3152 f->subclass = chan->emulate_dtmf_digit;
3153 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3154 chan->dtmf_tv = now;
3155 if (chan->audiohooks) {
3156 struct ast_frame *old_frame = f;
3157 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3159 ast_frfree(old_frame);
3161 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);