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/mod_format.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/cel.h"
50 #include "asterisk/chanvars.h"
51 #include "asterisk/linkedlists.h"
52 #include "asterisk/indications.h"
53 #include "asterisk/monitor.h"
54 #include "asterisk/causes.h"
55 #include "asterisk/callerid.h"
56 #include "asterisk/utils.h"
57 #include "asterisk/lock.h"
58 #include "asterisk/app.h"
59 #include "asterisk/transcap.h"
60 #include "asterisk/devicestate.h"
61 #include "asterisk/sha1.h"
62 #include "asterisk/threadstorage.h"
63 #include "asterisk/slinfactory.h"
64 #include "asterisk/audiohook.h"
65 #include "asterisk/timing.h"
66 #include "asterisk/autochan.h"
67 #include "asterisk/stringfields.h"
68 #include "asterisk/data.h"
71 #include <sys/epoll.h>
74 struct ast_epoll_data {
75 struct ast_channel *chan;
79 /* uncomment if you have problems with 'monitoring' synchronized files */
81 #define MONITOR_CONSTANT_DELAY
82 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
85 /*! \brief Prevent new channel allocation if shutting down. */
86 static int shutting_down;
90 unsigned long global_fin, global_fout;
92 AST_THREADSTORAGE(state2str_threadbuf);
93 #define STATE2STR_BUFSIZE 32
95 /*! Default amount of time to use when emulating a digit as a begin and end
97 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
99 /*! Minimum allowed digit length - 80ms */
100 #define AST_MIN_DTMF_DURATION 80
102 /*! Minimum amount of time between the end of the last digit and the beginning
103 * of a new one - 45ms */
104 #define AST_MIN_DTMF_GAP 45
106 /*! \brief List of channel drivers */
108 const struct ast_channel_tech *tech;
109 AST_LIST_ENTRY(chanlist) list;
113 /*! \brief Structure to hold channel context backtrace data */
114 struct ast_chan_trace_data {
116 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
119 /*! \brief Structure to save contexts where an ast_chan has been into */
120 struct ast_chan_trace {
121 char context[AST_MAX_CONTEXT];
122 char exten[AST_MAX_EXTENSION];
124 AST_LIST_ENTRY(ast_chan_trace) entry;
128 /*! \brief the list of registered channel types */
129 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
132 #define NUM_CHANNEL_BUCKETS 61
134 #define NUM_CHANNEL_BUCKETS 1567
137 #define DATA_EXPORT_CHANNEL(MEMBER) \
138 MEMBER(ast_channel, blockproc, AST_DATA_STRING) \
139 MEMBER(ast_channel, appl, AST_DATA_STRING) \
140 MEMBER(ast_channel, data, AST_DATA_STRING) \
141 MEMBER(ast_channel, name, AST_DATA_STRING) \
142 MEMBER(ast_channel, language, AST_DATA_STRING) \
143 MEMBER(ast_channel, musicclass, AST_DATA_STRING) \
144 MEMBER(ast_channel, accountcode, AST_DATA_STRING) \
145 MEMBER(ast_channel, peeraccount, AST_DATA_STRING) \
146 MEMBER(ast_channel, userfield, AST_DATA_STRING) \
147 MEMBER(ast_channel, call_forward, AST_DATA_STRING) \
148 MEMBER(ast_channel, uniqueid, AST_DATA_STRING) \
149 MEMBER(ast_channel, linkedid, AST_DATA_STRING) \
150 MEMBER(ast_channel, parkinglot, AST_DATA_STRING) \
151 MEMBER(ast_channel, hangupsource, AST_DATA_STRING) \
152 MEMBER(ast_channel, dialcontext, AST_DATA_STRING) \
153 MEMBER(ast_channel, _softhangup, AST_DATA_INTEGER) \
154 MEMBER(ast_channel, streamid, AST_DATA_INTEGER) \
155 MEMBER(ast_channel, vstreamid, AST_DATA_INTEGER) \
156 MEMBER(ast_channel, oldwriteformat, AST_DATA_INTEGER) \
157 MEMBER(ast_channel, _state, AST_DATA_INTEGER) \
158 MEMBER(ast_channel, rings, AST_DATA_INTEGER) \
159 MEMBER(ast_channel, priority, AST_DATA_INTEGER) \
160 MEMBER(ast_channel, macropriority, AST_DATA_INTEGER) \
161 MEMBER(ast_channel, amaflags, AST_DATA_INTEGER) \
162 MEMBER(ast_channel, adsicpe, AST_DATA_INTEGER) \
163 MEMBER(ast_channel, fin, AST_DATA_UNSIGNED_INTEGER) \
164 MEMBER(ast_channel, fout, AST_DATA_UNSIGNED_INTEGER) \
165 MEMBER(ast_channel, hangupcause, AST_DATA_INTEGER) \
166 MEMBER(ast_channel, flags, AST_DATA_UNSIGNED_INTEGER) \
167 MEMBER(ast_channel, nativeformats, AST_DATA_INTEGER) \
168 MEMBER(ast_channel, readformat, AST_DATA_INTEGER) \
169 MEMBER(ast_channel, writeformat, AST_DATA_INTEGER) \
170 MEMBER(ast_channel, rawreadformat, AST_DATA_INTEGER) \
171 MEMBER(ast_channel, rawwriteformat, AST_DATA_INTEGER) \
172 MEMBER(ast_channel, emulate_dtmf_duration, AST_DATA_UNSIGNED_INTEGER) \
173 MEMBER(ast_channel, visible_indication, AST_DATA_INTEGER) \
174 MEMBER(ast_channel, transfercapability, AST_DATA_INTEGER) \
175 MEMBER(ast_channel, context, AST_DATA_STRING) \
176 MEMBER(ast_channel, exten, AST_DATA_STRING) \
177 MEMBER(ast_channel, macrocontext, AST_DATA_STRING) \
178 MEMBER(ast_channel, macroexten, AST_DATA_STRING)
180 AST_DATA_STRUCTURE(ast_channel, DATA_EXPORT_CHANNEL);
183 /*! \brief All active channels on the system */
184 static struct ao2_container *channels;
186 /*! \brief map AST_CAUSE's to readable string representations
190 static const struct {
195 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
196 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
197 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
198 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
199 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
200 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
201 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
202 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
203 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
204 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
205 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
206 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
207 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
208 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
209 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
210 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
211 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
212 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
213 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
214 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
215 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
216 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
217 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
218 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
219 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
220 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
221 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
222 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
223 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
224 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
225 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
226 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
227 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
228 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
229 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
230 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
231 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
232 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
233 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
234 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
235 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
236 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
237 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
238 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
241 struct ast_variable *ast_channeltype_list(void)
244 struct ast_variable *var = NULL, *prev = NULL;
246 AST_RWLIST_RDLOCK(&backends);
247 AST_RWLIST_TRAVERSE(&backends, cl, list) {
249 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
252 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
256 AST_RWLIST_UNLOCK(&backends);
261 int ast_channel_data_add_structure(struct ast_data *tree, struct ast_channel *chan)
263 return ast_data_add_structure(ast_channel, tree, chan);
266 int ast_channel_data_cmp_structure(const struct ast_data_search *tree,
267 struct ast_channel *chan, const char *structure_name)
269 return ast_data_search_cmp_structure(tree, ast_channel, chan, structure_name);
272 /*! \brief Show channel types - CLI command */
273 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
275 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
281 e->command = "core show channeltypes";
283 "Usage: core show channeltypes\n"
284 " Lists available channel types registered in your\n"
285 " Asterisk server.\n";
292 return CLI_SHOWUSAGE;
294 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
295 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
297 AST_RWLIST_RDLOCK(&backends);
298 AST_RWLIST_TRAVERSE(&backends, cl, list) {
299 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
300 (cl->tech->devicestate) ? "yes" : "no",
301 (cl->tech->indicate) ? "yes" : "no",
302 (cl->tech->transfer) ? "yes" : "no");
305 AST_RWLIST_UNLOCK(&backends);
307 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
314 static char *complete_channeltypes(struct ast_cli_args *a)
324 wordlen = strlen(a->word);
326 AST_RWLIST_RDLOCK(&backends);
327 AST_RWLIST_TRAVERSE(&backends, cl, list) {
328 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
329 ret = ast_strdup(cl->tech->type);
333 AST_RWLIST_UNLOCK(&backends);
338 /*! \brief Show details about a channel driver - CLI command */
339 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
341 struct chanlist *cl = NULL;
346 e->command = "core show channeltype";
348 "Usage: core show channeltype <name>\n"
349 " Show details about the specified channel type, <name>.\n";
352 return complete_channeltypes(a);
356 return CLI_SHOWUSAGE;
358 AST_RWLIST_RDLOCK(&backends);
360 AST_RWLIST_TRAVERSE(&backends, cl, list) {
361 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
367 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
368 AST_RWLIST_UNLOCK(&backends);
373 "-- Info about channel driver: %s --\n"
374 " Device State: %s\n"
377 " Capabilities: %s\n"
381 " Image Support: %s\n"
382 " Text Support: %s\n",
384 (cl->tech->devicestate) ? "yes" : "no",
385 (cl->tech->indicate) ? "yes" : "no",
386 (cl->tech->transfer) ? "yes" : "no",
387 ast_getformatname_multiple(buf, sizeof(buf), (cl->tech->capabilities) ? cl->tech->capabilities : -1),
388 (cl->tech->send_digit_begin) ? "yes" : "no",
389 (cl->tech->send_digit_end) ? "yes" : "no",
390 (cl->tech->send_html) ? "yes" : "no",
391 (cl->tech->send_image) ? "yes" : "no",
392 (cl->tech->send_text) ? "yes" : "no"
396 AST_RWLIST_UNLOCK(&backends);
401 static struct ast_cli_entry cli_channel[] = {
402 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
403 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
407 /*! \brief Destructor for the channel trace datastore */
408 static void ast_chan_trace_destroy_cb(void *data)
410 struct ast_chan_trace *trace;
411 struct ast_chan_trace_data *traced = data;
412 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
418 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
419 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
421 .destroy = ast_chan_trace_destroy_cb
424 /*! \brief Put the channel backtrace in a string */
425 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
428 struct ast_chan_trace *trace;
429 struct ast_chan_trace_data *traced;
430 struct ast_datastore *store;
432 ast_channel_lock(chan);
433 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
435 ast_channel_unlock(chan);
438 traced = store->data;
440 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
441 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
442 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
448 ast_channel_unlock(chan);
452 /* !\brief Whether or not context tracing is enabled */
453 int ast_channel_trace_is_enabled(struct ast_channel *chan)
455 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
458 return ((struct ast_chan_trace_data *)store->data)->enabled;
461 /*! \brief Update the context backtrace data if tracing is enabled */
462 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
464 struct ast_chan_trace *trace;
465 if (!traced->enabled)
467 /* If the last saved context does not match the current one
468 OR we have not saved any context so far, then save the current context */
469 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) ||
470 (AST_LIST_EMPTY(&traced->trace))) {
471 /* Just do some debug logging */
472 if (AST_LIST_EMPTY(&traced->trace))
473 ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
475 ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
476 /* alloc or bail out */
477 trace = ast_malloc(sizeof(*trace));
480 /* save the current location and store it in the trace list */
481 ast_copy_string(trace->context, chan->context, sizeof(trace->context));
482 ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
483 trace->priority = chan->priority;
484 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
489 /*! \brief Update the context backtrace if tracing is enabled */
490 int ast_channel_trace_update(struct ast_channel *chan)
492 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
495 return ast_channel_trace_data_update(chan, store->data);
498 /*! \brief Enable context tracing in the channel */
499 int ast_channel_trace_enable(struct ast_channel *chan)
501 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
502 struct ast_chan_trace_data *traced;
504 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
507 traced = ast_calloc(1, sizeof(*traced));
509 ast_datastore_free(store);
512 store->data = traced;
513 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
514 ast_channel_datastore_add(chan, store);
516 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
517 ast_channel_trace_data_update(chan, store->data);
521 /*! \brief Disable context tracing in the channel */
522 int ast_channel_trace_disable(struct ast_channel *chan)
524 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
527 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
530 #endif /* CHANNEL_TRACE */
532 /*! \brief Checks to see if a channel is needing hang up */
533 int ast_check_hangup(struct ast_channel *chan)
535 if (chan->_softhangup) /* yes if soft hangup flag set */
537 if (ast_tvzero(chan->whentohangup)) /* no if no hangup scheduled */
539 if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0) /* no if hangup time has not come yet. */
541 ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(chan->whentohangup, ast_tvnow()));
542 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
546 int ast_check_hangup_locked(struct ast_channel *chan)
549 ast_channel_lock(chan);
550 res = ast_check_hangup(chan);
551 ast_channel_unlock(chan);
555 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
557 struct ast_channel *chan = obj;
559 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
564 void ast_begin_shutdown(int hangup)
569 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
573 /*! \brief returns number of active/allocated channels */
574 int ast_active_channels(void)
576 return channels ? ao2_container_count(channels) : 0;
579 /*! \brief Cancel a shutdown in progress */
580 void ast_cancel_shutdown(void)
585 /*! \brief Returns non-zero if Asterisk is being shut down */
586 int ast_shutting_down(void)
588 return shutting_down;
591 /*! \brief Set when to hangup channel */
592 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
594 chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
595 ast_queue_frame(chan, &ast_null_frame);
599 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
601 struct timeval when = { offset, };
602 ast_channel_setwhentohangup_tv(chan, when);
605 /*! \brief Compare a offset with when to hangup channel */
606 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
608 struct timeval whentohangup;
610 if (ast_tvzero(chan->whentohangup))
611 return ast_tvzero(offset) ? 0 : -1;
613 if (ast_tvzero(offset))
616 whentohangup = ast_tvadd(offset, ast_tvnow());
618 return ast_tvdiff_ms(whentohangup, chan->whentohangup);
621 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
623 struct timeval when = { offset, };
624 return ast_channel_cmpwhentohangup_tv(chan, when);
627 /*! \brief Register a new telephony channel in Asterisk */
628 int ast_channel_register(const struct ast_channel_tech *tech)
630 struct chanlist *chan;
632 AST_RWLIST_WRLOCK(&backends);
634 AST_RWLIST_TRAVERSE(&backends, chan, list) {
635 if (!strcasecmp(tech->type, chan->tech->type)) {
636 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
637 AST_RWLIST_UNLOCK(&backends);
642 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
643 AST_RWLIST_UNLOCK(&backends);
647 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
649 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
651 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
653 AST_RWLIST_UNLOCK(&backends);
658 /*! \brief Unregister channel driver */
659 void ast_channel_unregister(const struct ast_channel_tech *tech)
661 struct chanlist *chan;
663 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
665 AST_RWLIST_WRLOCK(&backends);
667 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
668 if (chan->tech == tech) {
669 AST_LIST_REMOVE_CURRENT(list);
671 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
675 AST_LIST_TRAVERSE_SAFE_END;
677 AST_RWLIST_UNLOCK(&backends);
680 /*! \brief Get handle to channel driver based on name */
681 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
683 struct chanlist *chanls;
684 const struct ast_channel_tech *ret = NULL;
686 AST_RWLIST_RDLOCK(&backends);
688 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
689 if (!strcasecmp(name, chanls->tech->type)) {
695 AST_RWLIST_UNLOCK(&backends);
700 /*! \brief Gives the string form of a given hangup cause */
701 const char *ast_cause2str(int cause)
705 for (x = 0; x < ARRAY_LEN(causes); x++) {
706 if (causes[x].cause == cause)
707 return causes[x].desc;
713 /*! \brief Convert a symbolic hangup cause to number */
714 int ast_str2cause(const char *name)
718 for (x = 0; x < ARRAY_LEN(causes); x++)
719 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
720 return causes[x].cause;
725 /*! \brief Gives the string form of a given channel state.
726 \note This function is not reentrant.
728 const char *ast_state2str(enum ast_channel_state state)
735 case AST_STATE_RESERVED:
737 case AST_STATE_OFFHOOK:
739 case AST_STATE_DIALING:
743 case AST_STATE_RINGING:
749 case AST_STATE_DIALING_OFFHOOK:
750 return "Dialing Offhook";
751 case AST_STATE_PRERING:
754 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
756 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
761 /*! \brief Gives the string form of a given transfer capability */
762 char *ast_transfercapability2str(int transfercapability)
764 switch (transfercapability) {
765 case AST_TRANS_CAP_SPEECH:
767 case AST_TRANS_CAP_DIGITAL:
769 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
770 return "RESTRICTED_DIGITAL";
771 case AST_TRANS_CAP_3_1K_AUDIO:
773 case AST_TRANS_CAP_DIGITAL_W_TONES:
774 return "DIGITAL_W_TONES";
775 case AST_TRANS_CAP_VIDEO:
782 /*! \brief Pick the best audio codec */
783 format_t ast_best_codec(format_t fmts)
785 /* This just our opinion, expressed in code. We are asked to choose
786 the best codec to use, given no information */
788 static const format_t prefs[] =
790 /*! Okay, ulaw is used by all telephony equipment, so start with it */
792 /*! Unless of course, you're a silly European, so then prefer ALAW */
797 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
799 /*! Okay, well, signed linear is easy to translate into other stuff */
800 AST_FORMAT_SLINEAR16,
802 /*! G.726 is standard ADPCM, in RFC3551 packing order */
804 /*! G.726 is standard ADPCM, in AAL2 packing order */
805 AST_FORMAT_G726_AAL2,
806 /*! ADPCM has great sound quality and is still pretty easy to translate */
808 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
809 translate and sounds pretty good */
811 /*! iLBC is not too bad */
813 /*! Speex is free, but computationally more expensive than GSM */
815 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
818 /*! G.729a is faster than 723 and slightly less expensive */
820 /*! Down to G.723.1 which is proprietary but at least designed for voice */
825 /* Strip out video */
826 fmts &= AST_FORMAT_AUDIO_MASK;
828 /* Find the first preferred codec in the format given */
829 for (x = 0; x < ARRAY_LEN(prefs); x++) {
834 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), fmts));
839 static const struct ast_channel_tech null_tech = {
841 .description = "Null channel (should not see this)",
844 static void ast_channel_destructor(void *obj);
845 static void ast_dummy_channel_destructor(void *obj);
847 /*! \brief Create a new channel structure */
848 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
849 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
850 const char *acctcode, const char *exten, const char *context,
851 const char *linkedid, const int amaflag, const char *file, int line,
852 const char *function, const char *name_fmt, va_list ap1, va_list ap2)
854 struct ast_channel *tmp;
857 struct varshead *headp;
860 /* If shutting down, don't allocate any new channels */
862 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
866 #if defined(REF_DEBUG)
867 if (!(tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line, function, 1))) {
870 #elif defined(__AST_DEBUG_MALLOC)
871 if (!(tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line, function, 0))) {
875 if (!(tmp = ao2_alloc(sizeof(*tmp), ast_channel_destructor))) {
880 if (!(tmp->sched = sched_context_create())) {
881 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
882 return ast_channel_unref(tmp);
885 if ((ast_string_field_init(tmp, 128))) {
886 return ast_channel_unref(tmp);
890 if (!(tmp->cid.cid_name = ast_strdup(cid_name))) {
891 return ast_channel_unref(tmp);
895 if (!(tmp->cid.cid_num = ast_strdup(cid_num))) {
896 return ast_channel_unref(tmp);
901 tmp->epfd = epoll_create(25);
904 for (x = 0; x < AST_MAX_FDS; x++) {
907 tmp->epfd_data[x] = NULL;
911 if ((tmp->timer = ast_timer_open())) {
913 tmp->timingfd = ast_timer_fd(tmp->timer);
919 if (pipe(tmp->alertpipe)) {
920 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
923 ast_timer_close(tmp->timer);
926 sched_context_destroy(tmp->sched);
927 ast_string_field_free_memory(tmp);
928 ast_free(tmp->cid.cid_name);
929 ast_free(tmp->cid.cid_num);
933 flags = fcntl(tmp->alertpipe[0], F_GETFL);
934 if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
935 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
936 close(tmp->alertpipe[0]);
937 close(tmp->alertpipe[1]);
938 goto alertpipe_failed;
940 flags = fcntl(tmp->alertpipe[1], F_GETFL);
941 if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
942 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
943 close(tmp->alertpipe[0]);
944 close(tmp->alertpipe[1]);
945 goto alertpipe_failed;
948 } else /* Make sure we've got it done right if they don't */
949 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
951 /* Always watch the alertpipe */
952 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
953 /* And timing pipe */
954 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
955 ast_string_field_set(tmp, name, "**Unknown**");
962 tmp->fin = global_fin;
963 tmp->fout = global_fout;
965 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
966 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
967 ast_atomic_fetchadd_int(&uniqueint, 1));
969 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
970 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
973 if (!ast_strlen_zero(linkedid)) {
974 ast_string_field_set(tmp, linkedid, linkedid);
977 ast_string_field_set(tmp, linkedid, tmp->uniqueid);
980 if (!ast_strlen_zero(name_fmt)) {
982 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
983 * And they all use slightly different formats for their name string.
984 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
985 * This means, that the stringfields must have a routine that takes the va_lists directly, and
986 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
987 * This new function was written so this can be accomplished.
989 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
990 tech = ast_strdupa(tmp->name);
991 if ((slash = strchr(tech, '/'))) {
996 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
998 /* These 4 variables need to be set up for the cdr_init() to work right */
1000 tmp->amaflags = amaflag;
1002 tmp->amaflags = ast_default_amaflags;
1004 if (!ast_strlen_zero(acctcode))
1005 ast_string_field_set(tmp, accountcode, acctcode);
1007 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
1009 if (!ast_strlen_zero(context))
1010 ast_copy_string(tmp->context, context, sizeof(tmp->context));
1012 strcpy(tmp->context, "default");
1014 if (!ast_strlen_zero(exten))
1015 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
1017 strcpy(tmp->exten, "s");
1021 tmp->cdr = ast_cdr_alloc();
1022 ast_cdr_init(tmp->cdr, tmp);
1023 ast_cdr_start(tmp->cdr);
1025 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1027 headp = &tmp->varshead;
1028 AST_LIST_HEAD_INIT_NOLOCK(headp);
1030 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
1032 AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
1034 ast_string_field_set(tmp, language, defaultlanguage);
1036 tmp->tech = &null_tech;
1038 ao2_link(channels, tmp);
1041 * and now, since the channel structure is built, and has its name, let's
1042 * call the manager event generator with this Newchannel event. This is the
1043 * proper and correct place to make this call, but you sure do have to pass
1044 * a lot of data into this func to do it here!
1046 if (ast_get_channel_tech(tech)) {
1047 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1049 "ChannelState: %d\r\n"
1050 "ChannelStateDesc: %s\r\n"
1051 "CallerIDNum: %s\r\n"
1052 "CallerIDName: %s\r\n"
1053 "AccountCode: %s\r\n"
1059 ast_state2str(state),
1071 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1072 const char *cid_name, const char *acctcode,
1073 const char *exten, const char *context,
1074 const char *linkedid, const int amaflag,
1075 const char *file, int line, const char *function,
1076 const char *name_fmt, ...)
1079 struct ast_channel *result;
1081 va_start(ap1, name_fmt);
1082 va_start(ap2, name_fmt);
1083 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1084 linkedid, amaflag, file, line, function, name_fmt, ap1, ap2);
1091 /* only do the minimum amount of work needed here to make a channel
1092 * structure that can be used to expand channel vars */
1093 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1094 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1096 struct ast_channel *ast_dummy_channel_alloc(void)
1099 struct ast_channel *tmp;
1100 struct varshead *headp;
1102 #if defined(REF_DEBUG)
1103 if (!(tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel", file, line, function, 1))) {
1106 #elif defined(__AST_DEBUG_MALLOC)
1107 if (!(tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel", file, line, function, 0))) {
1111 if (!(tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor))) {
1116 if ((ast_string_field_init(tmp, 128))) {
1117 ast_channel_unref(tmp);
1121 headp = &tmp->varshead;
1122 AST_LIST_HEAD_INIT_NOLOCK(headp);
1127 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1129 struct ast_frame *f;
1130 struct ast_frame *cur;
1132 unsigned int new_frames = 0;
1133 unsigned int new_voice_frames = 0;
1134 unsigned int queued_frames = 0;
1135 unsigned int queued_voice_frames = 0;
1136 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1138 ast_channel_lock(chan);
1140 /* See if the last frame on the queue is a hangup, if so don't queue anything */
1141 if ((cur = AST_LIST_LAST(&chan->readq)) &&
1142 (cur->frametype == AST_FRAME_CONTROL) &&
1143 (cur->subclass.integer == AST_CONTROL_HANGUP)) {
1144 ast_channel_unlock(chan);
1148 /* Build copies of all the frames and count them */
1149 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1150 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1151 if (!(f = ast_frdup(cur))) {
1152 ast_frfree(AST_LIST_FIRST(&frames));
1153 ast_channel_unlock(chan);
1157 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1159 if (f->frametype == AST_FRAME_VOICE) {
1164 /* Count how many frames exist on the queue */
1165 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1167 if (cur->frametype == AST_FRAME_VOICE) {
1168 queued_voice_frames++;
1172 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1174 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", chan->name);
1175 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
1176 /* Save the most recent frame */
1177 if (!AST_LIST_NEXT(cur, frame_list)) {
1179 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1183 AST_LIST_REMOVE_CURRENT(frame_list);
1187 AST_LIST_TRAVERSE_SAFE_END;
1191 AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1194 AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1195 AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1197 AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1200 if (chan->alertpipe[1] > -1) {
1201 if (write(chan->alertpipe[1], &blah, new_frames * sizeof(blah)) != (new_frames * sizeof(blah))) {
1202 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1203 chan->name, queued_frames, strerror(errno));
1205 } else if (chan->timingfd > -1) {
1206 ast_timer_enable_continuous(chan->timer);
1207 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1208 pthread_kill(chan->blocker, SIGURG);
1211 ast_channel_unlock(chan);
1216 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1218 return __ast_queue_frame(chan, fin, 0, NULL);
1221 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1223 return __ast_queue_frame(chan, fin, 1, NULL);
1226 /*! \brief Queue a hangup frame for channel */
1227 int ast_queue_hangup(struct ast_channel *chan)
1229 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1230 /* Yeah, let's not change a lock-critical value without locking */
1231 if (!ast_channel_trylock(chan)) {
1232 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1233 ast_channel_unlock(chan);
1235 return ast_queue_frame(chan, &f);
1238 /*! \brief Queue a hangup frame for channel */
1239 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1241 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1244 f.data.uint32 = cause;
1246 /* Yeah, let's not change a lock-critical value without locking */
1247 if (!ast_channel_trylock(chan)) {
1248 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1250 f.data.uint32 = chan->hangupcause;
1252 ast_channel_unlock(chan);
1255 return ast_queue_frame(chan, &f);
1258 /*! \brief Queue a control frame */
1259 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1261 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1262 return ast_queue_frame(chan, &f);
1265 /*! \brief Queue a control frame with payload */
1266 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1267 const void *data, size_t datalen)
1269 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1270 return ast_queue_frame(chan, &f);
1273 /*! \brief Set defer DTMF flag on channel */
1274 int ast_channel_defer_dtmf(struct ast_channel *chan)
1279 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1280 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1285 /*! \brief Unset defer DTMF flag on channel */
1286 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1289 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1292 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1293 void *data, int ao2_flags)
1295 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1298 struct ast_channel_iterator {
1299 /* storage for non-dynamically allocated iterator */
1300 struct ao2_iterator simple_iterator;
1301 /* pointer to the actual iterator (simple_iterator or a dynamically
1302 * allocated iterator)
1304 struct ao2_iterator *active_iterator;
1307 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1309 ao2_iterator_destroy(i->active_iterator);
1315 static struct ast_channel_iterator *channel_iterator_search(const char *name,
1316 size_t name_len, const char *exten,
1317 const char *context)
1319 struct ast_channel_iterator *i;
1320 struct ast_channel tmp_chan = {
1322 /* This is sort of a hack. Basically, we're using an arbitrary field
1323 * in ast_channel to pass the name_len for a prefix match. If this
1324 * gets changed, then the compare callback must be changed, too. */
1328 if (!(i = ast_calloc(1, sizeof(*i)))) {
1333 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1337 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1340 if (!(i->active_iterator = ao2_find(channels, &tmp_chan,
1341 OBJ_MULTIPLE | ((!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0)))) {
1349 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1351 return channel_iterator_search(NULL, 0, exten, context);
1354 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1356 return channel_iterator_search(name, name_len, NULL, NULL);
1359 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1361 struct ast_channel_iterator *i;
1363 if (!(i = ast_calloc(1, sizeof(*i)))) {
1367 i->simple_iterator = ao2_iterator_init(channels, 0);
1368 i->active_iterator = &i->simple_iterator;
1373 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1375 return ao2_iterator_next(i->active_iterator);
1378 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1380 struct ast_channel *chan = obj, *cmp_args = arg;
1382 int ret = CMP_MATCH;
1384 /* This is sort of a hack. Basically, we're using an arbitrary field
1385 * in ast_channel to pass the name_len for a prefix match. If this
1386 * gets changed, then the uses of ao2_find() must be changed, too. */
1387 name_len = cmp_args->rings;
1389 ast_channel_lock(chan);
1391 if (!ast_strlen_zero(cmp_args->name)) { /* match by name */
1392 if ((!name_len && strcasecmp(chan->name, cmp_args->name)) ||
1393 (name_len && strncasecmp(chan->name, cmp_args->name, name_len))) {
1394 ret = 0; /* name match failed */
1396 } else if (!ast_strlen_zero(cmp_args->exten)) {
1397 if (cmp_args->context && strcasecmp(chan->context, cmp_args->context) &&
1398 strcasecmp(chan->macrocontext, cmp_args->context)) {
1399 ret = 0; /* context match failed */
1401 if (ret && strcasecmp(chan->exten, cmp_args->exten) &&
1402 strcasecmp(chan->macroexten, cmp_args->exten)) {
1403 ret = 0; /* exten match failed */
1405 } else if (!ast_strlen_zero(cmp_args->uniqueid)) {
1406 if ((!name_len && strcasecmp(chan->uniqueid, cmp_args->uniqueid)) ||
1407 (name_len && strncasecmp(chan->uniqueid, cmp_args->uniqueid, name_len))) {
1408 ret = 0; /* uniqueid match failed */
1414 ast_channel_unlock(chan);
1419 static struct ast_channel *ast_channel_get_full(const char *name, size_t name_len,
1420 const char *exten, const char *context)
1422 struct ast_channel tmp_chan = {
1424 /* This is sort of a hack. Basically, we're using an arbitrary field
1425 * in ast_channel to pass the name_len for a prefix match. If this
1426 * gets changed, then the compare callback must be changed, too. */
1429 struct ast_channel *chan;
1432 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1436 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1439 if ((chan = ao2_find(channels, &tmp_chan,
1440 (!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0))) {
1448 /* If name was specified, but the result was NULL,
1449 * try a search on uniqueid, instead. */
1452 struct ast_channel tmp_chan2 = {
1457 return ao2_find(channels, &tmp_chan2, 0);
1461 struct ast_channel *ast_channel_get_by_name(const char *name)
1463 return ast_channel_get_full(name, 0, NULL, NULL);
1466 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1468 return ast_channel_get_full(name, name_len, NULL, NULL);
1471 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1473 return ast_channel_get_full(NULL, 0, exten, context);
1476 int ast_is_deferrable_frame(const struct ast_frame *frame)
1478 /* Do not add a default entry in this switch statement. Each new
1479 * frame type should be addressed directly as to whether it should
1480 * be queued up or not.
1482 switch (frame->frametype) {
1483 case AST_FRAME_DTMF_END:
1484 case AST_FRAME_CONTROL:
1485 case AST_FRAME_TEXT:
1486 case AST_FRAME_IMAGE:
1487 case AST_FRAME_HTML:
1490 case AST_FRAME_DTMF_BEGIN:
1491 case AST_FRAME_VOICE:
1492 case AST_FRAME_VIDEO:
1493 case AST_FRAME_NULL:
1496 case AST_FRAME_MODEM:
1502 /*! \brief Wait, look for hangups and condition arg */
1503 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1505 struct ast_frame *f;
1506 struct ast_silence_generator *silgen = NULL;
1508 AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1510 AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1512 /* If no other generator is present, start silencegen while waiting */
1513 if (ast_opt_transmit_silence && !chan->generatordata) {
1514 silgen = ast_channel_start_silence_generator(chan);
1518 struct ast_frame *dup_f = NULL;
1519 if (cond && ((*cond)(data) == 0)) {
1522 ms = ast_waitfor(chan, ms);
1534 if (!ast_is_deferrable_frame(f)) {
1539 if ((dup_f = ast_frisolate(f))) {
1543 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1548 /* stop silgen if present */
1550 ast_channel_stop_silence_generator(chan, silgen);
1553 /* We need to free all the deferred frames, but we only need to
1554 * queue the deferred frames if there was no error and no
1555 * hangup was received
1557 ast_channel_lock(chan);
1558 while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1560 ast_queue_frame_head(chan, f);
1564 ast_channel_unlock(chan);
1569 /*! \brief Wait, look for hangups */
1570 int ast_safe_sleep(struct ast_channel *chan, int ms)
1572 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1575 static void free_cid(struct ast_callerid *cid)
1578 ast_free(cid->cid_dnid);
1580 ast_free(cid->cid_num);
1582 ast_free(cid->cid_name);
1584 ast_free(cid->cid_ani);
1586 ast_free(cid->cid_tag);
1587 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = NULL;
1588 ast_party_subaddress_free(&cid->subaddress);
1589 ast_party_subaddress_free(&cid->dialed_subaddress);
1592 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1594 /* Safe, even if already unlinked. */
1595 ao2_unlink(channels, chan);
1596 return ast_channel_unref(chan);
1599 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1603 init->odd_even_indicator = 0;
1607 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1610 /* Don't copy to self */
1615 ast_free(dest->str);
1617 dest->str = ast_strdup(src->str);
1618 dest->type = src->type;
1619 dest->odd_even_indicator = src->odd_even_indicator;
1620 dest->valid = src->valid;
1623 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1626 init->type = guide->type;
1627 init->odd_even_indicator = guide->odd_even_indicator;
1628 init->valid = guide->valid;
1631 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1634 /* Don't set to self */
1638 if (src->str && src->str != dest->str) {
1640 ast_free(dest->str);
1642 dest->str = ast_strdup(src->str);
1645 dest->type = src->type;
1646 dest->odd_even_indicator = src->odd_even_indicator;
1647 dest->valid = src->valid;
1650 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1653 ast_free(doomed->str);
1660 * \brief Initialize the given party id structure.
1662 * \param init Party id structure to initialize.
1666 static void ast_party_id_init(struct ast_party_id *init)
1668 init->number = NULL;
1671 init->number_type = 0; /* Unknown */
1672 init->number_presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1673 ast_party_subaddress_init(&init->subaddress);
1678 * \brief Copy the source party id information to the destination party id.
1680 * \param dest Destination party id
1681 * \param src Source party id
1685 static void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1688 /* Don't copy to self */
1693 ast_free(dest->number);
1695 dest->number = ast_strdup(src->number);
1698 ast_free(dest->name);
1700 dest->name = ast_strdup(src->name);
1703 ast_free(dest->tag);
1705 dest->tag = ast_strdup(src->tag);
1707 dest->number_type = src->number_type;
1708 dest->number_presentation = src->number_presentation;
1709 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1714 * \brief Initialize the given party id structure using the given guide
1715 * for a set update operation.
1718 * The initialization is needed to allow a set operation to know if a
1719 * value needs to be updated. Simple integers need the guide's original
1720 * value in case the set operation is not trying to set a new value.
1721 * String values are simply set to NULL pointers if they are not going
1724 * \param init Party id structure to initialize.
1725 * \param guide Source party id to use as a guide in initializing.
1729 static void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1731 init->number = NULL;
1734 init->number_type = guide->number_type;
1735 init->number_presentation = guide->number_presentation;
1736 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1741 * \brief Set the source party id information into the destination party id.
1743 * \param dest Destination party id
1744 * \param src Source party id
1748 static void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src)
1751 /* Don't set to self */
1755 if (src->name && src->name != dest->name) {
1757 ast_free(dest->name);
1759 dest->name = ast_strdup(src->name);
1762 if (src->number && src->number != dest->number) {
1764 ast_free(dest->number);
1766 dest->number = ast_strdup(src->number);
1769 if (src->tag && src->tag != dest->tag) {
1771 ast_free(dest->tag);
1773 dest->tag = ast_strdup(src->tag);
1776 dest->number_type = src->number_type;
1777 dest->number_presentation = src->number_presentation;
1778 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1783 * \brief Destroy the party id contents
1785 * \param doomed The party id to destroy.
1789 static void ast_party_id_free(struct ast_party_id *doomed)
1791 if (doomed->number) {
1792 ast_free(doomed->number);
1793 doomed->number = NULL;
1797 ast_free(doomed->name);
1798 doomed->name = NULL;
1802 ast_free(doomed->tag);
1805 ast_party_subaddress_free(&doomed->subaddress);
1808 void ast_party_caller_init(struct ast_party_caller *init)
1810 ast_party_id_init(&init->id);
1815 void ast_party_caller_copy(struct ast_callerid *dest, const struct ast_callerid *src)
1818 /* Don't copy to self */
1823 /* Copy caller-id specific information ONLY from struct ast_callerid */
1826 ast_free(dest->cid_num);
1828 dest->cid_num = ast_strdup(src->cid_num);
1832 ast_free(dest->cid_name);
1834 dest->cid_name = ast_strdup(src->cid_name);
1836 if (dest->cid_tag) {
1837 ast_free(dest->cid_tag);
1839 dest->cid_tag = ast_strdup(src->cid_tag);
1841 dest->cid_ton = src->cid_ton;
1842 dest->cid_pres = src->cid_pres;
1847 ast_free(dest->cid_ani);
1849 dest->cid_ani = ast_strdup(src->cid_ani);
1851 dest->cid_ani2 = src->cid_ani2;
1853 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1857 /* The src and dest parameter types will become struct ast_party_caller ptrs. */
1858 /* This is future code */
1860 ast_party_id_copy(&dest->id, &src->id);
1863 ast_free(dest->ani);
1865 dest->ani = ast_strdup(src->ani);
1867 dest->ani2 = src->ani2;
1871 void ast_party_connected_line_init(struct ast_party_connected_line *init)
1873 ast_party_id_init(&init->id);
1876 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
1879 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
1882 /* Don't copy to self */
1886 ast_party_id_copy(&dest->id, &src->id);
1889 ast_free(dest->ani);
1891 dest->ani = ast_strdup(src->ani);
1893 dest->ani2 = src->ani2;
1894 dest->source = src->source;
1897 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
1899 ast_party_id_set_init(&init->id, &guide->id);
1901 init->ani2 = guide->ani2;
1902 init->source = guide->source;
1905 void ast_party_connected_line_set(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
1907 ast_party_id_set(&dest->id, &src->id);
1909 if (src->ani && src->ani != dest->ani) {
1911 ast_free(dest->ani);
1913 dest->ani = ast_strdup(src->ani);
1916 dest->ani2 = src->ani2;
1917 dest->source = src->source;
1920 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_callerid *cid)
1922 connected->id.number = cid->cid_num;
1923 connected->id.name = cid->cid_name;
1924 connected->id.number_type = cid->cid_ton;
1925 connected->id.number_presentation = cid->cid_pres;
1926 connected->id.tag = cid->cid_tag;
1927 connected->id.subaddress = cid->subaddress;
1929 connected->ani = cid->cid_ani;
1930 connected->ani2 = cid->cid_ani2;
1931 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
1934 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
1936 ast_party_id_free(&doomed->id);
1939 ast_free(doomed->ani);
1944 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
1947 /* Don't copy to self */
1951 ast_party_id_copy(&dest->from, &src->from);
1952 ast_party_id_copy(&dest->to, &src->to);
1953 dest->count = src->count;
1954 dest->reason = src->reason;
1957 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
1959 ast_party_id_set_init(&init->from, &guide->from);
1960 ast_party_id_set_init(&init->to, &guide->to);
1961 init->count = guide->count;
1962 init->reason = guide->reason;
1965 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
1967 ast_party_id_free(&doomed->from);
1968 ast_party_id_free(&doomed->to);
1971 /*! \brief Free a channel structure */
1972 static void ast_channel_destructor(void *obj)
1974 struct ast_channel *chan = obj;
1979 struct ast_var_t *vardata;
1980 struct ast_frame *f;
1981 struct varshead *headp;
1982 struct ast_datastore *datastore = NULL;
1983 char name[AST_CHANNEL_NAME], *dashptr;
1985 headp = &chan->varshead;
1987 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
1988 ast_cel_check_retire_linkedid(chan);
1990 /* Get rid of each of the data stores on the channel */
1991 ast_channel_lock(chan);
1992 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1993 /* Free the data store */
1994 ast_datastore_free(datastore);
1995 ast_channel_unlock(chan);
1997 /* Lock and unlock the channel just to be sure nobody has it locked still
1998 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1999 ast_channel_lock(chan);
2000 ast_channel_unlock(chan);
2002 if (chan->tech_pvt) {
2003 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
2004 ast_free(chan->tech_pvt);
2008 sched_context_destroy(chan->sched);
2010 ast_copy_string(name, chan->name, sizeof(name));
2011 if ((dashptr = strrchr(name, '-'))) {
2015 /* Stop monitoring */
2017 chan->monitor->stop( chan, 0 );
2019 /* If there is native format music-on-hold state, free it */
2020 if (chan->music_state)
2021 ast_moh_cleanup(chan);
2023 /* Free translators */
2024 if (chan->readtrans)
2025 ast_translator_free_path(chan->readtrans);
2026 if (chan->writetrans)
2027 ast_translator_free_path(chan->writetrans);
2029 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
2031 free_cid(&chan->cid);
2032 ast_party_connected_line_free(&chan->connected);
2033 ast_party_redirecting_free(&chan->redirecting);
2035 /* Close pipes if appropriate */
2036 if ((fd = chan->alertpipe[0]) > -1)
2038 if ((fd = chan->alertpipe[1]) > -1)
2041 ast_timer_close(chan->timer);
2044 for (i = 0; i < AST_MAX_FDS; i++) {
2045 if (chan->epfd_data[i])
2046 free(chan->epfd_data[i]);
2050 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
2053 /* loop over the variables list, freeing all data and deleting list items */
2054 /* no need to lock the list, as the channel is already locked */
2056 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2057 ast_var_delete(vardata);
2059 ast_app_group_discard(chan);
2061 /* Destroy the jitterbuffer */
2062 ast_jb_destroy(chan);
2065 ast_cdr_discard(chan->cdr);
2070 chan->zone = ast_tone_zone_unref(chan->zone);
2073 ast_string_field_free_memory(chan);
2075 /* Queue an unknown state, because, while we know that this particular
2076 * instance is dead, we don't know the state of all other possible
2078 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, name);
2081 /*! \brief Free a dummy channel structure */
2082 static void ast_dummy_channel_destructor(void *obj)
2084 struct ast_channel *chan = obj;
2085 struct ast_var_t *vardata;
2086 struct varshead *headp;
2088 headp = &chan->varshead;
2090 free_cid(&chan->cid);
2092 /* loop over the variables list, freeing all data and deleting list items */
2093 /* no need to lock the list, as the channel is already locked */
2094 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2095 ast_var_delete(vardata);
2098 ast_cdr_discard(chan->cdr);
2102 ast_string_field_free_memory(chan);
2105 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2107 return ast_datastore_alloc(info, uid);
2110 int ast_channel_datastore_free(struct ast_datastore *datastore)
2112 return ast_datastore_free(datastore);
2115 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2117 struct ast_datastore *datastore = NULL, *datastore2;
2119 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
2120 if (datastore->inheritance > 0) {
2121 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2123 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2124 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2125 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
2132 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2136 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
2141 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2143 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
2146 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2148 struct ast_datastore *datastore = NULL;
2153 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
2154 if (datastore->info != info) {
2159 /* matched by type only */
2163 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2164 /* Matched by type AND uid */
2168 AST_LIST_TRAVERSE_SAFE_END;
2173 /*! Set the file descriptor on the channel */
2174 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2177 struct epoll_event ev;
2178 struct ast_epoll_data *aed = NULL;
2180 if (chan->fds[which] > -1) {
2181 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2182 aed = chan->epfd_data[which];
2185 /* If this new fd is valid, add it to the epoll */
2187 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2190 chan->epfd_data[which] = aed;
2194 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2196 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2198 /* We don't have to keep around this epoll data structure now */
2200 chan->epfd_data[which] = NULL;
2203 chan->fds[which] = fd;
2207 /*! Add a channel to an optimized waitfor */
2208 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2211 struct epoll_event ev;
2214 if (chan0->epfd == -1)
2217 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2218 for (i = 0; i < AST_MAX_FDS; i++) {
2219 if (chan1->fds[i] == -1)
2221 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2222 ev.data.ptr = chan1->epfd_data[i];
2223 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2230 /*! Delete a channel from an optimized waitfor */
2231 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2234 struct epoll_event ev;
2237 if (chan0->epfd == -1)
2240 for (i = 0; i < AST_MAX_FDS; i++) {
2241 if (chan1->fds[i] == -1)
2243 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2250 /*! \brief Softly hangup a channel, don't lock */
2251 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2253 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
2254 /* Inform channel driver that we need to be hung up, if it cares */
2255 chan->_softhangup |= cause;
2256 ast_queue_frame(chan, &ast_null_frame);
2257 /* Interrupt any poll call or such */
2258 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2259 pthread_kill(chan->blocker, SIGURG);
2263 /*! \brief Softly hangup a channel, lock */
2264 int ast_softhangup(struct ast_channel *chan, int cause)
2268 ast_channel_lock(chan);
2269 res = ast_softhangup_nolock(chan, cause);
2270 ast_channel_unlock(chan);
2275 static void free_translation(struct ast_channel *clonechan)
2277 if (clonechan->writetrans)
2278 ast_translator_free_path(clonechan->writetrans);
2279 if (clonechan->readtrans)
2280 ast_translator_free_path(clonechan->readtrans);
2281 clonechan->writetrans = NULL;
2282 clonechan->readtrans = NULL;
2283 clonechan->rawwriteformat = clonechan->nativeformats;
2284 clonechan->rawreadformat = clonechan->nativeformats;
2287 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2289 struct ast_channel *bridge;
2291 ast_channel_lock(chan);
2292 if (force || ast_strlen_zero(chan->hangupsource)) {
2293 ast_string_field_set(chan, hangupsource, source);
2295 bridge = ast_bridged_channel(chan);
2296 ast_channel_unlock(chan);
2298 if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
2299 ast_channel_lock(bridge);
2300 ast_string_field_set(chan, hangupsource, source);
2301 ast_channel_unlock(bridge);
2305 /*! \brief Hangup a channel */
2306 int ast_hangup(struct ast_channel *chan)
2309 char extra_str[64]; /* used for cel logging below */
2311 /* Don't actually hang up a channel that will masquerade as someone else, or
2312 if someone is going to masquerade as us */
2313 ast_channel_lock(chan);
2315 if (chan->audiohooks) {
2316 ast_audiohook_detach_list(chan->audiohooks);
2317 chan->audiohooks = NULL;
2320 ast_autoservice_stop(chan);
2323 ast_channel_unlock(chan);
2324 if (ast_do_masquerade(chan)) {
2325 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2327 ast_channel_lock(chan);
2331 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
2332 ast_channel_unlock(chan);
2335 /* If this channel is one which will be masqueraded into something,
2336 mark it as a zombie already, so we know to free it later */
2338 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2339 ast_channel_unlock(chan);
2342 ast_channel_unlock(chan);
2344 ao2_unlink(channels, chan);
2346 ast_channel_lock(chan);
2347 free_translation(chan);
2348 /* Close audio stream */
2350 ast_closestream(chan->stream);
2351 chan->stream = NULL;
2353 /* Close video stream */
2354 if (chan->vstream) {
2355 ast_closestream(chan->vstream);
2356 chan->vstream = NULL;
2359 sched_context_destroy(chan->sched);
2363 if (chan->generatordata) /* Clear any tone stuff remaining */
2364 if (chan->generator && chan->generator->release)
2365 chan->generator->release(chan, chan->generatordata);
2366 chan->generatordata = NULL;
2367 chan->generator = NULL;
2369 snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2370 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2372 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2373 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2374 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2375 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
2376 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2378 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
2379 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
2380 if (chan->tech->hangup)
2381 res = chan->tech->hangup(chan);
2383 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
2386 ast_channel_unlock(chan);
2388 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2391 "CallerIDNum: %s\r\n"
2392 "CallerIDName: %s\r\n"
2394 "Cause-txt: %s\r\n",
2397 S_OR(chan->cid.cid_num, "<unknown>"),
2398 S_OR(chan->cid.cid_name, "<unknown>"),
2400 ast_cause2str(chan->hangupcause)
2403 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
2404 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
2405 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2406 ast_channel_lock(chan);
2408 ast_cdr_end(chan->cdr);
2409 ast_cdr_detach(chan->cdr);
2411 ast_channel_unlock(chan);
2414 chan = ast_channel_release(chan);
2419 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2423 ast_channel_lock(chan);
2425 /* You can't answer an outbound call */
2426 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2427 ast_channel_unlock(chan);
2431 /* Stop if we're a zombie or need a soft hangup */
2432 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2433 ast_channel_unlock(chan);
2437 ast_channel_unlock(chan);
2439 switch (chan->_state) {
2440 case AST_STATE_RINGING:
2441 case AST_STATE_RING:
2442 ast_channel_lock(chan);
2443 if (chan->tech->answer) {
2444 res = chan->tech->answer(chan);
2446 ast_setstate(chan, AST_STATE_UP);
2448 ast_cdr_answer(chan->cdr);
2450 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2451 ast_channel_unlock(chan);
2454 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2455 /* Calling ast_cdr_answer when it it has previously been called
2456 * is essentially a no-op, so it is safe.
2459 ast_cdr_answer(chan->cdr);
2466 ast_indicate(chan, -1);
2467 chan->visible_indication = 0;
2472 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2475 enum ast_channel_state old_state;
2477 old_state = chan->_state;
2478 if ((res = ast_raw_answer(chan, cdr_answer))) {
2482 switch (old_state) {
2483 case AST_STATE_RINGING:
2484 case AST_STATE_RING:
2485 /* wait for media to start flowing, but don't wait any longer
2486 * than 'delay' or 500 milliseconds, whichever is longer
2489 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2490 struct ast_frame *cur, *new;
2491 int ms = MAX(delay, 500);
2492 unsigned int done = 0;
2494 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2497 ms = ast_waitfor(chan, ms);
2499 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
2504 ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
2507 cur = ast_read(chan);
2508 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2509 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2514 ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
2518 if ((new = ast_frisolate(cur)) != cur) {
2522 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2524 /* if a specific delay period was requested, continue
2525 * until that delay has passed. don't stop just because
2526 * incoming media has arrived.
2532 switch (new->frametype) {
2533 /* all of these frametypes qualify as 'media' */
2534 case AST_FRAME_VOICE:
2535 case AST_FRAME_VIDEO:
2536 case AST_FRAME_TEXT:
2537 case AST_FRAME_DTMF_BEGIN:
2538 case AST_FRAME_DTMF_END:
2539 case AST_FRAME_IMAGE:
2540 case AST_FRAME_HTML:
2541 case AST_FRAME_MODEM:
2544 case AST_FRAME_CONTROL:
2546 case AST_FRAME_NULL:
2557 ast_channel_lock(chan);
2558 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2559 ast_queue_frame_head(chan, cur);
2562 ast_channel_unlock(chan);
2573 int ast_answer(struct ast_channel *chan)
2575 return __ast_answer(chan, 0, 1);
2578 void ast_deactivate_generator(struct ast_channel *chan)
2580 ast_channel_lock(chan);
2581 if (chan->generatordata) {
2582 if (chan->generator && chan->generator->release)
2583 chan->generator->release(chan, chan->generatordata);
2584 chan->generatordata = NULL;
2585 chan->generator = NULL;
2586 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2587 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2588 ast_settimeout(chan, 0, NULL, NULL);
2590 ast_channel_unlock(chan);
2593 static int generator_force(const void *data)
2595 /* Called if generator doesn't have data */
2598 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2599 struct ast_channel *chan = (struct ast_channel *)data;
2601 ast_channel_lock(chan);
2602 tmp = chan->generatordata;
2603 chan->generatordata = NULL;
2604 if (chan->generator)
2605 generate = chan->generator->generate;
2606 ast_channel_unlock(chan);
2608 if (!tmp || !generate)
2611 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
2613 chan->generatordata = tmp;
2616 ast_debug(1, "Auto-deactivating generator\n");
2617 ast_deactivate_generator(chan);
2623 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2627 ast_channel_lock(chan);
2628 if (chan->generatordata) {
2629 if (chan->generator && chan->generator->release)
2630 chan->generator->release(chan, chan->generatordata);
2631 chan->generatordata = NULL;
2633 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2637 ast_settimeout(chan, 50, generator_force, chan);
2638 chan->generator = gen;
2640 ast_channel_unlock(chan);
2647 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2648 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2651 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2655 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2657 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2658 int *exception, int *outfd, int *ms)
2660 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2661 int *exception, int *outfd, int *ms)
2664 struct timeval start = { 0 , 0 };
2665 struct pollfd *pfds = NULL;
2670 struct timeval now = { 0, 0 };
2671 struct timeval whentohangup = { 0, 0 }, diff;
2672 struct ast_channel *winner = NULL;
2678 if ((sz = n * AST_MAX_FDS + nfds)) {
2679 pfds = alloca(sizeof(*pfds) * sz);
2680 fdmap = alloca(sizeof(*fdmap) * sz);
2688 /* Perform any pending masquerades */
2689 for (x = 0; x < n; x++) {
2690 if (c[x]->masq && ast_do_masquerade(c[x])) {
2691 ast_log(LOG_WARNING, "Masquerade failed\n");
2696 ast_channel_lock(c[x]);
2697 if (!ast_tvzero(c[x]->whentohangup)) {
2698 if (ast_tvzero(whentohangup))
2700 diff = ast_tvsub(c[x]->whentohangup, now);
2701 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
2702 /* Should already be hungup */
2703 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2704 ast_channel_unlock(c[x]);
2707 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
2708 whentohangup = diff;
2710 ast_channel_unlock(c[x]);
2712 /* Wait full interval */
2714 /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
2715 if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
2716 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
2717 if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
2720 } else if (!ast_tvzero(whentohangup) && rms < 0) {
2721 /* Tiny corner case... call would need to last >24 days */
2725 * Build the pollfd array, putting the channels' fds first,
2726 * followed by individual fds. Order is important because
2727 * individual fd's must have priority over channel fds.
2730 for (x = 0; x < n; x++) {
2731 for (y = 0; y < AST_MAX_FDS; y++) {
2732 fdmap[max].fdno = y; /* fd y is linked to this pfds */
2733 fdmap[max].chan = x; /* channel x is linked to this pfds */
2734 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
2736 CHECK_BLOCKING(c[x]);
2738 /* Add the individual fds */
2739 for (x = 0; x < nfds; x++) {
2740 fdmap[max].chan = -1;
2741 max += ast_add_fd(&pfds[max], fds[x]);
2745 start = ast_tvnow();
2747 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
2752 res = ast_poll(pfds, max, kbrms);
2755 } while (!res && (rms > 0));
2757 res = ast_poll(pfds, max, rms);
2759 for (x = 0; x < n; x++)
2760 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
2761 if (res < 0) { /* Simulate a timeout if we were interrupted */
2766 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
2768 for (x = 0; x < n; x++) {
2769 if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
2770 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2776 if (res == 0) { /* no fd ready, reset timeout and done */
2777 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
2781 * Then check if any channel or fd has a pending event.
2782 * Remember to check channels first and fds last, as they
2783 * must have priority on setting 'winner'
2785 for (x = 0; x < max; x++) {
2786 res = pfds[x].revents;
2789 if (fdmap[x].chan >= 0) { /* this is a channel */
2790 winner = c[fdmap[x].chan]; /* override previous winners */
2792 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2794 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2795 winner->fdno = fdmap[x].fdno;
2796 } else { /* this is an fd */
2798 *outfd = pfds[x].fd;
2800 *exception = (res & POLLPRI) ? -1 : 0;
2805 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2813 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
2815 struct timeval start = { 0 , 0 };
2817 struct epoll_event ev[1];
2818 long diff, rms = *ms;
2819 struct ast_channel *winner = NULL;
2820 struct ast_epoll_data *aed = NULL;
2823 /* See if this channel needs to be masqueraded */
2824 if (chan->masq && ast_do_masquerade(chan)) {
2825 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
2830 ast_channel_lock(chan);
2831 /* Figure out their timeout */
2832 if (!ast_tvzero(chan->whentohangup)) {
2833 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
2834 /* They should already be hungup! */
2835 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2836 ast_channel_unlock(chan);
2839 /* If this value is smaller then the current one... make it priority */
2844 ast_channel_unlock(chan);
2846 /* Time to make this channel block... */
2847 CHECK_BLOCKING(chan);
2850 start = ast_tvnow();
2852 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
2853 res = epoll_wait(chan->epfd, ev, 1, rms);
2856 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2858 /* Simulate a timeout if we were interrupted */
2865 /* If this channel has a timeout see if it expired */
2866 if (!ast_tvzero(chan->whentohangup)) {
2867 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
2868 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2873 /* No fd ready, reset timeout and be done for now */
2879 /* See what events are pending */
2880 aed = ev[0].data.ptr;
2881 chan->fdno = aed->which;
2882 if (ev[0].events & EPOLLPRI)
2883 ast_set_flag(chan, AST_FLAG_EXCEPTION);
2885 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2888 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2896 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2898 struct timeval start = { 0 , 0 };
2900 struct epoll_event ev[25] = { { 0, } };
2901 struct timeval now = { 0, 0 };
2902 long whentohangup = 0, diff = 0, rms = *ms;
2903 struct ast_channel *winner = NULL;
2905 for (i = 0; i < n; i++) {
2906 if (c[i]->masq && ast_do_masquerade(c[i])) {
2907 ast_log(LOG_WARNING, "Masquerade failed\n");
2912 ast_channel_lock(c[i]);
2913 if (!ast_tvzero(c[i]->whentohangup)) {
2914 if (whentohangup == 0)
2916 if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
2917 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2918 ast_channel_unlock(c[i]);
2921 if (!whentohangup || whentohangup > diff)
2922 whentohangup = diff;
2924 ast_channel_unlock(c[i]);
2925 CHECK_BLOCKING(c[i]);
2931 if (*ms >= 0 && *ms < rms)
2936 start = ast_tvnow();
2938 res = epoll_wait(c[0]->epfd, ev, 25, rms);
2940 for (i = 0; i < n; i++)
2941 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2951 for (i = 0; i < n; i++) {
2952 if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
2953 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2965 for (i = 0; i < res; i++) {
2966 struct ast_epoll_data *aed = ev[i].data.ptr;
2968 if (!ev[i].events || !aed)
2972 if (ev[i].events & EPOLLPRI)
2973 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2975 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2976 winner->fdno = aed->which;
2980 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2988 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2989 int *exception, int *outfd, int *ms)
2991 /* Clear all provided values in one place. */
2997 /* If no epoll file descriptor is available resort to classic nandfds */
2998 if (!n || nfds || c[0]->epfd == -1)
2999 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3000 else if (!nfds && n == 1)
3001 return ast_waitfor_nandfds_simple(c[0], ms);
3003 return ast_waitfor_nandfds_complex(c, n, ms);
3007 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3009 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3012 int ast_waitfor(struct ast_channel *c, int ms)
3014 int oldms = ms; /* -1 if no timeout */
3016 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3017 if ((ms < 0) && (oldms < 0))
3022 /* XXX never to be called with ms = -1 */
3023 int ast_waitfordigit(struct ast_channel *c, int ms)
3025 return ast_waitfordigit_full(c, ms, -1, -1);
3028 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3031 unsigned int real_rate = rate, max_rate;
3033 ast_channel_lock(c);
3035 if (c->timingfd == -1) {
3036 ast_channel_unlock(c);
3045 if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
3046 real_rate = max_rate;
3049 ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3051 res = ast_timer_set_rate(c->timer, real_rate);
3053 c->timingfunc = func;
3054 c->timingdata = data;
3056 ast_channel_unlock(c);
3061 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
3063 /* Stop if we're a zombie or need a soft hangup */
3064 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3067 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3068 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
3070 /* Wait for a digit, no more than ms milliseconds total. */
3073 struct ast_channel *rchan;
3077 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3079 if (!rchan && outfd < 0 && ms) {
3080 if (errno == 0 || errno == EINTR)
3082 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
3083 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3085 } else if (outfd > -1) {
3086 /* The FD we were watching has something waiting */
3087 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
3088 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3092 struct ast_frame *f = ast_read(c);
3096 switch (f->frametype) {
3097 case AST_FRAME_DTMF_BEGIN:
3099 case AST_FRAME_DTMF_END:
3100 res = f->subclass.integer;
3102 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3104 case AST_FRAME_CONTROL:
3105 switch (f->subclass.integer) {
3106 case AST_CONTROL_HANGUP:
3108 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3110 case AST_CONTROL_RINGING:
3111 case AST_CONTROL_ANSWER:
3112 case AST_CONTROL_SRCUPDATE:
3113 case AST_CONTROL_SRCCHANGE:
3114 case AST_CONTROL_CONNECTED_LINE:
3115 case AST_CONTROL_REDIRECTING:
3119 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
3123 case AST_FRAME_VOICE:
3124 /* Write audio if appropriate */
3126 if (write(audiofd, f->data.ptr, f->datalen) < 0) {
3127 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3138 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3140 return 0; /* Time is up */
3143 static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
3145 ast_manager_event(chan, EVENT_FLAG_DTMF,
3153 chan->name, chan->uniqueid, digit, direction, begin, end);
3156 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
3158 if (chan->generator && chan->generator->generate && chan->generatordata && !ast_internal_timing_enabled(chan)) {
3159 void *tmp = chan->generatordata;
3160 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = chan->generator->generate;
3164 if (chan->timingfunc) {
3165 ast_debug(1, "Generator got voice, switching to phase locked mode\n");
3166 ast_settimeout(chan, 0, NULL, NULL);
3169 chan->generatordata = NULL; /* reset, to let writes go through */
3171 if (f->subclass.codec != chan->writeformat) {
3173 factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass.codec));
3174 samples = (int) ( ((float) f->samples) * factor );
3176 samples = f->samples;
3179 /* This unlock is here based on two assumptions that hold true at this point in the
3180 * code. 1) this function is only called from within __ast_read() and 2) all generators
3181 * call ast_write() in their generate callback.
3183 * The reason this is added is so that when ast_write is called, the lock that occurs
3184 * there will not recursively lock the channel. Doing this will cause intended deadlock
3185 * avoidance not to work in deeper functions
3187 ast_channel_unlock(chan);
3188 res = generate(chan, tmp, f->datalen, samples);
3189 ast_channel_lock(chan);
3190 chan->generatordata = tmp;
3192 ast_debug(1, "Auto-deactivating generator\n");
3193 ast_deactivate_generator(chan);
3196 } else if (f->frametype == AST_FRAME_CNG) {
3197 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
3198 ast_debug(1, "Generator got CNG, switching to timed mode\n");
3199 ast_settimeout(chan, 50, generator_force, chan);
3204 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3206 struct ast_frame *fr = &chan->dtmff;
3208 fr->frametype = AST_FRAME_DTMF_END;
3209 fr->subclass.integer = f->subclass.integer;
3212 /* The only time this function will be called is for a frame that just came
3213 * out of the channel driver. So, we want to stick it on the tail of the
3216 ast_queue_frame(chan, fr);
3220 * \brief Determine whether or not we should ignore DTMF in the readq
3222 static inline int should_skip_dtmf(struct ast_channel *chan)
3224 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
3225 /* We're in the middle of emulating a digit, or DTMF has been
3226 * explicitly deferred. Skip this digit, then. */
3230 if (!ast_tvzero(chan->dtmf_tv) &&
3231 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3232 /* We're not in the middle of a digit, but it hasn't been long enough
3233 * since the last digit, so we'll have to skip DTMF for now. */
3241 * \brief calculates the number of samples to jump forward with in a monitor stream.
3243 * \note When using ast_seekstream() with the read and write streams of a monitor,
3244 * the number of samples to seek forward must be of the same sample rate as the stream
3245 * or else the jump will not be calculated correctly.
3247 * \retval number of samples to seek forward after rate conversion.
3249 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
3251 int diff = sample_rate - seek_rate;
3254 samples = samples / (float) (sample_rate / seek_rate);
3255 } else if (diff < 0) {
3256 samples = samples * (float) (seek_rate / sample_rate);
3262 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
3264 struct ast_frame *f = NULL; /* the return value */
3269 /* this function is very long so make sure there is only one return
3270 * point at the end (there are only two exceptions to this).
3274 if (ast_do_masquerade(chan))
3275 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
3277 f = &ast_null_frame;
3281 /* if here, no masq has happened, lock the channel and proceed */
3282 ast_channel_lock(chan);
3284 /* Stop if we're a zombie or need a soft hangup */
3285 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
3286 if (chan->generator)
3287 ast_deactivate_generator(chan);
3293 * The ast_waitfor() code records which of the channel's file descriptors reported that
3294 * data is available. In theory, ast_read() should only be called after ast_waitfor()
3295 * reports that a channel has data available for reading. However, there still may be
3296 * some edge cases throughout the code where ast_read() is called improperly. This can
3297 * potentially cause problems, so if this is a developer build, make a lot of noise if
3298 * this happens so that it can be addressed.
3300 if (chan->fdno == -1) {
3301 ast_log(LOG_ERROR, "ast_read() called with no recorded file descriptor.\n");
3305 prestate = chan->_state;
3307 /* Read and ignore anything on the alertpipe, but read only
3308 one sizeof(blah) per frame that we send from it */
3309 if (chan->alertpipe[0] > -1) {
3310 int flags = fcntl(chan->alertpipe[0], F_GETFL);
3311 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
3312 * which immediately causes a deadlock scenario. Detect and prevent this. */
3313 if ((flags & O_NONBLOCK) == 0) {
3314 ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
3315 if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
3316 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
3317 f = &ast_null_frame;
3321 if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
3322 if (errno != EINTR && errno != EAGAIN)
3323 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
3327 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
3328 enum ast_timer_event res;
3330 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3332 res = ast_timer_get_event(chan->timer);
3335 case AST_TIMING_EVENT_EXPIRED:
3336 ast_timer_ack(chan->timer, 1);
3338 if (chan->timingfunc) {
3339 /* save a copy of func/data before unlocking the channel */
3340 int (*func)(const void *) = chan->timingfunc;
3341 void *data = chan->timingdata;
3343 ast_channel_unlock(chan);
3346 ast_timer_set_rate(chan->timer, 0);
3348 ast_channel_unlock(chan);
3351 /* cannot 'goto done' because the channel is already unlocked */
3352 return &ast_null_frame;
3354 case AST_TIMING_EVENT_CONTINUOUS:
3355 if (AST_LIST_EMPTY(&chan->readq) ||
3356 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
3357 ast_timer_disable_continuous(chan->timer);
3362 } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
3363 /* if the AST_GENERATOR_FD is set, call the generator with args
3364 * set to -1 so it can do whatever it needs to.
3366 void *tmp = chan->generatordata;
3367 chan->generatordata = NULL; /* reset to let ast_write get through */
3368 chan->generator->generate(chan, tmp, -1, -1);
3369 chan->generatordata = tmp;
3370 f = &ast_null_frame;
3375 /* Check for pending read queue */
3376 if (!AST_LIST_EMPTY(&chan->readq)) {
3377 int skip_dtmf = should_skip_dtmf(chan);
3379 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
3380 /* We have to be picky about which frame we pull off of the readq because
3381 * there are cases where we want to leave DTMF frames on the queue until
3382 * some later time. */
3384 if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
3388 AST_LIST_REMOVE_CURRENT(frame_list);
3391 AST_LIST_TRAVERSE_SAFE_END;
3394 /* There were no acceptable frames on the readq. */
3395 f = &ast_null_frame;
3396 if (chan->alertpipe[0] > -1) {
3398 /* Restore the state of the alertpipe since we aren't ready for any
3399 * of the frames in the readq. */
3400 if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
3401 ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
3406 /* Interpret hangup and return NULL */
3407 /* XXX why not the same for frames from the channel ? */
3408 if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
3409 cause = f->data.uint32;
3414 chan->blocker = pthread_self();
3415 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
3416 if (chan->tech->exception)
3417 f = chan->tech->exception(chan);
3419 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
3420 f = &ast_null_frame;
3422 /* Clear the exception flag */
3423 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3424 } else if (chan->tech->read)
3425 f = chan->tech->read(chan);
3427 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
3431 * Reset the recorded file descriptor that triggered this read so that we can
3432 * easily detect when ast_read() is called without properly using ast_waitfor().
3437 struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
3438 struct ast_control_read_action_payload *read_action_payload;
3439 struct ast_party_connected_line connected;
3441 /* if the channel driver returned more than one frame, stuff the excess
3442 into the readq for the next ast_read call
3444 if (AST_LIST_NEXT(f, frame_list)) {
3445 ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
3446 ast_frfree(AST_LIST_NEXT(f, frame_list));
3447 AST_LIST_NEXT(f, frame_list) = NULL;
3450 switch (f->frametype) {
3451 case AST_FRAME_CONTROL:
3452 if (f->subclass.integer == AST_CONTROL_ANSWER) {
3453 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
3454 ast_debug(1, "Ignoring answer on an inbound call!\n");
3456 f = &ast_null_frame;
3457 } else if (prestate == AST_STATE_UP) {
3458 ast_debug(1, "Dropping duplicate answer!\n");
3460 f = &ast_null_frame;
3462 /* Answer the CDR */
3463 ast_setstate(chan, AST_STATE_UP);
3464 /* removed a call to ast_cdr_answer(chan->cdr) from here. */
3465 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
3467 } else if (f->subclass.integer == AST_CONTROL_READ_ACTION) {
3468 ast_party_connected_line_init(&connected);
3469 read_action_payload = f->data.ptr;
3470 switch (read_action_payload->action) {
3471 case AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO:
3472 if (ast_connected_line_parse_data(read_action_payload->payload,
3473 read_action_payload->payload_size, &connected)) {
3476 if (ast_channel_connected_line_macro(NULL, chan, &connected, 1, 0)) {
3477 ast_indicate_data(chan, AST_CONTROL_CONNECTED_LINE,
3478 read_action_payload->payload, read_action_payload->payload_size);
3483 f = &ast_null_frame;
3486 case AST_FRAME_DTMF_END:
3487 send_dtmf_event(chan, "Received", f->subclass.integer, "No", "Yes");
3488 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass.integer, chan->name, f->len);
3489 /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
3490 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
3491 queue_dtmf_readq(chan, f);
3493 f = &ast_null_frame;
3494 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
3495 if (!ast_tvzero(chan->dtmf_tv) &&
3496 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3497 /* If it hasn't been long enough, defer this digit */
3498 queue_dtmf_readq(chan, f);
3500 f = &ast_null_frame;
3502 /* There was no begin, turn this into a begin and send the end later */
3503 f->frametype = AST_FRAME_DTMF_BEGIN;
3504 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
3505 chan->emulate_dtmf_digit = f->subclass.integer;
3506 chan->dtmf_tv = ast_tvnow();
3508 if (f->len > AST_MIN_DTMF_DURATION)
3509 chan->emulate_dtmf_duration = f->len;
3511 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
3513 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
3514 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass.integer, chan->emulate_dtmf_duration, chan->name);
3516 if (chan->audiohooks) {
3517 struct ast_frame *old_frame = f;
3519 * \todo XXX It is possible to write a digit to the audiohook twice
3520 * if the digit was originally read while the channel was in autoservice. */
3521 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3523 ast_frfree(old_frame);
3526 struct timeval now = ast_tvnow();
3527 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
3528 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass.integer, chan->name);
3529 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
3531 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3532 } else if (!f->len) {
3533 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass.integer, chan->name);
3534 f->len = AST_MIN_DTMF_DURATION;
3536 if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
3537 ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f->subclass.integer, f->len, AST_MIN_DTMF_DURATION, chan->name);
3538 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
3539 chan->emulate_dtmf_digit = f->subclass.integer;
3540 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
3542 f = &ast_null_frame;
3544 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass.integer, chan->name);
3545 if (f->len < AST_MIN_DTMF_DURATION) {
3546 f->len = AST_MIN_DTMF_DURATION;
3548 chan->dtmf_tv = now;
3550 if (chan->audiohooks) {
3551 struct ast_frame *old_frame = f;
3552 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3554 ast_frfree(old_frame);
3558 case AST_FRAME_DTMF_BEGIN:
3559 send_dtmf_event(chan, "Received", f->subclass.integer, "Yes", "No");
3560 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass.integer, chan->name);
3561 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
3562 (!ast_tvzero(chan->dtmf_tv) &&
3563 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
3564 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass.integer, chan->name);
3566 f = &ast_null_frame;
3568 ast_set_flag(chan, AST_FLAG_IN_DTMF);
3569 chan->dtmf_tv = ast_tvnow();
3570 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass.integer, chan->name);
3573 case AST_FRAME_NULL:
3574 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
3575 * is reached , because we want to make sure we pass at least one
3576 * voice frame through before starting the next digit, to ensure a gap
3577 * between DTMF digits. */
3578 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
3579 struct timeval now = ast_tvnow();
3580 if (!chan->emulate_dtmf_duration) {
3581 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
3582 chan->emulate_dtmf_digit = 0;
3583 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
3584 chan->emulate_dtmf_duration = 0;
3587 f->frametype = AST_FRAME_DTMF_END;
3588 f->subclass.integer = chan->emulate_dtmf_digit;
3589 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3590 chan->dtmf_tv = now;
3591 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
3592 chan->emulate_dtmf_digit = 0;
3593 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, chan->name);
3594 if (chan->audiohooks) {
3595 struct ast_frame *old_frame = f;
3596 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3597 if (old_frame != f) {
3598 ast_frfree(old_frame);
3604 case AST_FRAME_VOICE:
3605 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
3606 * is reached , because we want to make sure we pass at least one
3607 * voice frame through before starting the next digit, to ensure a gap
3608 * between DTMF digits. */
3609 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
3610 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
3611 chan->emulate_dtmf_digit = 0;
3614 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
3616 ast_read_generator_actions(chan, f);
3618 f = &ast_null_frame;
3621 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
3622 struct timeval now = ast_tvnow();
3623 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
3624 chan->emulate_dtmf_duration = 0;
3627 f->frametype = AST_FRAME_DTMF_END;
3628 f->subclass.integer = chan->emulate_dtmf_digit;
3629 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3630 chan->dtmf_tv = now;
3631 if (chan->audiohooks) {
3632 struct ast_frame *old_frame = f;
3633 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3635 ast_frfree(old_frame);
3637 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, chan->name);
3639 /* Drop voice frames while we're still in the middle of the digit */
3641 f = &ast_null_frame;
3643 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass.codec & chan->nativeformats)) {
3644 /* This frame is not one of the current native formats -- drop it on the floor */
3646 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
3647 chan->name, ast_getformatname(f->subclass.codec), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
3649 f = &ast_null_frame;
3650 } else if ((f->frametype == AST_FRAME_VOICE)) {
3651 /* Send frame to audiohooks if present */
3652 if (chan->audiohooks) {
3653 struct ast_frame *old_frame = f;
3654 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3656 ast_frfree(old_frame);
3658 if (chan->monitor && chan->monitor->read_stream ) {
3659 /* XXX what does this do ? */
3660 #ifndef MONITOR_CONSTANT_DELAY
3661 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
3663 jump = calc_monitor_jump((chan->outsmpl - chan->insmpl), ast_format_rate(f->subclass.codec), ast_format_rate(chan->monitor->read_stream->fmt->format));
3664 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
3665 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
3666 chan->insmpl += (chan->outsmpl - chan->insmpl) + f->samples;
3668 chan->insmpl+= f->samples;