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/global_datastores.h"
69 #include "asterisk/data.h"
72 #include <sys/epoll.h>
79 struct ast_epoll_data {
80 struct ast_channel *chan;
84 /* uncomment if you have problems with 'monitoring' synchronized files */
86 #define MONITOR_CONSTANT_DELAY
87 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
90 /*! \brief Prevent new channel allocation if shutting down. */
91 static int shutting_down;
95 unsigned long global_fin, global_fout;
97 AST_THREADSTORAGE(state2str_threadbuf);
98 #define STATE2STR_BUFSIZE 32
100 /*! Default amount of time to use when emulating a digit as a begin and end
102 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
104 /*! Minimum allowed digit length - 80ms */
105 #define AST_MIN_DTMF_DURATION 80
107 /*! Minimum amount of time between the end of the last digit and the beginning
108 * of a new one - 45ms */
109 #define AST_MIN_DTMF_GAP 45
111 /*! \brief List of channel drivers */
113 const struct ast_channel_tech *tech;
114 AST_LIST_ENTRY(chanlist) list;
118 /*! \brief Structure to hold channel context backtrace data */
119 struct ast_chan_trace_data {
121 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
124 /*! \brief Structure to save contexts where an ast_chan has been into */
125 struct ast_chan_trace {
126 char context[AST_MAX_CONTEXT];
127 char exten[AST_MAX_EXTENSION];
129 AST_LIST_ENTRY(ast_chan_trace) entry;
133 /*! \brief the list of registered channel types */
134 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
137 #define NUM_CHANNEL_BUCKETS 61
139 #define NUM_CHANNEL_BUCKETS 1567
142 #define DATA_EXPORT_CALLERID(MEMBER) \
143 MEMBER(ast_callerid, cid_dnid, AST_DATA_STRING) \
144 MEMBER(ast_callerid, cid_num, AST_DATA_STRING) \
145 MEMBER(ast_callerid, cid_name, AST_DATA_STRING) \
146 MEMBER(ast_callerid, cid_ani, AST_DATA_STRING) \
147 MEMBER(ast_callerid, cid_pres, AST_DATA_INTEGER) \
148 MEMBER(ast_callerid, cid_ani2, AST_DATA_INTEGER) \
149 MEMBER(ast_callerid, cid_tag, AST_DATA_STRING)
151 AST_DATA_STRUCTURE(ast_callerid, DATA_EXPORT_CALLERID);
153 #define DATA_EXPORT_CHANNEL(MEMBER) \
154 MEMBER(ast_channel, blockproc, AST_DATA_STRING) \
155 MEMBER(ast_channel, appl, AST_DATA_STRING) \
156 MEMBER(ast_channel, data, AST_DATA_STRING) \
157 MEMBER(ast_channel, name, AST_DATA_STRING) \
158 MEMBER(ast_channel, language, AST_DATA_STRING) \
159 MEMBER(ast_channel, musicclass, AST_DATA_STRING) \
160 MEMBER(ast_channel, accountcode, AST_DATA_STRING) \
161 MEMBER(ast_channel, peeraccount, AST_DATA_STRING) \
162 MEMBER(ast_channel, userfield, AST_DATA_STRING) \
163 MEMBER(ast_channel, call_forward, AST_DATA_STRING) \
164 MEMBER(ast_channel, uniqueid, AST_DATA_STRING) \
165 MEMBER(ast_channel, linkedid, AST_DATA_STRING) \
166 MEMBER(ast_channel, parkinglot, AST_DATA_STRING) \
167 MEMBER(ast_channel, hangupsource, AST_DATA_STRING) \
168 MEMBER(ast_channel, dialcontext, AST_DATA_STRING) \
169 MEMBER(ast_channel, rings, AST_DATA_INTEGER) \
170 MEMBER(ast_channel, priority, AST_DATA_INTEGER) \
171 MEMBER(ast_channel, macropriority, AST_DATA_INTEGER) \
172 MEMBER(ast_channel, adsicpe, AST_DATA_INTEGER) \
173 MEMBER(ast_channel, fin, AST_DATA_UNSIGNED_INTEGER) \
174 MEMBER(ast_channel, fout, AST_DATA_UNSIGNED_INTEGER) \
175 MEMBER(ast_channel, emulate_dtmf_duration, AST_DATA_UNSIGNED_INTEGER) \
176 MEMBER(ast_channel, visible_indication, AST_DATA_INTEGER) \
177 MEMBER(ast_channel, context, AST_DATA_STRING) \
178 MEMBER(ast_channel, exten, AST_DATA_STRING) \
179 MEMBER(ast_channel, macrocontext, AST_DATA_STRING) \
180 MEMBER(ast_channel, macroexten, AST_DATA_STRING)
182 AST_DATA_STRUCTURE(ast_channel, DATA_EXPORT_CHANNEL);
185 /*! \brief All active channels on the system */
186 static struct ao2_container *channels;
188 /*! \brief map AST_CAUSE's to readable string representations
192 static const struct {
197 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
198 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
199 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
200 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
201 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
202 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
203 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
204 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
205 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
206 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
207 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
208 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
209 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
210 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
211 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
212 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
213 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
214 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
215 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
216 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
217 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
218 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
219 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
220 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
221 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
222 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
223 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
224 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
225 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
226 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
227 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
228 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
229 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
230 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
231 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
232 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
233 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
234 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
235 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
236 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
237 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
238 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
239 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
240 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
243 struct ast_variable *ast_channeltype_list(void)
246 struct ast_variable *var = NULL, *prev = NULL;
248 AST_RWLIST_RDLOCK(&backends);
249 AST_RWLIST_TRAVERSE(&backends, cl, list) {
251 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
254 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
258 AST_RWLIST_UNLOCK(&backends);
263 static void channel_data_add_flags(struct ast_data *tree,
264 struct ast_channel *chan)
266 ast_data_add_bool(tree, "DEFER_DTMF", ast_test_flag(chan, AST_FLAG_DEFER_DTMF));
267 ast_data_add_bool(tree, "WRITE_INT", ast_test_flag(chan, AST_FLAG_WRITE_INT));
268 ast_data_add_bool(tree, "BLOCKING", ast_test_flag(chan, AST_FLAG_BLOCKING));
269 ast_data_add_bool(tree, "ZOMBIE", ast_test_flag(chan, AST_FLAG_ZOMBIE));
270 ast_data_add_bool(tree, "EXCEPTION", ast_test_flag(chan, AST_FLAG_EXCEPTION));
271 ast_data_add_bool(tree, "MOH", ast_test_flag(chan, AST_FLAG_MOH));
272 ast_data_add_bool(tree, "SPYING", ast_test_flag(chan, AST_FLAG_SPYING));
273 ast_data_add_bool(tree, "NBRIDGE", ast_test_flag(chan, AST_FLAG_NBRIDGE));
274 ast_data_add_bool(tree, "IN_AUTOLOOP", ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP));
275 ast_data_add_bool(tree, "OUTGOING", ast_test_flag(chan, AST_FLAG_OUTGOING));
276 ast_data_add_bool(tree, "IN_DTMF", ast_test_flag(chan, AST_FLAG_IN_DTMF));
277 ast_data_add_bool(tree, "EMULATE_DTMF", ast_test_flag(chan, AST_FLAG_EMULATE_DTMF));
278 ast_data_add_bool(tree, "END_DTMF_ONLY", ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY));
279 ast_data_add_bool(tree, "ANSWERED_ELSEWHERE", ast_test_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE));
280 ast_data_add_bool(tree, "MASQ_NOSTREAM", ast_test_flag(chan, AST_FLAG_MASQ_NOSTREAM));
281 ast_data_add_bool(tree, "BRIDGE_HANGUP_RUN", ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_RUN));
282 ast_data_add_bool(tree, "BRIDGE_HANGUP_DONT", ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT));
283 ast_data_add_bool(tree, "DISABLE_WORKAROUNDS", ast_test_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS));
286 static const char *callerid_ton2str(int ton)
290 case PRI_TON_INTERNATIONAL:
291 return "International Number";
292 case PRI_TON_NATIONAL:
293 return "National Number";
294 case PRI_TON_NET_SPECIFIC:
295 return "Network Specific Number";
296 case PRI_TON_SUBSCRIBER:
297 return "Subscriber Number";
298 case PRI_TON_ABBREVIATED:
299 return "Abbreviated number";
300 case PRI_TON_RESERVED:
301 return "Reserved Number";
302 case PRI_TON_UNKNOWN:
304 return "Unknown Number Type";
310 int ast_channel_data_add_structure(struct ast_data *tree,
311 struct ast_channel *chan, int add_bridged)
313 struct ast_channel *bc;
314 struct ast_data *data_bridged, *data_cdr, *data_flags, *data_zones;
315 struct ast_data *data_callerid, *enum_node, *data_softhangup;
321 ast_data_add_structure(ast_channel, tree, chan);
324 bc = ast_bridged_channel(chan);
326 data_bridged = ast_data_add_node(tree, "bridged");
330 ast_channel_data_add_structure(data_bridged, bc, 0);
334 ast_data_add_codecs(tree, "oldwriteformat", chan->oldwriteformat);
335 ast_data_add_codecs(tree, "nativeformats", chan->nativeformats);
336 ast_data_add_codecs(tree, "readformat", chan->readformat);
337 ast_data_add_codecs(tree, "writeformat", chan->writeformat);
338 ast_data_add_codecs(tree, "rawreadformat", chan->rawreadformat);
339 ast_data_add_codecs(tree, "rawwriteformat", chan->rawwriteformat);
342 enum_node = ast_data_add_node(tree, "state");
346 ast_data_add_str(enum_node, "text", ast_state2str(chan->_state));
347 ast_data_add_int(enum_node, "value", chan->_state);
350 enum_node = ast_data_add_node(tree, "hangupcause");
354 ast_data_add_str(enum_node, "text", ast_cause2str(chan->hangupcause));
355 ast_data_add_int(enum_node, "value", chan->hangupcause);
358 enum_node = ast_data_add_node(tree, "amaflags");
362 ast_data_add_str(enum_node, "text", ast_cdr_flags2str(chan->amaflags));
363 ast_data_add_int(enum_node, "value", chan->amaflags);
365 /* transfercapability */
366 enum_node = ast_data_add_node(tree, "transfercapability");
370 ast_data_add_str(enum_node, "text", ast_transfercapability2str(chan->transfercapability));
371 ast_data_add_int(enum_node, "value", chan->transfercapability);
374 data_softhangup = ast_data_add_node(tree, "softhangup");
375 if (!data_softhangup) {
378 ast_data_add_bool(data_softhangup, "dev", chan->_softhangup & AST_SOFTHANGUP_DEV);
379 ast_data_add_bool(data_softhangup, "asyncgoto", chan->_softhangup & AST_SOFTHANGUP_ASYNCGOTO);
380 ast_data_add_bool(data_softhangup, "shutdown", chan->_softhangup & AST_SOFTHANGUP_SHUTDOWN);
381 ast_data_add_bool(data_softhangup, "timeout", chan->_softhangup & AST_SOFTHANGUP_TIMEOUT);
382 ast_data_add_bool(data_softhangup, "appunload", chan->_softhangup & AST_SOFTHANGUP_APPUNLOAD);
383 ast_data_add_bool(data_softhangup, "explicit", chan->_softhangup & AST_SOFTHANGUP_EXPLICIT);
384 ast_data_add_bool(data_softhangup, "unbridge", chan->_softhangup & AST_SOFTHANGUP_UNBRIDGE);
387 data_flags = ast_data_add_node(tree, "flags");
391 channel_data_add_flags(data_flags, chan);
393 ast_data_add_uint(tree, "timetohangup", chan->whentohangup.tv_sec);
396 data_callerid = ast_data_add_node(tree, "callerid");
397 if (!data_callerid) {
400 ast_data_add_structure(ast_callerid, data_callerid, &(chan->cid));
401 /* insert the callerid ton */
402 enum_node = ast_data_add_node(data_callerid, "cid_ton");
406 ast_data_add_int(enum_node, "value", chan->cid.cid_ton);
407 ast_data_add_str(enum_node, "text", callerid_ton2str(chan->cid.cid_ton));
411 data_zones = ast_data_add_node(tree, "zone");
415 ast_tone_zone_data_add_structure(data_zones, chan->zone);
419 data_cdr = ast_data_add_node(tree, "cdr");
424 ast_cdr_data_add_structure(data_cdr, chan->cdr, 1);
429 int ast_channel_data_cmp_structure(const struct ast_data_search *tree,
430 struct ast_channel *chan, const char *structure_name)
432 return ast_data_search_cmp_structure(tree, ast_channel, chan, structure_name);
435 /*! \brief Show channel types - CLI command */
436 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
438 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
444 e->command = "core show channeltypes";
446 "Usage: core show channeltypes\n"
447 " Lists available channel types registered in your\n"
448 " Asterisk server.\n";
455 return CLI_SHOWUSAGE;
457 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
458 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
460 AST_RWLIST_RDLOCK(&backends);
461 AST_RWLIST_TRAVERSE(&backends, cl, list) {
462 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
463 (cl->tech->devicestate) ? "yes" : "no",
464 (cl->tech->indicate) ? "yes" : "no",
465 (cl->tech->transfer) ? "yes" : "no");
468 AST_RWLIST_UNLOCK(&backends);
470 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
477 static char *complete_channeltypes(struct ast_cli_args *a)
487 wordlen = strlen(a->word);
489 AST_RWLIST_RDLOCK(&backends);
490 AST_RWLIST_TRAVERSE(&backends, cl, list) {
491 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
492 ret = ast_strdup(cl->tech->type);
496 AST_RWLIST_UNLOCK(&backends);
501 /*! \brief Show details about a channel driver - CLI command */
502 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
504 struct chanlist *cl = NULL;
509 e->command = "core show channeltype";
511 "Usage: core show channeltype <name>\n"
512 " Show details about the specified channel type, <name>.\n";
515 return complete_channeltypes(a);
519 return CLI_SHOWUSAGE;
521 AST_RWLIST_RDLOCK(&backends);
523 AST_RWLIST_TRAVERSE(&backends, cl, list) {
524 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
530 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
531 AST_RWLIST_UNLOCK(&backends);
536 "-- Info about channel driver: %s --\n"
537 " Device State: %s\n"
540 " Capabilities: %s\n"
544 " Image Support: %s\n"
545 " Text Support: %s\n",
547 (cl->tech->devicestate) ? "yes" : "no",
548 (cl->tech->indicate) ? "yes" : "no",
549 (cl->tech->transfer) ? "yes" : "no",
550 ast_getformatname_multiple(buf, sizeof(buf), (cl->tech->capabilities) ? cl->tech->capabilities : -1),
551 (cl->tech->send_digit_begin) ? "yes" : "no",
552 (cl->tech->send_digit_end) ? "yes" : "no",
553 (cl->tech->send_html) ? "yes" : "no",
554 (cl->tech->send_image) ? "yes" : "no",
555 (cl->tech->send_text) ? "yes" : "no"
559 AST_RWLIST_UNLOCK(&backends);
564 static struct ast_cli_entry cli_channel[] = {
565 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
566 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
570 /*! \brief Destructor for the channel trace datastore */
571 static void ast_chan_trace_destroy_cb(void *data)
573 struct ast_chan_trace *trace;
574 struct ast_chan_trace_data *traced = data;
575 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
581 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
582 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
584 .destroy = ast_chan_trace_destroy_cb
587 /*! \brief Put the channel backtrace in a string */
588 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
591 struct ast_chan_trace *trace;
592 struct ast_chan_trace_data *traced;
593 struct ast_datastore *store;
595 ast_channel_lock(chan);
596 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
598 ast_channel_unlock(chan);
601 traced = store->data;
603 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
604 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
605 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
611 ast_channel_unlock(chan);
615 /* !\brief Whether or not context tracing is enabled */
616 int ast_channel_trace_is_enabled(struct ast_channel *chan)
618 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
621 return ((struct ast_chan_trace_data *)store->data)->enabled;
624 /*! \brief Update the context backtrace data if tracing is enabled */
625 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
627 struct ast_chan_trace *trace;
628 if (!traced->enabled)
630 /* If the last saved context does not match the current one
631 OR we have not saved any context so far, then save the current context */
632 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) ||
633 (AST_LIST_EMPTY(&traced->trace))) {
634 /* Just do some debug logging */
635 if (AST_LIST_EMPTY(&traced->trace))
636 ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
638 ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
639 /* alloc or bail out */
640 trace = ast_malloc(sizeof(*trace));
643 /* save the current location and store it in the trace list */
644 ast_copy_string(trace->context, chan->context, sizeof(trace->context));
645 ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
646 trace->priority = chan->priority;
647 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
652 /*! \brief Update the context backtrace if tracing is enabled */
653 int ast_channel_trace_update(struct ast_channel *chan)
655 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
658 return ast_channel_trace_data_update(chan, store->data);
661 /*! \brief Enable context tracing in the channel */
662 int ast_channel_trace_enable(struct ast_channel *chan)
664 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
665 struct ast_chan_trace_data *traced;
667 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
670 traced = ast_calloc(1, sizeof(*traced));
672 ast_datastore_free(store);
675 store->data = traced;
676 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
677 ast_channel_datastore_add(chan, store);
679 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
680 ast_channel_trace_data_update(chan, store->data);
684 /*! \brief Disable context tracing in the channel */
685 int ast_channel_trace_disable(struct ast_channel *chan)
687 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
690 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
693 #endif /* CHANNEL_TRACE */
695 /*! \brief Checks to see if a channel is needing hang up */
696 int ast_check_hangup(struct ast_channel *chan)
698 if (chan->_softhangup) /* yes if soft hangup flag set */
700 if (ast_tvzero(chan->whentohangup)) /* no if no hangup scheduled */
702 if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0) /* no if hangup time has not come yet. */
704 ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(chan->whentohangup, ast_tvnow()));
705 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
709 int ast_check_hangup_locked(struct ast_channel *chan)
712 ast_channel_lock(chan);
713 res = ast_check_hangup(chan);
714 ast_channel_unlock(chan);
718 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
720 struct ast_channel *chan = obj;
722 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
727 void ast_begin_shutdown(int hangup)
732 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
736 /*! \brief returns number of active/allocated channels */
737 int ast_active_channels(void)
739 return channels ? ao2_container_count(channels) : 0;
742 /*! \brief Cancel a shutdown in progress */
743 void ast_cancel_shutdown(void)
748 /*! \brief Returns non-zero if Asterisk is being shut down */
749 int ast_shutting_down(void)
751 return shutting_down;
754 /*! \brief Set when to hangup channel */
755 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
757 chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
758 ast_queue_frame(chan, &ast_null_frame);
762 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
764 struct timeval when = { offset, };
765 ast_channel_setwhentohangup_tv(chan, when);
768 /*! \brief Compare a offset with when to hangup channel */
769 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
771 struct timeval whentohangup;
773 if (ast_tvzero(chan->whentohangup))
774 return ast_tvzero(offset) ? 0 : -1;
776 if (ast_tvzero(offset))
779 whentohangup = ast_tvadd(offset, ast_tvnow());
781 return ast_tvdiff_ms(whentohangup, chan->whentohangup);
784 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
786 struct timeval when = { offset, };
787 return ast_channel_cmpwhentohangup_tv(chan, when);
790 /*! \brief Register a new telephony channel in Asterisk */
791 int ast_channel_register(const struct ast_channel_tech *tech)
793 struct chanlist *chan;
795 AST_RWLIST_WRLOCK(&backends);
797 AST_RWLIST_TRAVERSE(&backends, chan, list) {
798 if (!strcasecmp(tech->type, chan->tech->type)) {
799 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
800 AST_RWLIST_UNLOCK(&backends);
805 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
806 AST_RWLIST_UNLOCK(&backends);
810 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
812 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
814 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
816 AST_RWLIST_UNLOCK(&backends);
821 /*! \brief Unregister channel driver */
822 void ast_channel_unregister(const struct ast_channel_tech *tech)
824 struct chanlist *chan;
826 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
828 AST_RWLIST_WRLOCK(&backends);
830 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
831 if (chan->tech == tech) {
832 AST_LIST_REMOVE_CURRENT(list);
834 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
838 AST_LIST_TRAVERSE_SAFE_END;
840 AST_RWLIST_UNLOCK(&backends);
843 /*! \brief Get handle to channel driver based on name */
844 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
846 struct chanlist *chanls;
847 const struct ast_channel_tech *ret = NULL;
849 AST_RWLIST_RDLOCK(&backends);
851 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
852 if (!strcasecmp(name, chanls->tech->type)) {
858 AST_RWLIST_UNLOCK(&backends);
863 /*! \brief Gives the string form of a given hangup cause */
864 const char *ast_cause2str(int cause)
868 for (x = 0; x < ARRAY_LEN(causes); x++) {
869 if (causes[x].cause == cause)
870 return causes[x].desc;
876 /*! \brief Convert a symbolic hangup cause to number */
877 int ast_str2cause(const char *name)
881 for (x = 0; x < ARRAY_LEN(causes); x++)
882 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
883 return causes[x].cause;
888 /*! \brief Gives the string form of a given channel state.
889 \note This function is not reentrant.
891 const char *ast_state2str(enum ast_channel_state state)
898 case AST_STATE_RESERVED:
900 case AST_STATE_OFFHOOK:
902 case AST_STATE_DIALING:
906 case AST_STATE_RINGING:
912 case AST_STATE_DIALING_OFFHOOK:
913 return "Dialing Offhook";
914 case AST_STATE_PRERING:
917 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
919 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
924 /*! \brief Gives the string form of a given transfer capability */
925 char *ast_transfercapability2str(int transfercapability)
927 switch (transfercapability) {
928 case AST_TRANS_CAP_SPEECH:
930 case AST_TRANS_CAP_DIGITAL:
932 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
933 return "RESTRICTED_DIGITAL";
934 case AST_TRANS_CAP_3_1K_AUDIO:
936 case AST_TRANS_CAP_DIGITAL_W_TONES:
937 return "DIGITAL_W_TONES";
938 case AST_TRANS_CAP_VIDEO:
945 /*! \brief Pick the best audio codec */
946 format_t ast_best_codec(format_t fmts)
948 /* This just our opinion, expressed in code. We are asked to choose
949 the best codec to use, given no information */
951 static const format_t prefs[] =
953 /*! Okay, ulaw is used by all telephony equipment, so start with it */
955 /*! Unless of course, you're a silly European, so then prefer ALAW */
961 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
963 /*! Okay, well, signed linear is easy to translate into other stuff */
964 AST_FORMAT_SLINEAR16,
966 /*! G.726 is standard ADPCM, in RFC3551 packing order */
968 /*! G.726 is standard ADPCM, in AAL2 packing order */
969 AST_FORMAT_G726_AAL2,
970 /*! ADPCM has great sound quality and is still pretty easy to translate */
972 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
973 translate and sounds pretty good */
975 /*! iLBC is not too bad */
977 /*! Speex is free, but computationally more expensive than GSM */
980 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
983 /*! G.729a is faster than 723 and slightly less expensive */
985 /*! Down to G.723.1 which is proprietary but at least designed for voice */
990 /* Strip out video */
991 fmts &= AST_FORMAT_AUDIO_MASK;
993 /* Find the first preferred codec in the format given */
994 for (x = 0; x < ARRAY_LEN(prefs); x++) {
999 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), fmts));
1004 static const struct ast_channel_tech null_tech = {
1006 .description = "Null channel (should not see this)",
1009 static void ast_channel_destructor(void *obj);
1010 static void ast_dummy_channel_destructor(void *obj);
1012 /*! \brief Create a new channel structure */
1013 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
1014 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
1015 const char *acctcode, const char *exten, const char *context,
1016 const char *linkedid, const int amaflag, const char *file, int line,
1017 const char *function, const char *name_fmt, va_list ap1, va_list ap2)
1019 struct ast_channel *tmp;
1022 struct varshead *headp;
1025 /* If shutting down, don't allocate any new channels */
1026 if (shutting_down) {
1027 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
1031 #if defined(REF_DEBUG)
1032 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
1034 #elif defined(__AST_DEBUG_MALLOC)
1035 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
1038 tmp = ao2_alloc(sizeof(*tmp), ast_channel_destructor);
1041 /* Channel structure allocation failure. */
1046 * Init file descriptors to unopened state so
1047 * the destructor can know not to close them.
1050 for (x = 0; x < ARRAY_LEN(tmp->alertpipe); ++x) {
1051 tmp->alertpipe[x] = -1;
1053 for (x = 0; x < ARRAY_LEN(tmp->fds); ++x) {
1057 tmp->epfd = epoll_create(25);
1060 if (!(tmp->sched = sched_context_create())) {
1061 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
1062 return ast_channel_unref(tmp);
1066 if (!(tmp->cid.cid_name = ast_strdup(cid_name))) {
1067 return ast_channel_unref(tmp);
1071 if (!(tmp->cid.cid_num = ast_strdup(cid_num))) {
1072 return ast_channel_unref(tmp);
1076 if ((tmp->timer = ast_timer_open())) {
1078 tmp->timingfd = ast_timer_fd(tmp->timer);
1082 if (pipe(tmp->alertpipe)) {
1083 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
1084 return ast_channel_unref(tmp);
1086 flags = fcntl(tmp->alertpipe[0], F_GETFL);
1087 if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
1088 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1089 return ast_channel_unref(tmp);
1091 flags = fcntl(tmp->alertpipe[1], F_GETFL);
1092 if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
1093 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1094 return ast_channel_unref(tmp);
1100 * This is the last place the channel constructor can fail.
1102 * The destructor takes advantage of this fact to ensure that the
1103 * AST_CEL_CHANNEL_END is not posted if we have not posted the
1104 * AST_CEL_CHANNEL_START yet.
1106 if ((ast_string_field_init(tmp, 128))) {
1107 return ast_channel_unref(tmp);
1110 /* Always watch the alertpipe */
1111 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
1112 /* And timing pipe */
1113 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
1116 tmp->_state = state;
1120 tmp->fin = global_fin;
1121 tmp->fout = global_fout;
1123 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1124 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
1125 ast_atomic_fetchadd_int(&uniqueint, 1));
1127 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
1128 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1131 if (!ast_strlen_zero(linkedid)) {
1132 ast_string_field_set(tmp, linkedid, linkedid);
1134 ast_string_field_set(tmp, linkedid, tmp->uniqueid);
1137 if (!ast_strlen_zero(name_fmt)) {
1139 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1140 * And they all use slightly different formats for their name string.
1141 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1142 * This means, that the stringfields must have a routine that takes the va_lists directly, and
1143 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1144 * This new function was written so this can be accomplished.
1146 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
1147 tech = ast_strdupa(tmp->name);
1148 if ((slash = strchr(tech, '/'))) {
1153 * Start the string with '-' so it becomes an empty string
1154 * in the destructor.
1156 ast_string_field_set(tmp, name, "-**Unknown**");
1159 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1161 /* These 4 variables need to be set up for the cdr_init() to work right */
1163 tmp->amaflags = amaflag;
1165 tmp->amaflags = ast_default_amaflags;
1167 if (!ast_strlen_zero(acctcode))
1168 ast_string_field_set(tmp, accountcode, acctcode);
1170 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
1172 if (!ast_strlen_zero(context))
1173 ast_copy_string(tmp->context, context, sizeof(tmp->context));
1175 strcpy(tmp->context, "default");
1177 if (!ast_strlen_zero(exten))
1178 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
1180 strcpy(tmp->exten, "s");
1184 tmp->cdr = ast_cdr_alloc();
1185 ast_cdr_init(tmp->cdr, tmp);
1186 ast_cdr_start(tmp->cdr);
1188 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1190 headp = &tmp->varshead;
1191 AST_LIST_HEAD_INIT_NOLOCK(headp);
1193 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
1195 AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
1197 ast_string_field_set(tmp, language, defaultlanguage);
1199 tmp->tech = &null_tech;
1201 ao2_link(channels, tmp);
1204 * And now, since the channel structure is built, and has its name, let's
1205 * call the manager event generator with this Newchannel event. This is the
1206 * proper and correct place to make this call, but you sure do have to pass
1207 * a lot of data into this func to do it here!
1209 if (ast_get_channel_tech(tech)) {
1210 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1212 "ChannelState: %d\r\n"
1213 "ChannelStateDesc: %s\r\n"
1214 "CallerIDNum: %s\r\n"
1215 "CallerIDName: %s\r\n"
1216 "AccountCode: %s\r\n"
1222 ast_state2str(state),
1234 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1235 const char *cid_name, const char *acctcode,
1236 const char *exten, const char *context,
1237 const char *linkedid, const int amaflag,
1238 const char *file, int line, const char *function,
1239 const char *name_fmt, ...)
1242 struct ast_channel *result;
1244 va_start(ap1, name_fmt);
1245 va_start(ap2, name_fmt);
1246 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1247 linkedid, amaflag, file, line, function, name_fmt, ap1, ap2);
1254 /* only do the minimum amount of work needed here to make a channel
1255 * structure that can be used to expand channel vars */
1256 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1257 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1259 struct ast_channel *ast_dummy_channel_alloc(void)
1262 struct ast_channel *tmp;
1263 struct varshead *headp;
1265 #if defined(REF_DEBUG)
1266 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1267 file, line, function, 1);
1268 #elif defined(__AST_DEBUG_MALLOC)
1269 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1270 file, line, function, 0);
1272 tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor);
1275 /* Dummy channel structure allocation failure. */
1279 if ((ast_string_field_init(tmp, 128))) {
1280 return ast_channel_unref(tmp);
1283 headp = &tmp->varshead;
1284 AST_LIST_HEAD_INIT_NOLOCK(headp);
1289 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1291 struct ast_frame *f;
1292 struct ast_frame *cur;
1294 unsigned int new_frames = 0;
1295 unsigned int new_voice_frames = 0;
1296 unsigned int queued_frames = 0;
1297 unsigned int queued_voice_frames = 0;
1298 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1300 ast_channel_lock(chan);
1302 /* See if the last frame on the queue is a hangup, if so don't queue anything */
1303 if ((cur = AST_LIST_LAST(&chan->readq)) &&
1304 (cur->frametype == AST_FRAME_CONTROL) &&
1305 (cur->subclass.integer == AST_CONTROL_HANGUP)) {
1306 ast_channel_unlock(chan);
1310 /* Build copies of all the frames and count them */
1311 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1312 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1313 if (!(f = ast_frdup(cur))) {
1314 ast_frfree(AST_LIST_FIRST(&frames));
1315 ast_channel_unlock(chan);
1319 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1321 if (f->frametype == AST_FRAME_VOICE) {
1326 /* Count how many frames exist on the queue */
1327 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1329 if (cur->frametype == AST_FRAME_VOICE) {
1330 queued_voice_frames++;
1334 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1336 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", chan->name);
1337 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
1338 /* Save the most recent frame */
1339 if (!AST_LIST_NEXT(cur, frame_list)) {
1341 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1345 AST_LIST_REMOVE_CURRENT(frame_list);
1349 AST_LIST_TRAVERSE_SAFE_END;
1353 AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1356 AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1357 AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1359 AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1362 if (chan->alertpipe[1] > -1) {
1363 if (write(chan->alertpipe[1], &blah, new_frames * sizeof(blah)) != (new_frames * sizeof(blah))) {
1364 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1365 chan->name, queued_frames, strerror(errno));
1367 } else if (chan->timingfd > -1) {
1368 ast_timer_enable_continuous(chan->timer);
1369 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1370 pthread_kill(chan->blocker, SIGURG);
1373 ast_channel_unlock(chan);
1378 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1380 return __ast_queue_frame(chan, fin, 0, NULL);
1383 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1385 return __ast_queue_frame(chan, fin, 1, NULL);
1388 /*! \brief Queue a hangup frame for channel */
1389 int ast_queue_hangup(struct ast_channel *chan)
1391 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1392 /* Yeah, let's not change a lock-critical value without locking */
1393 if (!ast_channel_trylock(chan)) {
1394 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1395 ast_channel_unlock(chan);
1397 return ast_queue_frame(chan, &f);
1400 /*! \brief Queue a hangup frame for channel */
1401 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1403 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1406 f.data.uint32 = cause;
1408 /* Yeah, let's not change a lock-critical value without locking */
1409 if (!ast_channel_trylock(chan)) {
1410 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1412 f.data.uint32 = chan->hangupcause;
1414 ast_channel_unlock(chan);
1417 return ast_queue_frame(chan, &f);
1420 /*! \brief Queue a control frame */
1421 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1423 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1424 return ast_queue_frame(chan, &f);
1427 /*! \brief Queue a control frame with payload */
1428 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1429 const void *data, size_t datalen)
1431 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1432 return ast_queue_frame(chan, &f);
1435 /*! \brief Set defer DTMF flag on channel */
1436 int ast_channel_defer_dtmf(struct ast_channel *chan)
1441 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1442 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1447 /*! \brief Unset defer DTMF flag on channel */
1448 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1451 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1454 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1455 void *data, int ao2_flags)
1457 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1460 struct ast_channel_iterator {
1461 /* storage for non-dynamically allocated iterator */
1462 struct ao2_iterator simple_iterator;
1463 /* pointer to the actual iterator (simple_iterator or a dynamically
1464 * allocated iterator)
1466 struct ao2_iterator *active_iterator;
1469 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1471 ao2_iterator_destroy(i->active_iterator);
1477 static struct ast_channel_iterator *channel_iterator_search(const char *name,
1478 size_t name_len, const char *exten,
1479 const char *context)
1481 struct ast_channel_iterator *i;
1482 struct ast_channel tmp_chan = {
1484 /* This is sort of a hack. Basically, we're using an arbitrary field
1485 * in ast_channel to pass the name_len for a prefix match. If this
1486 * gets changed, then the compare callback must be changed, too. */
1490 if (!(i = ast_calloc(1, sizeof(*i)))) {
1495 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1499 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1502 if (!(i->active_iterator = ao2_find(channels, &tmp_chan,
1503 OBJ_MULTIPLE | ((!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0)))) {
1511 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1513 return channel_iterator_search(NULL, 0, exten, context);
1516 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1518 return channel_iterator_search(name, name_len, NULL, NULL);
1521 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1523 struct ast_channel_iterator *i;
1525 if (!(i = ast_calloc(1, sizeof(*i)))) {
1529 i->simple_iterator = ao2_iterator_init(channels, 0);
1530 i->active_iterator = &i->simple_iterator;
1535 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1537 return ao2_iterator_next(i->active_iterator);
1540 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1542 struct ast_channel *chan = obj, *cmp_args = arg;
1544 int ret = CMP_MATCH;
1546 /* This is sort of a hack. Basically, we're using an arbitrary field
1547 * in ast_channel to pass the name_len for a prefix match. If this
1548 * gets changed, then the uses of ao2_find() must be changed, too. */
1549 name_len = cmp_args->rings;
1551 ast_channel_lock(chan);
1553 if (!ast_strlen_zero(cmp_args->name)) { /* match by name */
1554 if ((!name_len && strcasecmp(chan->name, cmp_args->name)) ||
1555 (name_len && strncasecmp(chan->name, cmp_args->name, name_len))) {
1556 ret = 0; /* name match failed */
1558 } else if (!ast_strlen_zero(cmp_args->exten)) {
1559 if (cmp_args->context && strcasecmp(chan->context, cmp_args->context) &&
1560 strcasecmp(chan->macrocontext, cmp_args->context)) {
1561 ret = 0; /* context match failed */
1563 if (ret && strcasecmp(chan->exten, cmp_args->exten) &&
1564 strcasecmp(chan->macroexten, cmp_args->exten)) {
1565 ret = 0; /* exten match failed */
1567 } else if (!ast_strlen_zero(cmp_args->uniqueid)) {
1568 if ((!name_len && strcasecmp(chan->uniqueid, cmp_args->uniqueid)) ||
1569 (name_len && strncasecmp(chan->uniqueid, cmp_args->uniqueid, name_len))) {
1570 ret = 0; /* uniqueid match failed */
1576 ast_channel_unlock(chan);
1581 static struct ast_channel *ast_channel_get_full(const char *name, size_t name_len,
1582 const char *exten, const char *context)
1584 struct ast_channel tmp_chan = {
1586 /* This is sort of a hack. Basically, we're using an arbitrary field
1587 * in ast_channel to pass the name_len for a prefix match. If this
1588 * gets changed, then the compare callback must be changed, too. */
1591 struct ast_channel *chan;
1594 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1598 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1601 if ((chan = ao2_find(channels, &tmp_chan,
1602 (!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0))) {
1610 /* If name was specified, but the result was NULL,
1611 * try a search on uniqueid, instead. */
1614 struct ast_channel tmp_chan2 = {
1619 return ao2_find(channels, &tmp_chan2, 0);
1623 struct ast_channel *ast_channel_get_by_name(const char *name)
1625 return ast_channel_get_full(name, 0, NULL, NULL);
1628 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1630 return ast_channel_get_full(name, name_len, NULL, NULL);
1633 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1635 return ast_channel_get_full(NULL, 0, exten, context);
1638 int ast_is_deferrable_frame(const struct ast_frame *frame)
1640 /* Do not add a default entry in this switch statement. Each new
1641 * frame type should be addressed directly as to whether it should
1642 * be queued up or not.
1644 switch (frame->frametype) {
1645 case AST_FRAME_DTMF_END:
1646 case AST_FRAME_CONTROL:
1647 case AST_FRAME_TEXT:
1648 case AST_FRAME_IMAGE:
1649 case AST_FRAME_HTML:
1652 case AST_FRAME_DTMF_BEGIN:
1653 case AST_FRAME_VOICE:
1654 case AST_FRAME_VIDEO:
1655 case AST_FRAME_NULL:
1658 case AST_FRAME_MODEM:
1664 /*! \brief Wait, look for hangups and condition arg */
1665 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1667 struct ast_frame *f;
1668 struct ast_silence_generator *silgen = NULL;
1670 AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1672 AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1674 /* If no other generator is present, start silencegen while waiting */
1675 if (ast_opt_transmit_silence && !chan->generatordata) {
1676 silgen = ast_channel_start_silence_generator(chan);
1680 struct ast_frame *dup_f = NULL;
1681 if (cond && ((*cond)(data) == 0)) {
1684 ms = ast_waitfor(chan, ms);
1696 if (!ast_is_deferrable_frame(f)) {
1701 if ((dup_f = ast_frisolate(f))) {
1705 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1710 /* stop silgen if present */
1712 ast_channel_stop_silence_generator(chan, silgen);
1715 /* We need to free all the deferred frames, but we only need to
1716 * queue the deferred frames if there was no error and no
1717 * hangup was received
1719 ast_channel_lock(chan);
1720 while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1722 ast_queue_frame_head(chan, f);
1726 ast_channel_unlock(chan);
1731 /*! \brief Wait, look for hangups */
1732 int ast_safe_sleep(struct ast_channel *chan, int ms)
1734 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1737 static void free_cid(struct ast_callerid *cid)
1740 ast_free(cid->cid_dnid);
1742 ast_free(cid->cid_num);
1744 ast_free(cid->cid_name);
1746 ast_free(cid->cid_ani);
1748 ast_free(cid->cid_tag);
1749 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = NULL;
1750 ast_party_subaddress_free(&cid->subaddress);
1751 ast_party_subaddress_free(&cid->dialed_subaddress);
1754 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1756 /* Safe, even if already unlinked. */
1757 ao2_unlink(channels, chan);
1758 return ast_channel_unref(chan);
1761 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1765 init->odd_even_indicator = 0;
1769 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1772 /* Don't copy to self */
1777 ast_free(dest->str);
1779 dest->str = ast_strdup(src->str);
1780 dest->type = src->type;
1781 dest->odd_even_indicator = src->odd_even_indicator;
1782 dest->valid = src->valid;
1785 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1788 init->type = guide->type;
1789 init->odd_even_indicator = guide->odd_even_indicator;
1790 init->valid = guide->valid;
1793 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1796 /* Don't set to self */
1800 if (src->str && src->str != dest->str) {
1802 ast_free(dest->str);
1804 dest->str = ast_strdup(src->str);
1807 dest->type = src->type;
1808 dest->odd_even_indicator = src->odd_even_indicator;
1809 dest->valid = src->valid;
1812 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1815 ast_free(doomed->str);
1820 void ast_party_id_init(struct ast_party_id *init)
1822 init->number = NULL;
1825 init->number_type = 0; /* Unknown */
1826 init->number_presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1827 ast_party_subaddress_init(&init->subaddress);
1832 * \brief Copy the source party id information to the destination party id.
1834 * \param dest Destination party id
1835 * \param src Source party id
1839 static void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1842 /* Don't copy to self */
1847 ast_free(dest->number);
1849 dest->number = ast_strdup(src->number);
1852 ast_free(dest->name);
1854 dest->name = ast_strdup(src->name);
1857 ast_free(dest->tag);
1859 dest->tag = ast_strdup(src->tag);
1861 dest->number_type = src->number_type;
1862 dest->number_presentation = src->number_presentation;
1863 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1868 * \brief Initialize the given party id structure using the given guide
1869 * for a set update operation.
1872 * The initialization is needed to allow a set operation to know if a
1873 * value needs to be updated. Simple integers need the guide's original
1874 * value in case the set operation is not trying to set a new value.
1875 * String values are simply set to NULL pointers if they are not going
1878 * \param init Party id structure to initialize.
1879 * \param guide Source party id to use as a guide in initializing.
1883 static void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1885 init->number = NULL;
1888 init->number_type = guide->number_type;
1889 init->number_presentation = guide->number_presentation;
1890 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1895 * \brief Set the source party id information into the destination party id.
1897 * \param dest Destination party id
1898 * \param src Source party id
1902 static void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src)
1905 /* Don't set to self */
1909 if (src->name && src->name != dest->name) {
1911 ast_free(dest->name);
1913 dest->name = ast_strdup(src->name);
1916 if (src->number && src->number != dest->number) {
1918 ast_free(dest->number);
1920 dest->number = ast_strdup(src->number);
1923 if (src->tag && src->tag != dest->tag) {
1925 ast_free(dest->tag);
1927 dest->tag = ast_strdup(src->tag);
1930 dest->number_type = src->number_type;
1931 dest->number_presentation = src->number_presentation;
1932 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1935 void ast_party_id_free(struct ast_party_id *doomed)
1937 if (doomed->number) {
1938 ast_free(doomed->number);
1939 doomed->number = NULL;
1943 ast_free(doomed->name);
1944 doomed->name = NULL;
1948 ast_free(doomed->tag);
1951 ast_party_subaddress_free(&doomed->subaddress);
1954 void ast_party_caller_init(struct ast_party_caller *init)
1956 ast_party_id_init(&init->id);
1961 void ast_party_caller_copy(struct ast_callerid *dest, const struct ast_callerid *src)
1964 /* Don't copy to self */
1969 /* Copy caller-id specific information ONLY from struct ast_callerid */
1972 ast_free(dest->cid_num);
1974 dest->cid_num = ast_strdup(src->cid_num);
1978 ast_free(dest->cid_name);
1980 dest->cid_name = ast_strdup(src->cid_name);
1982 if (dest->cid_tag) {
1983 ast_free(dest->cid_tag);
1985 dest->cid_tag = ast_strdup(src->cid_tag);
1987 dest->cid_ton = src->cid_ton;
1988 dest->cid_pres = src->cid_pres;
1993 ast_free(dest->cid_ani);
1995 dest->cid_ani = ast_strdup(src->cid_ani);
1997 dest->cid_ani2 = src->cid_ani2;
1999 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2003 /* The src and dest parameter types will become struct ast_party_caller ptrs. */
2004 /* This is future code */
2006 ast_party_id_copy(&dest->id, &src->id);
2009 ast_free(dest->ani);
2011 dest->ani = ast_strdup(src->ani);
2013 dest->ani2 = src->ani2;
2017 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2019 ast_party_id_init(&init->id);
2022 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2025 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2028 /* Don't copy to self */
2032 ast_party_id_copy(&dest->id, &src->id);
2035 ast_free(dest->ani);
2037 dest->ani = ast_strdup(src->ani);
2039 dest->ani2 = src->ani2;
2040 dest->source = src->source;
2043 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2045 ast_party_id_set_init(&init->id, &guide->id);
2047 init->ani2 = guide->ani2;
2048 init->source = guide->source;
2051 void ast_party_connected_line_set(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2053 ast_party_id_set(&dest->id, &src->id);
2055 if (src->ani && src->ani != dest->ani) {
2057 ast_free(dest->ani);
2059 dest->ani = ast_strdup(src->ani);
2062 dest->ani2 = src->ani2;
2063 dest->source = src->source;
2066 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_callerid *cid)
2068 connected->id.number = cid->cid_num;
2069 connected->id.name = cid->cid_name;
2070 connected->id.number_type = cid->cid_ton;
2071 connected->id.number_presentation = cid->cid_pres;
2072 connected->id.tag = cid->cid_tag;
2073 connected->id.subaddress = cid->subaddress;
2075 connected->ani = cid->cid_ani;
2076 connected->ani2 = cid->cid_ani2;
2077 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2080 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2082 ast_party_id_free(&doomed->id);
2085 ast_free(doomed->ani);
2090 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2093 /* Don't copy to self */
2097 ast_party_id_copy(&dest->from, &src->from);
2098 ast_party_id_copy(&dest->to, &src->to);
2099 dest->count = src->count;
2100 dest->reason = src->reason;
2103 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2105 ast_party_id_set_init(&init->from, &guide->from);
2106 ast_party_id_set_init(&init->to, &guide->to);
2107 init->count = guide->count;
2108 init->reason = guide->reason;
2111 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2113 ast_party_id_free(&doomed->from);
2114 ast_party_id_free(&doomed->to);
2117 /*! \brief Free a channel structure */
2118 static void ast_channel_destructor(void *obj)
2120 struct ast_channel *chan = obj;
2125 struct ast_var_t *vardata;
2126 struct ast_frame *f;
2127 struct varshead *headp;
2128 struct ast_datastore *datastore;
2129 char device_name[AST_CHANNEL_NAME];
2132 /* The string fields were initialized. */
2133 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2134 ast_cel_check_retire_linkedid(chan);
2137 /* Get rid of each of the data stores on the channel */
2138 ast_channel_lock(chan);
2139 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
2140 /* Free the data store */
2141 ast_datastore_free(datastore);
2142 ast_channel_unlock(chan);
2144 /* Lock and unlock the channel just to be sure nobody has it locked still
2145 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2146 ast_channel_lock(chan);
2147 ast_channel_unlock(chan);
2149 if (chan->tech_pvt) {
2150 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
2151 ast_free(chan->tech_pvt);
2155 sched_context_destroy(chan->sched);
2160 /* The string fields were initialized. */
2161 ast_copy_string(device_name, chan->name, sizeof(device_name));
2162 if ((dashptr = strrchr(device_name, '-'))) {
2166 device_name[0] = '\0';
2169 /* Stop monitoring */
2171 chan->monitor->stop( chan, 0 );
2173 /* If there is native format music-on-hold state, free it */
2174 if (chan->music_state)
2175 ast_moh_cleanup(chan);
2177 /* Free translators */
2178 if (chan->readtrans)
2179 ast_translator_free_path(chan->readtrans);
2180 if (chan->writetrans)
2181 ast_translator_free_path(chan->writetrans);
2183 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
2185 free_cid(&chan->cid);
2186 ast_party_connected_line_free(&chan->connected);
2187 ast_party_redirecting_free(&chan->redirecting);
2189 /* Close pipes if appropriate */
2190 if ((fd = chan->alertpipe[0]) > -1)
2192 if ((fd = chan->alertpipe[1]) > -1)
2195 ast_timer_close(chan->timer);
2198 for (i = 0; i < AST_MAX_FDS; i++) {
2199 if (chan->epfd_data[i])
2200 free(chan->epfd_data[i]);
2204 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
2207 /* loop over the variables list, freeing all data and deleting list items */
2208 /* no need to lock the list, as the channel is already locked */
2209 headp = &chan->varshead;
2210 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2211 ast_var_delete(vardata);
2213 ast_app_group_discard(chan);
2215 /* Destroy the jitterbuffer */
2216 ast_jb_destroy(chan);
2219 ast_cdr_discard(chan->cdr);
2224 chan->zone = ast_tone_zone_unref(chan->zone);
2227 ast_string_field_free_memory(chan);
2229 if (device_name[0]) {
2231 * We have a device name to notify of a new state.
2233 * Queue an unknown state, because, while we know that this particular
2234 * instance is dead, we don't know the state of all other possible
2237 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2241 /*! \brief Free a dummy channel structure */
2242 static void ast_dummy_channel_destructor(void *obj)
2244 struct ast_channel *chan = obj;
2245 struct ast_var_t *vardata;
2246 struct varshead *headp;
2248 headp = &chan->varshead;
2250 free_cid(&chan->cid);
2252 /* loop over the variables list, freeing all data and deleting list items */
2253 /* no need to lock the list, as the channel is already locked */
2254 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2255 ast_var_delete(vardata);
2258 ast_cdr_discard(chan->cdr);
2262 ast_string_field_free_memory(chan);
2265 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2267 return ast_datastore_alloc(info, uid);
2270 int ast_channel_datastore_free(struct ast_datastore *datastore)
2272 return ast_datastore_free(datastore);
2275 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2277 struct ast_datastore *datastore = NULL, *datastore2;
2279 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
2280 if (datastore->inheritance > 0) {
2281 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2283 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2284 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2285 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
2292 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2296 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
2301 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2303 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
2306 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2308 struct ast_datastore *datastore = NULL;
2313 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
2314 if (datastore->info != info) {
2319 /* matched by type only */
2323 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2324 /* Matched by type AND uid */
2328 AST_LIST_TRAVERSE_SAFE_END;
2333 /*! Set the file descriptor on the channel */
2334 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2337 struct epoll_event ev;
2338 struct ast_epoll_data *aed = NULL;
2340 if (chan->fds[which] > -1) {
2341 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2342 aed = chan->epfd_data[which];
2345 /* If this new fd is valid, add it to the epoll */
2347 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2350 chan->epfd_data[which] = aed;
2354 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2356 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2358 /* We don't have to keep around this epoll data structure now */
2360 chan->epfd_data[which] = NULL;
2363 chan->fds[which] = fd;
2367 /*! Add a channel to an optimized waitfor */
2368 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2371 struct epoll_event ev;
2374 if (chan0->epfd == -1)
2377 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2378 for (i = 0; i < AST_MAX_FDS; i++) {
2379 if (chan1->fds[i] == -1)
2381 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2382 ev.data.ptr = chan1->epfd_data[i];
2383 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2390 /*! Delete a channel from an optimized waitfor */
2391 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2394 struct epoll_event ev;
2397 if (chan0->epfd == -1)
2400 for (i = 0; i < AST_MAX_FDS; i++) {
2401 if (chan1->fds[i] == -1)
2403 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2410 /*! \brief Softly hangup a channel, don't lock */
2411 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2413 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
2414 /* Inform channel driver that we need to be hung up, if it cares */
2415 chan->_softhangup |= cause;
2416 ast_queue_frame(chan, &ast_null_frame);
2417 /* Interrupt any poll call or such */
2418 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2419 pthread_kill(chan->blocker, SIGURG);
2423 /*! \brief Softly hangup a channel, lock */
2424 int ast_softhangup(struct ast_channel *chan, int cause)
2428 ast_channel_lock(chan);
2429 res = ast_softhangup_nolock(chan, cause);
2430 ast_channel_unlock(chan);
2435 static void free_translation(struct ast_channel *clonechan)
2437 if (clonechan->writetrans)
2438 ast_translator_free_path(clonechan->writetrans);
2439 if (clonechan->readtrans)
2440 ast_translator_free_path(clonechan->readtrans);
2441 clonechan->writetrans = NULL;
2442 clonechan->readtrans = NULL;
2443 clonechan->rawwriteformat = clonechan->nativeformats;
2444 clonechan->rawreadformat = clonechan->nativeformats;
2447 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2449 struct ast_channel *bridge;
2451 ast_channel_lock(chan);
2452 if (force || ast_strlen_zero(chan->hangupsource)) {
2453 ast_string_field_set(chan, hangupsource, source);
2455 bridge = ast_bridged_channel(chan);
2456 ast_channel_unlock(chan);
2458 if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
2459 ast_channel_lock(bridge);
2460 ast_string_field_set(chan, hangupsource, source);
2461 ast_channel_unlock(bridge);
2465 /*! \brief Hangup a channel */
2466 int ast_hangup(struct ast_channel *chan)
2469 char extra_str[64]; /* used for cel logging below */
2471 /* Don't actually hang up a channel that will masquerade as someone else, or
2472 if someone is going to masquerade as us */
2473 ast_channel_lock(chan);
2475 if (chan->audiohooks) {
2476 ast_audiohook_detach_list(chan->audiohooks);
2477 chan->audiohooks = NULL;
2480 ast_autoservice_stop(chan);
2483 ast_channel_unlock(chan);
2484 if (ast_do_masquerade(chan)) {
2485 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2487 ast_channel_lock(chan);
2491 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
2492 ast_channel_unlock(chan);
2495 /* If this channel is one which will be masqueraded into something,
2496 mark it as a zombie already, so we know to free it later */
2498 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2499 ast_channel_unlock(chan);
2502 ast_channel_unlock(chan);
2504 ao2_unlink(channels, chan);
2506 ast_channel_lock(chan);
2507 free_translation(chan);
2508 /* Close audio stream */
2510 ast_closestream(chan->stream);
2511 chan->stream = NULL;
2513 /* Close video stream */
2514 if (chan->vstream) {
2515 ast_closestream(chan->vstream);
2516 chan->vstream = NULL;
2519 sched_context_destroy(chan->sched);
2523 if (chan->generatordata) /* Clear any tone stuff remaining */
2524 if (chan->generator && chan->generator->release)
2525 chan->generator->release(chan, chan->generatordata);
2526 chan->generatordata = NULL;
2527 chan->generator = NULL;
2529 snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2530 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2532 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2533 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2534 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2535 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
2536 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2538 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
2539 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
2540 if (chan->tech->hangup)
2541 res = chan->tech->hangup(chan);
2543 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
2546 ast_channel_unlock(chan);
2548 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2551 "CallerIDNum: %s\r\n"
2552 "CallerIDName: %s\r\n"
2554 "Cause-txt: %s\r\n",
2557 S_OR(chan->cid.cid_num, "<unknown>"),
2558 S_OR(chan->cid.cid_name, "<unknown>"),
2560 ast_cause2str(chan->hangupcause)
2563 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
2564 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
2565 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2566 ast_channel_lock(chan);
2568 ast_cdr_end(chan->cdr);
2569 ast_cdr_detach(chan->cdr);
2571 ast_channel_unlock(chan);
2574 chan = ast_channel_release(chan);
2579 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2583 ast_channel_lock(chan);
2585 /* You can't answer an outbound call */
2586 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2587 ast_channel_unlock(chan);
2591 /* Stop if we're a zombie or need a soft hangup */
2592 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2593 ast_channel_unlock(chan);
2597 ast_channel_unlock(chan);
2599 switch (chan->_state) {
2600 case AST_STATE_RINGING:
2601 case AST_STATE_RING:
2602 ast_channel_lock(chan);
2603 if (chan->tech->answer) {
2604 res = chan->tech->answer(chan);
2606 ast_setstate(chan, AST_STATE_UP);
2608 ast_cdr_answer(chan->cdr);
2610 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2611 ast_channel_unlock(chan);
2614 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2615 /* Calling ast_cdr_answer when it it has previously been called
2616 * is essentially a no-op, so it is safe.
2619 ast_cdr_answer(chan->cdr);
2626 ast_indicate(chan, -1);
2627 chan->visible_indication = 0;
2632 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2635 enum ast_channel_state old_state;
2637 old_state = chan->_state;
2638 if ((res = ast_raw_answer(chan, cdr_answer))) {
2642 switch (old_state) {
2643 case AST_STATE_RINGING:
2644 case AST_STATE_RING:
2645 /* wait for media to start flowing, but don't wait any longer
2646 * than 'delay' or 500 milliseconds, whichever is longer
2649 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2650 struct ast_frame *cur, *new;
2651 int ms = MAX(delay, 500);
2652 unsigned int done = 0;
2654 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2657 ms = ast_waitfor(chan, ms);
2659 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
2664 ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
2667 cur = ast_read(chan);
2668 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2669 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2674 ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
2678 if ((new = ast_frisolate(cur)) != cur) {
2682 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2684 /* if a specific delay period was requested, continue
2685 * until that delay has passed. don't stop just because
2686 * incoming media has arrived.
2692 switch (new->frametype) {
2693 /* all of these frametypes qualify as 'media' */
2694 case AST_FRAME_VOICE:
2695 case AST_FRAME_VIDEO:
2696 case AST_FRAME_TEXT:
2697 case AST_FRAME_DTMF_BEGIN:
2698 case AST_FRAME_DTMF_END:
2699 case AST_FRAME_IMAGE:
2700 case AST_FRAME_HTML:
2701 case AST_FRAME_MODEM:
2704 case AST_FRAME_CONTROL:
2706 case AST_FRAME_NULL:
2717 ast_channel_lock(chan);
2718 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2719 ast_queue_frame_head(chan, cur);
2722 ast_channel_unlock(chan);
2733 int ast_answer(struct ast_channel *chan)
2735 return __ast_answer(chan, 0, 1);
2738 void ast_deactivate_generator(struct ast_channel *chan)
2740 ast_channel_lock(chan);
2741 if (chan->generatordata) {
2742 if (chan->generator && chan->generator->release)
2743 chan->generator->release(chan, chan->generatordata);
2744 chan->generatordata = NULL;
2745 chan->generator = NULL;
2746 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2747 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2748 ast_settimeout(chan, 0, NULL, NULL);
2750 ast_channel_unlock(chan);
2753 static int generator_force(const void *data)
2755 /* Called if generator doesn't have data */
2758 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2759 struct ast_channel *chan = (struct ast_channel *)data;
2761 ast_channel_lock(chan);
2762 tmp = chan->generatordata;
2763 chan->generatordata = NULL;
2764 if (chan->generator)
2765 generate = chan->generator->generate;
2766 ast_channel_unlock(chan);
2768 if (!tmp || !generate)
2771 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
2773 chan->generatordata = tmp;
2776 ast_debug(1, "Auto-deactivating generator\n");
2777 ast_deactivate_generator(chan);
2783 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2787 ast_channel_lock(chan);
2788 if (chan->generatordata) {
2789 if (chan->generator && chan->generator->release)
2790 chan->generator->release(chan, chan->generatordata);
2791 chan->generatordata = NULL;
2793 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2797 ast_settimeout(chan, 50, generator_force, chan);
2798 chan->generator = gen;
2800 ast_channel_unlock(chan);
2807 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2808 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2811 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2815 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2817 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2818 int *exception, int *outfd, int *ms)
2820 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2821 int *exception, int *outfd, int *ms)
2824 struct timeval start = { 0 , 0 };
2825 struct pollfd *pfds = NULL;
2830 struct timeval now = { 0, 0 };
2831 struct timeval whentohangup = { 0, 0 }, diff;
2832 struct ast_channel *winner = NULL;
2838 if ((sz = n * AST_MAX_FDS + nfds)) {
2839 pfds = alloca(sizeof(*pfds) * sz);
2840 fdmap = alloca(sizeof(*fdmap) * sz);
2848 /* Perform any pending masquerades */
2849 for (x = 0; x < n; x++) {
2850 if (c[x]->masq && ast_do_masquerade(c[x])) {
2851 ast_log(LOG_WARNING, "Masquerade failed\n");
2856 ast_channel_lock(c[x]);
2857 if (!ast_tvzero(c[x]->whentohangup)) {
2858 if (ast_tvzero(whentohangup))
2860 diff = ast_tvsub(c[x]->whentohangup, now);
2861 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
2862 /* Should already be hungup */
2863 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2864 ast_channel_unlock(c[x]);
2867 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
2868 whentohangup = diff;
2870 ast_channel_unlock(c[x]);
2872 /* Wait full interval */
2874 /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
2875 if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
2876 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
2877 if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
2880 } else if (!ast_tvzero(whentohangup) && rms < 0) {
2881 /* Tiny corner case... call would need to last >24 days */
2885 * Build the pollfd array, putting the channels' fds first,
2886 * followed by individual fds. Order is important because
2887 * individual fd's must have priority over channel fds.
2890 for (x = 0; x < n; x++) {
2891 for (y = 0; y < AST_MAX_FDS; y++) {
2892 fdmap[max].fdno = y; /* fd y is linked to this pfds */
2893 fdmap[max].chan = x; /* channel x is linked to this pfds */
2894 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
2896 CHECK_BLOCKING(c[x]);
2898 /* Add the individual fds */
2899 for (x = 0; x < nfds; x++) {
2900 fdmap[max].chan = -1;
2901 max += ast_add_fd(&pfds[max], fds[x]);
2905 start = ast_tvnow();
2907 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
2912 res = ast_poll(pfds, max, kbrms);
2915 } while (!res && (rms > 0));
2917 res = ast_poll(pfds, max, rms);
2919 for (x = 0; x < n; x++)
2920 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
2921 if (res < 0) { /* Simulate a timeout if we were interrupted */
2926 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
2928 for (x = 0; x < n; x++) {
2929 if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
2930 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2936 if (res == 0) { /* no fd ready, reset timeout and done */
2937 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
2941 * Then check if any channel or fd has a pending event.
2942 * Remember to check channels first and fds last, as they
2943 * must have priority on setting 'winner'
2945 for (x = 0; x < max; x++) {
2946 res = pfds[x].revents;
2949 if (fdmap[x].chan >= 0) { /* this is a channel */
2950 winner = c[fdmap[x].chan]; /* override previous winners */
2952 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2954 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2955 winner->fdno = fdmap[x].fdno;
2956 } else { /* this is an fd */
2958 *outfd = pfds[x].fd;
2960 *exception = (res & POLLPRI) ? -1 : 0;
2965 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2973 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
2975 struct timeval start = { 0 , 0 };
2977 struct epoll_event ev[1];
2978 long diff, rms = *ms;
2979 struct ast_channel *winner = NULL;
2980 struct ast_epoll_data *aed = NULL;
2983 /* See if this channel needs to be masqueraded */
2984 if (chan->masq && ast_do_masquerade(chan)) {
2985 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
2990 ast_channel_lock(chan);
2991 /* Figure out their timeout */
2992 if (!ast_tvzero(chan->whentohangup)) {
2993 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
2994 /* They should already be hungup! */
2995 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2996 ast_channel_unlock(chan);
2999 /* If this value is smaller then the current one... make it priority */
3004 ast_channel_unlock(chan);
3006 /* Time to make this channel block... */
3007 CHECK_BLOCKING(chan);
3010 start = ast_tvnow();
3012 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3013 res = epoll_wait(chan->epfd, ev, 1, rms);
3016 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3018 /* Simulate a timeout if we were interrupted */
3025 /* If this channel has a timeout see if it expired */
3026 if (!ast_tvzero(chan->whentohangup)) {
3027 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
3028 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3033 /* No fd ready, reset timeout and be done for now */
3039 /* See what events are pending */
3040 aed = ev[0].data.ptr;
3041 chan->fdno = aed->which;
3042 if (ev[0].events & EPOLLPRI)
3043 ast_set_flag(chan, AST_FLAG_EXCEPTION);
3045 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3048 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3056 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3058 struct timeval start = { 0 , 0 };
3060 struct epoll_event ev[25] = { { 0, } };
3061 struct timeval now = { 0, 0 };
3062 long whentohangup = 0, diff = 0, rms = *ms;
3063 struct ast_channel *winner = NULL;
3065 for (i = 0; i < n; i++) {
3066 if (c[i]->masq && ast_do_masquerade(c[i])) {
3067 ast_log(LOG_WARNING, "Masquerade failed\n");
3072 ast_channel_lock(c[i]);
3073 if (!ast_tvzero(c[i]->whentohangup)) {
3074 if (whentohangup == 0)
3076 if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
3077 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3078 ast_channel_unlock(c[i]);
3081 if (!whentohangup || whentohangup > diff)
3082 whentohangup = diff;
3084 ast_channel_unlock(c[i]);
3085 CHECK_BLOCKING(c[i]);
3091 if (*ms >= 0 && *ms < rms)
3096 start = ast_tvnow();
3098 res = epoll_wait(c[0]->epfd, ev, 25, rms);
3100 for (i = 0; i < n; i++)
3101 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
3111 for (i = 0; i < n; i++) {
3112 if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
3113 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3125 for (i = 0; i < res; i++) {
3126 struct ast_epoll_data *aed = ev[i].data.ptr;
3128 if (!ev[i].events || !aed)
3132 if (ev[i].events & EPOLLPRI)
3133 ast_set_flag(winner, AST_FLAG_EXCEPTION);
3135 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3136 winner->fdno = aed->which;
3140 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3148 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3149 int *exception, int *outfd, int *ms)
3151 /* Clear all provided values in one place. */
3157 /* If no epoll file descriptor is available resort to classic nandfds */
3158 if (!n || nfds || c[0]->epfd == -1)
3159 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3160 else if (!nfds && n == 1)
3161 return ast_waitfor_nandfds_simple(c[0], ms);
3163 return ast_waitfor_nandfds_complex(c, n, ms);
3167 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3169 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3172 int ast_waitfor(struct ast_channel *c, int ms)
3174 int oldms = ms; /* -1 if no timeout */
3176 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3177 if ((ms < 0) && (oldms < 0))
3182 /* XXX never to be called with ms = -1 */
3183 int ast_waitfordigit(struct ast_channel *c, int ms)
3185 return ast_waitfordigit_full(c, ms, -1, -1);
3188 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3191 unsigned int real_rate = rate, max_rate;
3193 ast_channel_lock(c);
3195 if (c->timingfd == -1) {
3196 ast_channel_unlock(c);
3205 if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
3206 real_rate = max_rate;
3209 ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3211 res = ast_timer_set_rate(c->timer, real_rate);
3213 c->timingfunc = func;
3214 c->timingdata = data;
3216 ast_channel_unlock(c);
3221 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
3223 /* Stop if we're a zombie or need a soft hangup */
3224 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3227 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3228 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
3230 /* Wait for a digit, no more than ms milliseconds total. */
3233 struct ast_channel *rchan;
3237 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3239 if (!rchan && outfd < 0 && ms) {
3240 if (errno == 0 || errno == EINTR)
3242 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
3243 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3245 } else if (outfd > -1) {
3246 /* The FD we were watching has something waiting */
3247 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
3248 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3252 struct ast_frame *f = ast_read(c);
3256 switch (f->frametype) {
3257 case AST_FRAME_DTMF_BEGIN:
3259 case AST_FRAME_DTMF_END:
3260 res = f->subclass.integer;
3262 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3264 case AST_FRAME_CONTROL:
3265 switch (f->subclass.integer) {
3266 case AST_CONTROL_HANGUP:
3268 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3270 case AST_CONTROL_RINGING:
3271 case AST_CONTROL_ANSWER:
3272 case AST_CONTROL_SRCUPDATE:
3273 case AST_CONTROL_SRCCHANGE:
3274 case AST_CONTROL_CONNECTED_LINE:
3275 case AST_CONTROL_REDIRECTING:
3279 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
3283 case AST_FRAME_VOICE:
3284 /* Write audio if appropriate */
3286 if (write(audiofd, f->data.ptr, f->datalen) < 0) {
3287 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3298 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3300 return 0; /* Time is up */
3303 static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
3305 ast_manager_event(chan, EVENT_FLAG_DTMF,