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/framehook.h"
66 #include "asterisk/timing.h"
67 #include "asterisk/autochan.h"
68 #include "asterisk/stringfields.h"
69 #include "asterisk/global_datastores.h"
70 #include "asterisk/data.h"
73 #include <sys/epoll.h>
76 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
79 #endif /* defined(HAVE_PRI) */
80 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
82 struct ast_epoll_data {
83 struct ast_channel *chan;
87 /* uncomment if you have problems with 'monitoring' synchronized files */
89 #define MONITOR_CONSTANT_DELAY
90 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
93 /*! \brief Prevent new channel allocation if shutting down. */
94 static int shutting_down;
98 unsigned long global_fin, global_fout;
100 AST_THREADSTORAGE(state2str_threadbuf);
101 #define STATE2STR_BUFSIZE 32
103 /*! Default amount of time to use when emulating a digit as a begin and end
105 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
107 /*! Minimum allowed digit length - 80ms */
108 #define AST_MIN_DTMF_DURATION 80
110 /*! Minimum amount of time between the end of the last digit and the beginning
111 * of a new one - 45ms */
112 #define AST_MIN_DTMF_GAP 45
114 /*! \brief List of channel drivers */
116 const struct ast_channel_tech *tech;
117 AST_LIST_ENTRY(chanlist) list;
121 /*! \brief Structure to hold channel context backtrace data */
122 struct ast_chan_trace_data {
124 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
127 /*! \brief Structure to save contexts where an ast_chan has been into */
128 struct ast_chan_trace {
129 char context[AST_MAX_CONTEXT];
130 char exten[AST_MAX_EXTENSION];
132 AST_LIST_ENTRY(ast_chan_trace) entry;
136 /*! \brief the list of registered channel types */
137 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
140 #define NUM_CHANNEL_BUCKETS 61
142 #define NUM_CHANNEL_BUCKETS 1567
145 #if 0 /* XXX AstData: ast_callerid no longer exists. (Equivalent code not readily apparent.) */
146 #define DATA_EXPORT_CALLERID(MEMBER) \
147 MEMBER(ast_callerid, cid_dnid, AST_DATA_STRING) \
148 MEMBER(ast_callerid, cid_num, AST_DATA_STRING) \
149 MEMBER(ast_callerid, cid_name, AST_DATA_STRING) \
150 MEMBER(ast_callerid, cid_ani, AST_DATA_STRING) \
151 MEMBER(ast_callerid, cid_pres, AST_DATA_INTEGER) \
152 MEMBER(ast_callerid, cid_ani2, AST_DATA_INTEGER) \
153 MEMBER(ast_callerid, cid_tag, AST_DATA_STRING)
155 AST_DATA_STRUCTURE(ast_callerid, DATA_EXPORT_CALLERID);
158 #define DATA_EXPORT_CHANNEL(MEMBER) \
159 MEMBER(ast_channel, blockproc, AST_DATA_STRING) \
160 MEMBER(ast_channel, appl, AST_DATA_STRING) \
161 MEMBER(ast_channel, data, AST_DATA_STRING) \
162 MEMBER(ast_channel, name, AST_DATA_STRING) \
163 MEMBER(ast_channel, language, AST_DATA_STRING) \
164 MEMBER(ast_channel, musicclass, AST_DATA_STRING) \
165 MEMBER(ast_channel, accountcode, AST_DATA_STRING) \
166 MEMBER(ast_channel, peeraccount, AST_DATA_STRING) \
167 MEMBER(ast_channel, userfield, AST_DATA_STRING) \
168 MEMBER(ast_channel, call_forward, AST_DATA_STRING) \
169 MEMBER(ast_channel, uniqueid, AST_DATA_STRING) \
170 MEMBER(ast_channel, linkedid, AST_DATA_STRING) \
171 MEMBER(ast_channel, parkinglot, AST_DATA_STRING) \
172 MEMBER(ast_channel, hangupsource, AST_DATA_STRING) \
173 MEMBER(ast_channel, dialcontext, AST_DATA_STRING) \
174 MEMBER(ast_channel, rings, AST_DATA_INTEGER) \
175 MEMBER(ast_channel, priority, AST_DATA_INTEGER) \
176 MEMBER(ast_channel, macropriority, AST_DATA_INTEGER) \
177 MEMBER(ast_channel, adsicpe, AST_DATA_INTEGER) \
178 MEMBER(ast_channel, fin, AST_DATA_UNSIGNED_INTEGER) \
179 MEMBER(ast_channel, fout, AST_DATA_UNSIGNED_INTEGER) \
180 MEMBER(ast_channel, emulate_dtmf_duration, AST_DATA_UNSIGNED_INTEGER) \
181 MEMBER(ast_channel, visible_indication, AST_DATA_INTEGER) \
182 MEMBER(ast_channel, context, AST_DATA_STRING) \
183 MEMBER(ast_channel, exten, AST_DATA_STRING) \
184 MEMBER(ast_channel, macrocontext, AST_DATA_STRING) \
185 MEMBER(ast_channel, macroexten, AST_DATA_STRING)
187 AST_DATA_STRUCTURE(ast_channel, DATA_EXPORT_CHANNEL);
190 /*! \brief All active channels on the system */
191 static struct ao2_container *channels;
193 /*! \brief map AST_CAUSE's to readable string representations
197 static const struct {
202 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
203 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
204 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
205 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
206 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
207 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
208 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
209 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
210 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
211 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
212 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
213 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
214 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
215 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
216 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
217 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
218 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
219 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
220 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
221 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
222 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
223 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
224 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
225 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
226 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
227 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
228 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
229 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
230 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
231 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
232 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
233 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
234 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
235 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
236 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
237 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
238 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
239 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
240 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
241 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
242 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
243 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
244 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
245 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
248 struct ast_variable *ast_channeltype_list(void)
251 struct ast_variable *var = NULL, *prev = NULL;
253 AST_RWLIST_RDLOCK(&backends);
254 AST_RWLIST_TRAVERSE(&backends, cl, list) {
256 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
259 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
263 AST_RWLIST_UNLOCK(&backends);
268 static void channel_data_add_flags(struct ast_data *tree,
269 struct ast_channel *chan)
271 ast_data_add_bool(tree, "DEFER_DTMF", ast_test_flag(chan, AST_FLAG_DEFER_DTMF));
272 ast_data_add_bool(tree, "WRITE_INT", ast_test_flag(chan, AST_FLAG_WRITE_INT));
273 ast_data_add_bool(tree, "BLOCKING", ast_test_flag(chan, AST_FLAG_BLOCKING));
274 ast_data_add_bool(tree, "ZOMBIE", ast_test_flag(chan, AST_FLAG_ZOMBIE));
275 ast_data_add_bool(tree, "EXCEPTION", ast_test_flag(chan, AST_FLAG_EXCEPTION));
276 ast_data_add_bool(tree, "MOH", ast_test_flag(chan, AST_FLAG_MOH));
277 ast_data_add_bool(tree, "SPYING", ast_test_flag(chan, AST_FLAG_SPYING));
278 ast_data_add_bool(tree, "NBRIDGE", ast_test_flag(chan, AST_FLAG_NBRIDGE));
279 ast_data_add_bool(tree, "IN_AUTOLOOP", ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP));
280 ast_data_add_bool(tree, "OUTGOING", ast_test_flag(chan, AST_FLAG_OUTGOING));
281 ast_data_add_bool(tree, "IN_DTMF", ast_test_flag(chan, AST_FLAG_IN_DTMF));
282 ast_data_add_bool(tree, "EMULATE_DTMF", ast_test_flag(chan, AST_FLAG_EMULATE_DTMF));
283 ast_data_add_bool(tree, "END_DTMF_ONLY", ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY));
284 ast_data_add_bool(tree, "ANSWERED_ELSEWHERE", ast_test_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE));
285 ast_data_add_bool(tree, "MASQ_NOSTREAM", ast_test_flag(chan, AST_FLAG_MASQ_NOSTREAM));
286 ast_data_add_bool(tree, "BRIDGE_HANGUP_RUN", ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_RUN));
287 ast_data_add_bool(tree, "BRIDGE_HANGUP_DONT", ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT));
288 ast_data_add_bool(tree, "DISABLE_WORKAROUNDS", ast_test_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS));
291 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
292 static const char *party_number_ton2str(int ton)
294 #if defined(HAVE_PRI)
295 switch ((ton >> 4) & 0x07) {
296 case PRI_TON_INTERNATIONAL:
297 return "International";
298 case PRI_TON_NATIONAL:
300 case PRI_TON_NET_SPECIFIC:
301 return "Network Specific";
302 case PRI_TON_SUBSCRIBER:
304 case PRI_TON_ABBREVIATED:
305 return "Abbreviated";
306 case PRI_TON_RESERVED:
308 case PRI_TON_UNKNOWN:
312 #endif /* defined(HAVE_PRI) */
315 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
317 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
318 static const char *party_number_plan2str(int plan)
320 #if defined(HAVE_PRI)
321 switch (plan & 0x0F) {
323 case PRI_NPI_UNKNOWN:
325 case PRI_NPI_E163_E164:
326 return "Public (E.163/E.164)";
328 return "Data (X.121)";
330 return "Telex (F.69)";
331 case PRI_NPI_NATIONAL:
332 return "National Standard";
333 case PRI_NPI_PRIVATE:
335 case PRI_NPI_RESERVED:
338 #endif /* defined(HAVE_PRI) */
341 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
343 int ast_channel_data_add_structure(struct ast_data *tree,
344 struct ast_channel *chan, int add_bridged)
346 struct ast_channel *bc;
347 struct ast_data *data_bridged;
348 struct ast_data *data_cdr;
349 struct ast_data *data_flags;
350 struct ast_data *data_zones;
351 struct ast_data *enum_node;
352 struct ast_data *data_softhangup;
353 #if 0 /* XXX AstData: ast_callerid no longer exists. (Equivalent code not readily apparent.) */
354 struct ast_data *data_callerid;
362 ast_data_add_structure(ast_channel, tree, chan);
365 bc = ast_bridged_channel(chan);
367 data_bridged = ast_data_add_node(tree, "bridged");
371 ast_channel_data_add_structure(data_bridged, bc, 0);
375 ast_data_add_codecs(tree, "oldwriteformat", chan->oldwriteformat);
376 ast_data_add_codecs(tree, "nativeformats", chan->nativeformats);
377 ast_data_add_codecs(tree, "readformat", chan->readformat);
378 ast_data_add_codecs(tree, "writeformat", chan->writeformat);
379 ast_data_add_codecs(tree, "rawreadformat", chan->rawreadformat);
380 ast_data_add_codecs(tree, "rawwriteformat", chan->rawwriteformat);
383 enum_node = ast_data_add_node(tree, "state");
387 ast_data_add_str(enum_node, "text", ast_state2str(chan->_state));
388 ast_data_add_int(enum_node, "value", chan->_state);
391 enum_node = ast_data_add_node(tree, "hangupcause");
395 ast_data_add_str(enum_node, "text", ast_cause2str(chan->hangupcause));
396 ast_data_add_int(enum_node, "value", chan->hangupcause);
399 enum_node = ast_data_add_node(tree, "amaflags");
403 ast_data_add_str(enum_node, "text", ast_cdr_flags2str(chan->amaflags));
404 ast_data_add_int(enum_node, "value", chan->amaflags);
406 /* transfercapability */
407 enum_node = ast_data_add_node(tree, "transfercapability");
411 ast_data_add_str(enum_node, "text", ast_transfercapability2str(chan->transfercapability));
412 ast_data_add_int(enum_node, "value", chan->transfercapability);
415 data_softhangup = ast_data_add_node(tree, "softhangup");
416 if (!data_softhangup) {
419 ast_data_add_bool(data_softhangup, "dev", chan->_softhangup & AST_SOFTHANGUP_DEV);
420 ast_data_add_bool(data_softhangup, "asyncgoto", chan->_softhangup & AST_SOFTHANGUP_ASYNCGOTO);
421 ast_data_add_bool(data_softhangup, "shutdown", chan->_softhangup & AST_SOFTHANGUP_SHUTDOWN);
422 ast_data_add_bool(data_softhangup, "timeout", chan->_softhangup & AST_SOFTHANGUP_TIMEOUT);
423 ast_data_add_bool(data_softhangup, "appunload", chan->_softhangup & AST_SOFTHANGUP_APPUNLOAD);
424 ast_data_add_bool(data_softhangup, "explicit", chan->_softhangup & AST_SOFTHANGUP_EXPLICIT);
425 ast_data_add_bool(data_softhangup, "unbridge", chan->_softhangup & AST_SOFTHANGUP_UNBRIDGE);
428 data_flags = ast_data_add_node(tree, "flags");
432 channel_data_add_flags(data_flags, chan);
434 ast_data_add_uint(tree, "timetohangup", chan->whentohangup.tv_sec);
436 #if 0 /* XXX AstData: ast_callerid no longer exists. (Equivalent code not readily apparent.) */
438 data_callerid = ast_data_add_node(tree, "callerid");
439 if (!data_callerid) {
442 ast_data_add_structure(ast_callerid, data_callerid, &(chan->cid));
443 /* insert the callerid ton */
444 enum_node = ast_data_add_node(data_callerid, "cid_ton");
448 ast_data_add_int(enum_node, "value", chan->cid.cid_ton);
449 snprintf(value_str, sizeof(value_str), "TON: %s/Plan: %s",
450 party_number_ton2str(chan->cid.cid_ton),
451 party_number_plan2str(chan->cid.cid_ton));
452 ast_data_add_str(enum_node, "text", value_str);
457 data_zones = ast_data_add_node(tree, "zone");
461 ast_tone_zone_data_add_structure(data_zones, chan->zone);
465 data_cdr = ast_data_add_node(tree, "cdr");
470 ast_cdr_data_add_structure(data_cdr, chan->cdr, 1);
475 int ast_channel_data_cmp_structure(const struct ast_data_search *tree,
476 struct ast_channel *chan, const char *structure_name)
478 return ast_data_search_cmp_structure(tree, ast_channel, chan, structure_name);
481 /*! \brief Show channel types - CLI command */
482 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
484 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
490 e->command = "core show channeltypes";
492 "Usage: core show channeltypes\n"
493 " Lists available channel types registered in your\n"
494 " Asterisk server.\n";
501 return CLI_SHOWUSAGE;
503 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
504 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
506 AST_RWLIST_RDLOCK(&backends);
507 AST_RWLIST_TRAVERSE(&backends, cl, list) {
508 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
509 (cl->tech->devicestate) ? "yes" : "no",
510 (cl->tech->indicate) ? "yes" : "no",
511 (cl->tech->transfer) ? "yes" : "no");
514 AST_RWLIST_UNLOCK(&backends);
516 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
523 static char *complete_channeltypes(struct ast_cli_args *a)
533 wordlen = strlen(a->word);
535 AST_RWLIST_RDLOCK(&backends);
536 AST_RWLIST_TRAVERSE(&backends, cl, list) {
537 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
538 ret = ast_strdup(cl->tech->type);
542 AST_RWLIST_UNLOCK(&backends);
547 /*! \brief Show details about a channel driver - CLI command */
548 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
550 struct chanlist *cl = NULL;
555 e->command = "core show channeltype";
557 "Usage: core show channeltype <name>\n"
558 " Show details about the specified channel type, <name>.\n";
561 return complete_channeltypes(a);
565 return CLI_SHOWUSAGE;
567 AST_RWLIST_RDLOCK(&backends);
569 AST_RWLIST_TRAVERSE(&backends, cl, list) {
570 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
576 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
577 AST_RWLIST_UNLOCK(&backends);
582 "-- Info about channel driver: %s --\n"
583 " Device State: %s\n"
586 " Capabilities: %s\n"
590 " Image Support: %s\n"
591 " Text Support: %s\n",
593 (cl->tech->devicestate) ? "yes" : "no",
594 (cl->tech->indicate) ? "yes" : "no",
595 (cl->tech->transfer) ? "yes" : "no",
596 ast_getformatname_multiple(buf, sizeof(buf), (cl->tech->capabilities) ? cl->tech->capabilities : -1),
597 (cl->tech->send_digit_begin) ? "yes" : "no",
598 (cl->tech->send_digit_end) ? "yes" : "no",
599 (cl->tech->send_html) ? "yes" : "no",
600 (cl->tech->send_image) ? "yes" : "no",
601 (cl->tech->send_text) ? "yes" : "no"
605 AST_RWLIST_UNLOCK(&backends);
610 static struct ast_cli_entry cli_channel[] = {
611 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
612 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
616 /*! \brief Destructor for the channel trace datastore */
617 static void ast_chan_trace_destroy_cb(void *data)
619 struct ast_chan_trace *trace;
620 struct ast_chan_trace_data *traced = data;
621 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
627 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
628 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
630 .destroy = ast_chan_trace_destroy_cb
633 /*! \brief Put the channel backtrace in a string */
634 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
637 struct ast_chan_trace *trace;
638 struct ast_chan_trace_data *traced;
639 struct ast_datastore *store;
641 ast_channel_lock(chan);
642 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
644 ast_channel_unlock(chan);
647 traced = store->data;
649 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
650 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
651 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
657 ast_channel_unlock(chan);
661 /* !\brief Whether or not context tracing is enabled */
662 int ast_channel_trace_is_enabled(struct ast_channel *chan)
664 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
667 return ((struct ast_chan_trace_data *)store->data)->enabled;
670 /*! \brief Update the context backtrace data if tracing is enabled */
671 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
673 struct ast_chan_trace *trace;
674 if (!traced->enabled)
676 /* If the last saved context does not match the current one
677 OR we have not saved any context so far, then save the current context */
678 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) ||
679 (AST_LIST_EMPTY(&traced->trace))) {
680 /* Just do some debug logging */
681 if (AST_LIST_EMPTY(&traced->trace))
682 ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
684 ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
685 /* alloc or bail out */
686 trace = ast_malloc(sizeof(*trace));
689 /* save the current location and store it in the trace list */
690 ast_copy_string(trace->context, chan->context, sizeof(trace->context));
691 ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
692 trace->priority = chan->priority;
693 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
698 /*! \brief Update the context backtrace if tracing is enabled */
699 int ast_channel_trace_update(struct ast_channel *chan)
701 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
704 return ast_channel_trace_data_update(chan, store->data);
707 /*! \brief Enable context tracing in the channel */
708 int ast_channel_trace_enable(struct ast_channel *chan)
710 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
711 struct ast_chan_trace_data *traced;
713 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
716 traced = ast_calloc(1, sizeof(*traced));
718 ast_datastore_free(store);
721 store->data = traced;
722 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
723 ast_channel_datastore_add(chan, store);
725 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
726 ast_channel_trace_data_update(chan, store->data);
730 /*! \brief Disable context tracing in the channel */
731 int ast_channel_trace_disable(struct ast_channel *chan)
733 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
736 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
739 #endif /* CHANNEL_TRACE */
741 /*! \brief Checks to see if a channel is needing hang up */
742 int ast_check_hangup(struct ast_channel *chan)
744 if (chan->_softhangup) /* yes if soft hangup flag set */
746 if (ast_tvzero(chan->whentohangup)) /* no if no hangup scheduled */
748 if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0) /* no if hangup time has not come yet. */
750 ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(chan->whentohangup, ast_tvnow()));
751 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
755 int ast_check_hangup_locked(struct ast_channel *chan)
758 ast_channel_lock(chan);
759 res = ast_check_hangup(chan);
760 ast_channel_unlock(chan);
764 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
766 struct ast_channel *chan = obj;
768 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
773 void ast_begin_shutdown(int hangup)
778 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
782 /*! \brief returns number of active/allocated channels */
783 int ast_active_channels(void)
785 return channels ? ao2_container_count(channels) : 0;
788 /*! \brief Cancel a shutdown in progress */
789 void ast_cancel_shutdown(void)
794 /*! \brief Returns non-zero if Asterisk is being shut down */
795 int ast_shutting_down(void)
797 return shutting_down;
800 /*! \brief Set when to hangup channel */
801 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
803 chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
804 ast_queue_frame(chan, &ast_null_frame);
808 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
810 struct timeval when = { offset, };
811 ast_channel_setwhentohangup_tv(chan, when);
814 /*! \brief Compare a offset with when to hangup channel */
815 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
817 struct timeval whentohangup;
819 if (ast_tvzero(chan->whentohangup))
820 return ast_tvzero(offset) ? 0 : -1;
822 if (ast_tvzero(offset))
825 whentohangup = ast_tvadd(offset, ast_tvnow());
827 return ast_tvdiff_ms(whentohangup, chan->whentohangup);
830 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
832 struct timeval when = { offset, };
833 return ast_channel_cmpwhentohangup_tv(chan, when);
836 /*! \brief Register a new telephony channel in Asterisk */
837 int ast_channel_register(const struct ast_channel_tech *tech)
839 struct chanlist *chan;
841 AST_RWLIST_WRLOCK(&backends);
843 AST_RWLIST_TRAVERSE(&backends, chan, list) {
844 if (!strcasecmp(tech->type, chan->tech->type)) {
845 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
846 AST_RWLIST_UNLOCK(&backends);
851 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
852 AST_RWLIST_UNLOCK(&backends);
856 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
858 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
860 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
862 AST_RWLIST_UNLOCK(&backends);
867 /*! \brief Unregister channel driver */
868 void ast_channel_unregister(const struct ast_channel_tech *tech)
870 struct chanlist *chan;
872 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
874 AST_RWLIST_WRLOCK(&backends);
876 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
877 if (chan->tech == tech) {
878 AST_LIST_REMOVE_CURRENT(list);
880 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
884 AST_LIST_TRAVERSE_SAFE_END;
886 AST_RWLIST_UNLOCK(&backends);
889 /*! \brief Get handle to channel driver based on name */
890 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
892 struct chanlist *chanls;
893 const struct ast_channel_tech *ret = NULL;
895 AST_RWLIST_RDLOCK(&backends);
897 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
898 if (!strcasecmp(name, chanls->tech->type)) {
904 AST_RWLIST_UNLOCK(&backends);
909 /*! \brief Gives the string form of a given hangup cause */
910 const char *ast_cause2str(int cause)
914 for (x = 0; x < ARRAY_LEN(causes); x++) {
915 if (causes[x].cause == cause)
916 return causes[x].desc;
922 /*! \brief Convert a symbolic hangup cause to number */
923 int ast_str2cause(const char *name)
927 for (x = 0; x < ARRAY_LEN(causes); x++)
928 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
929 return causes[x].cause;
934 /*! \brief Gives the string form of a given channel state.
935 \note This function is not reentrant.
937 const char *ast_state2str(enum ast_channel_state state)
944 case AST_STATE_RESERVED:
946 case AST_STATE_OFFHOOK:
948 case AST_STATE_DIALING:
952 case AST_STATE_RINGING:
958 case AST_STATE_DIALING_OFFHOOK:
959 return "Dialing Offhook";
960 case AST_STATE_PRERING:
963 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
965 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
970 /*! \brief Gives the string form of a given transfer capability */
971 char *ast_transfercapability2str(int transfercapability)
973 switch (transfercapability) {
974 case AST_TRANS_CAP_SPEECH:
976 case AST_TRANS_CAP_DIGITAL:
978 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
979 return "RESTRICTED_DIGITAL";
980 case AST_TRANS_CAP_3_1K_AUDIO:
982 case AST_TRANS_CAP_DIGITAL_W_TONES:
983 return "DIGITAL_W_TONES";
984 case AST_TRANS_CAP_VIDEO:
991 /*! \brief Pick the best audio codec */
992 format_t ast_best_codec(format_t fmts)
994 /* This just our opinion, expressed in code. We are asked to choose
995 the best codec to use, given no information */
997 static const format_t prefs[] =
999 /*! Okay, ulaw is used by all telephony equipment, so start with it */
1001 /*! Unless of course, you're a silly European, so then prefer ALAW */
1007 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
1009 /*! Okay, well, signed linear is easy to translate into other stuff */
1010 AST_FORMAT_SLINEAR16,
1012 /*! G.726 is standard ADPCM, in RFC3551 packing order */
1014 /*! G.726 is standard ADPCM, in AAL2 packing order */
1015 AST_FORMAT_G726_AAL2,
1016 /*! ADPCM has great sound quality and is still pretty easy to translate */
1018 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
1019 translate and sounds pretty good */
1021 /*! iLBC is not too bad */
1023 /*! Speex is free, but computationally more expensive than GSM */
1026 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
1029 /*! G.729a is faster than 723 and slightly less expensive */
1031 /*! Down to G.723.1 which is proprietary but at least designed for voice */
1036 /* Strip out video */
1037 fmts &= AST_FORMAT_AUDIO_MASK;
1039 /* Find the first preferred codec in the format given */
1040 for (x = 0; x < ARRAY_LEN(prefs); x++) {
1041 if (fmts & prefs[x])
1045 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), fmts));
1050 static const struct ast_channel_tech null_tech = {
1052 .description = "Null channel (should not see this)",
1055 static void ast_channel_destructor(void *obj);
1056 static void ast_dummy_channel_destructor(void *obj);
1058 /*! \brief Create a new channel structure */
1059 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
1060 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
1061 const char *acctcode, const char *exten, const char *context,
1062 const char *linkedid, const int amaflag, const char *file, int line,
1063 const char *function, const char *name_fmt, va_list ap1, va_list ap2)
1065 struct ast_channel *tmp;
1068 struct varshead *headp;
1069 char *tech = "", *tech2 = NULL;
1071 /* If shutting down, don't allocate any new channels */
1072 if (shutting_down) {
1073 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
1077 #if defined(REF_DEBUG)
1078 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
1080 #elif defined(__AST_DEBUG_MALLOC)
1081 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
1084 tmp = ao2_alloc(sizeof(*tmp), ast_channel_destructor);
1087 /* Channel structure allocation failure. */
1092 * Init file descriptors to unopened state so
1093 * the destructor can know not to close them.
1096 for (x = 0; x < ARRAY_LEN(tmp->alertpipe); ++x) {
1097 tmp->alertpipe[x] = -1;
1099 for (x = 0; x < ARRAY_LEN(tmp->fds); ++x) {
1103 tmp->epfd = epoll_create(25);
1106 if (!(tmp->sched = sched_context_create())) {
1107 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
1108 return ast_channel_unref(tmp);
1111 ast_party_dialed_init(&tmp->dialed);
1112 ast_party_caller_init(&tmp->caller);
1113 ast_party_connected_line_init(&tmp->connected);
1114 ast_party_redirecting_init(&tmp->redirecting);
1117 tmp->caller.id.name.valid = 1;
1118 tmp->caller.id.name.str = ast_strdup(cid_name);
1119 if (!tmp->caller.id.name.str) {
1120 return ast_channel_unref(tmp);
1124 tmp->caller.id.number.valid = 1;
1125 tmp->caller.id.number.str = ast_strdup(cid_num);
1126 if (!tmp->caller.id.number.str) {
1127 return ast_channel_unref(tmp);
1131 if ((tmp->timer = ast_timer_open())) {
1133 tmp->timingfd = ast_timer_fd(tmp->timer);
1137 if (pipe(tmp->alertpipe)) {
1138 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
1139 return ast_channel_unref(tmp);
1141 flags = fcntl(tmp->alertpipe[0], F_GETFL);
1142 if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
1143 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1144 return ast_channel_unref(tmp);
1146 flags = fcntl(tmp->alertpipe[1], F_GETFL);
1147 if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
1148 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1149 return ast_channel_unref(tmp);
1155 * This is the last place the channel constructor can fail.
1157 * The destructor takes advantage of this fact to ensure that the
1158 * AST_CEL_CHANNEL_END is not posted if we have not posted the
1159 * AST_CEL_CHANNEL_START yet.
1161 if ((ast_string_field_init(tmp, 128))) {
1162 return ast_channel_unref(tmp);
1165 /* Always watch the alertpipe */
1166 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
1167 /* And timing pipe */
1168 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
1171 tmp->_state = state;
1175 tmp->fin = global_fin;
1176 tmp->fout = global_fout;
1178 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1179 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
1180 ast_atomic_fetchadd_int(&uniqueint, 1));
1182 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
1183 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1186 if (!ast_strlen_zero(linkedid)) {
1187 ast_string_field_set(tmp, linkedid, linkedid);
1189 ast_string_field_set(tmp, linkedid, tmp->uniqueid);
1192 if (!ast_strlen_zero(name_fmt)) {
1193 char *slash, *slash2;
1194 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1195 * And they all use slightly different formats for their name string.
1196 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1197 * This means, that the stringfields must have a routine that takes the va_lists directly, and
1198 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1199 * This new function was written so this can be accomplished.
1201 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
1202 tech = ast_strdupa(tmp->name);
1203 if ((slash = strchr(tech, '/'))) {
1204 if ((slash2 = strchr(slash + 1, '/'))) {
1212 * Start the string with '-' so it becomes an empty string
1213 * in the destructor.
1215 ast_string_field_set(tmp, name, "-**Unknown**");
1218 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1220 /* These 4 variables need to be set up for the cdr_init() to work right */
1222 tmp->amaflags = amaflag;
1224 tmp->amaflags = ast_default_amaflags;
1226 if (!ast_strlen_zero(acctcode))
1227 ast_string_field_set(tmp, accountcode, acctcode);
1229 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
1231 if (!ast_strlen_zero(context))
1232 ast_copy_string(tmp->context, context, sizeof(tmp->context));
1234 strcpy(tmp->context, "default");
1236 if (!ast_strlen_zero(exten))
1237 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
1239 strcpy(tmp->exten, "s");
1243 tmp->cdr = ast_cdr_alloc();
1244 ast_cdr_init(tmp->cdr, tmp);
1245 ast_cdr_start(tmp->cdr);
1247 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1249 headp = &tmp->varshead;
1250 AST_LIST_HEAD_INIT_NOLOCK(headp);
1252 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
1254 AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
1256 ast_string_field_set(tmp, language, defaultlanguage);
1258 tmp->tech = &null_tech;
1260 ao2_link(channels, tmp);
1263 * And now, since the channel structure is built, and has its name, let's
1264 * call the manager event generator with this Newchannel event. This is the
1265 * proper and correct place to make this call, but you sure do have to pass
1266 * a lot of data into this func to do it here!
1268 if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1269 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1271 "ChannelState: %d\r\n"
1272 "ChannelStateDesc: %s\r\n"
1273 "CallerIDNum: %s\r\n"
1274 "CallerIDName: %s\r\n"
1275 "AccountCode: %s\r\n"
1281 ast_state2str(state),
1293 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1294 const char *cid_name, const char *acctcode,
1295 const char *exten, const char *context,
1296 const char *linkedid, const int amaflag,
1297 const char *file, int line, const char *function,
1298 const char *name_fmt, ...)
1301 struct ast_channel *result;
1303 va_start(ap1, name_fmt);
1304 va_start(ap2, name_fmt);
1305 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1306 linkedid, amaflag, file, line, function, name_fmt, ap1, ap2);
1313 /* only do the minimum amount of work needed here to make a channel
1314 * structure that can be used to expand channel vars */
1315 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1316 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1318 struct ast_channel *ast_dummy_channel_alloc(void)
1321 struct ast_channel *tmp;
1322 struct varshead *headp;
1324 #if defined(REF_DEBUG)
1325 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1326 file, line, function, 1);
1327 #elif defined(__AST_DEBUG_MALLOC)
1328 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1329 file, line, function, 0);
1331 tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor);
1334 /* Dummy channel structure allocation failure. */
1338 if ((ast_string_field_init(tmp, 128))) {
1339 return ast_channel_unref(tmp);
1342 headp = &tmp->varshead;
1343 AST_LIST_HEAD_INIT_NOLOCK(headp);
1348 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1350 struct ast_frame *f;
1351 struct ast_frame *cur;
1353 unsigned int new_frames = 0;
1354 unsigned int new_voice_frames = 0;
1355 unsigned int queued_frames = 0;
1356 unsigned int queued_voice_frames = 0;
1357 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1359 ast_channel_lock(chan);
1361 /* See if the last frame on the queue is a hangup, if so don't queue anything */
1362 if ((cur = AST_LIST_LAST(&chan->readq)) &&
1363 (cur->frametype == AST_FRAME_CONTROL) &&
1364 (cur->subclass.integer == AST_CONTROL_HANGUP)) {
1365 ast_channel_unlock(chan);
1369 /* Build copies of all the frames and count them */
1370 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1371 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1372 if (!(f = ast_frdup(cur))) {
1373 if (AST_LIST_FIRST(&frames)) {
1374 ast_frfree(AST_LIST_FIRST(&frames));
1376 ast_channel_unlock(chan);
1380 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1382 if (f->frametype == AST_FRAME_VOICE) {
1387 /* Count how many frames exist on the queue */
1388 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1390 if (cur->frametype == AST_FRAME_VOICE) {
1391 queued_voice_frames++;
1395 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1397 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", chan->name);
1398 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
1399 /* Save the most recent frame */
1400 if (!AST_LIST_NEXT(cur, frame_list)) {
1402 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1406 AST_LIST_REMOVE_CURRENT(frame_list);
1410 AST_LIST_TRAVERSE_SAFE_END;
1414 AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1417 AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1418 AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1420 AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1423 if (chan->alertpipe[1] > -1) {
1424 if (write(chan->alertpipe[1], &blah, new_frames * sizeof(blah)) != (new_frames * sizeof(blah))) {
1425 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1426 chan->name, queued_frames, strerror(errno));
1428 } else if (chan->timingfd > -1) {
1429 ast_timer_enable_continuous(chan->timer);
1430 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1431 pthread_kill(chan->blocker, SIGURG);
1434 ast_channel_unlock(chan);
1439 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1441 return __ast_queue_frame(chan, fin, 0, NULL);
1444 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1446 return __ast_queue_frame(chan, fin, 1, NULL);
1449 /*! \brief Queue a hangup frame for channel */
1450 int ast_queue_hangup(struct ast_channel *chan)
1452 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1453 /* Yeah, let's not change a lock-critical value without locking */
1454 if (!ast_channel_trylock(chan)) {
1455 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1456 ast_channel_unlock(chan);
1458 return ast_queue_frame(chan, &f);
1461 /*! \brief Queue a hangup frame for channel */
1462 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1464 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1467 f.data.uint32 = cause;
1469 /* Yeah, let's not change a lock-critical value without locking */
1470 if (!ast_channel_trylock(chan)) {
1471 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1473 f.data.uint32 = chan->hangupcause;
1475 ast_channel_unlock(chan);
1478 return ast_queue_frame(chan, &f);
1481 /*! \brief Queue a control frame */
1482 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1484 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1485 return ast_queue_frame(chan, &f);
1488 /*! \brief Queue a control frame with payload */
1489 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1490 const void *data, size_t datalen)
1492 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1493 return ast_queue_frame(chan, &f);
1496 /*! \brief Set defer DTMF flag on channel */
1497 int ast_channel_defer_dtmf(struct ast_channel *chan)
1502 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1503 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1508 /*! \brief Unset defer DTMF flag on channel */
1509 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1512 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1515 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1516 void *data, int ao2_flags)
1518 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1521 struct ast_channel_iterator {
1522 /* storage for non-dynamically allocated iterator */
1523 struct ao2_iterator simple_iterator;
1524 /* pointer to the actual iterator (simple_iterator or a dynamically
1525 * allocated iterator)
1527 struct ao2_iterator *active_iterator;
1530 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1532 ao2_iterator_destroy(i->active_iterator);
1538 static struct ast_channel_iterator *channel_iterator_search(const char *name,
1539 size_t name_len, const char *exten,
1540 const char *context)
1542 struct ast_channel_iterator *i;
1543 struct ast_channel tmp_chan = {
1545 /* This is sort of a hack. Basically, we're using an arbitrary field
1546 * in ast_channel to pass the name_len for a prefix match. If this
1547 * gets changed, then the compare callback must be changed, too. */
1551 if (!(i = ast_calloc(1, sizeof(*i)))) {
1556 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1560 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1563 if (!(i->active_iterator = ao2_find(channels, &tmp_chan,
1564 OBJ_MULTIPLE | ((!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0)))) {
1572 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1574 return channel_iterator_search(NULL, 0, exten, context);
1577 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1579 return channel_iterator_search(name, name_len, NULL, NULL);
1582 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1584 struct ast_channel_iterator *i;
1586 if (!(i = ast_calloc(1, sizeof(*i)))) {
1590 i->simple_iterator = ao2_iterator_init(channels, 0);
1591 i->active_iterator = &i->simple_iterator;
1596 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1598 return ao2_iterator_next(i->active_iterator);
1601 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1603 struct ast_channel *chan = obj, *cmp_args = arg;
1605 int ret = CMP_MATCH;
1607 /* This is sort of a hack. Basically, we're using an arbitrary field
1608 * in ast_channel to pass the name_len for a prefix match. If this
1609 * gets changed, then the uses of ao2_find() must be changed, too. */
1610 name_len = cmp_args->rings;
1612 ast_channel_lock(chan);
1614 if (!ast_strlen_zero(cmp_args->name)) { /* match by name */
1615 if ((!name_len && strcasecmp(chan->name, cmp_args->name)) ||
1616 (name_len && strncasecmp(chan->name, cmp_args->name, name_len))) {
1617 ret = 0; /* name match failed */
1619 } else if (!ast_strlen_zero(cmp_args->exten)) {
1620 if (cmp_args->context && strcasecmp(chan->context, cmp_args->context) &&
1621 strcasecmp(chan->macrocontext, cmp_args->context)) {
1622 ret = 0; /* context match failed */
1624 if (ret && strcasecmp(chan->exten, cmp_args->exten) &&
1625 strcasecmp(chan->macroexten, cmp_args->exten)) {
1626 ret = 0; /* exten match failed */
1628 } else if (!ast_strlen_zero(cmp_args->uniqueid)) {
1629 if ((!name_len && strcasecmp(chan->uniqueid, cmp_args->uniqueid)) ||
1630 (name_len && strncasecmp(chan->uniqueid, cmp_args->uniqueid, name_len))) {
1631 ret = 0; /* uniqueid match failed */
1637 ast_channel_unlock(chan);
1642 static struct ast_channel *ast_channel_get_full(const char *name, size_t name_len,
1643 const char *exten, const char *context)
1645 struct ast_channel tmp_chan = {
1647 /* This is sort of a hack. Basically, we're using an arbitrary field
1648 * in ast_channel to pass the name_len for a prefix match. If this
1649 * gets changed, then the compare callback must be changed, too. */
1652 struct ast_channel *chan;
1655 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1659 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1662 if ((chan = ao2_find(channels, &tmp_chan,
1663 (!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0))) {
1671 /* If name was specified, but the result was NULL,
1672 * try a search on uniqueid, instead. */
1675 struct ast_channel tmp_chan2 = {
1680 return ao2_find(channels, &tmp_chan2, 0);
1684 struct ast_channel *ast_channel_get_by_name(const char *name)
1686 return ast_channel_get_full(name, 0, NULL, NULL);
1689 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1691 return ast_channel_get_full(name, name_len, NULL, NULL);
1694 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1696 return ast_channel_get_full(NULL, 0, exten, context);
1699 int ast_is_deferrable_frame(const struct ast_frame *frame)
1701 /* Do not add a default entry in this switch statement. Each new
1702 * frame type should be addressed directly as to whether it should
1703 * be queued up or not.
1705 switch (frame->frametype) {
1706 case AST_FRAME_DTMF_END:
1707 case AST_FRAME_CONTROL:
1708 case AST_FRAME_TEXT:
1709 case AST_FRAME_IMAGE:
1710 case AST_FRAME_HTML:
1713 case AST_FRAME_DTMF_BEGIN:
1714 case AST_FRAME_VOICE:
1715 case AST_FRAME_VIDEO:
1716 case AST_FRAME_NULL:
1719 case AST_FRAME_MODEM:
1725 /*! \brief Wait, look for hangups and condition arg */
1726 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1728 struct ast_frame *f;
1729 struct ast_silence_generator *silgen = NULL;
1731 AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1733 AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1735 /* If no other generator is present, start silencegen while waiting */
1736 if (ast_opt_transmit_silence && !chan->generatordata) {
1737 silgen = ast_channel_start_silence_generator(chan);
1741 struct ast_frame *dup_f = NULL;
1742 if (cond && ((*cond)(data) == 0)) {
1745 ms = ast_waitfor(chan, ms);
1757 if (!ast_is_deferrable_frame(f)) {
1762 if ((dup_f = ast_frisolate(f))) {
1766 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1771 /* stop silgen if present */
1773 ast_channel_stop_silence_generator(chan, silgen);
1776 /* We need to free all the deferred frames, but we only need to
1777 * queue the deferred frames if there was no error and no
1778 * hangup was received
1780 ast_channel_lock(chan);
1781 while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1783 ast_queue_frame_head(chan, f);
1787 ast_channel_unlock(chan);
1792 /*! \brief Wait, look for hangups */
1793 int ast_safe_sleep(struct ast_channel *chan, int ms)
1795 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1798 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1800 /* Safe, even if already unlinked. */
1801 ao2_unlink(channels, chan);
1802 return ast_channel_unref(chan);
1805 void ast_party_name_init(struct ast_party_name *init)
1808 init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1809 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1813 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1816 /* Don't copy to self */
1820 ast_free(dest->str);
1821 dest->str = ast_strdup(src->str);
1822 dest->char_set = src->char_set;
1823 dest->presentation = src->presentation;
1824 dest->valid = src->valid;
1827 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1830 init->char_set = guide->char_set;
1831 init->presentation = guide->presentation;
1832 init->valid = guide->valid;
1835 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1838 /* Don't set to self */
1842 if (src->str && src->str != dest->str) {
1843 ast_free(dest->str);
1844 dest->str = ast_strdup(src->str);
1847 dest->char_set = src->char_set;
1848 dest->presentation = src->presentation;
1849 dest->valid = src->valid;
1852 void ast_party_name_free(struct ast_party_name *doomed)
1854 ast_free(doomed->str);
1858 void ast_party_number_init(struct ast_party_number *init)
1861 init->plan = 0;/* Unknown */
1862 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1866 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1869 /* Don't copy to self */
1873 ast_free(dest->str);
1874 dest->str = ast_strdup(src->str);
1875 dest->plan = src->plan;
1876 dest->presentation = src->presentation;
1877 dest->valid = src->valid;
1880 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1883 init->plan = guide->plan;
1884 init->presentation = guide->presentation;
1885 init->valid = guide->valid;
1888 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1891 /* Don't set to self */
1895 if (src->str && src->str != dest->str) {
1896 ast_free(dest->str);
1897 dest->str = ast_strdup(src->str);
1900 dest->plan = src->plan;
1901 dest->presentation = src->presentation;
1902 dest->valid = src->valid;
1905 void ast_party_number_free(struct ast_party_number *doomed)
1907 ast_free(doomed->str);
1911 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1915 init->odd_even_indicator = 0;
1919 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1922 /* Don't copy to self */
1926 ast_free(dest->str);
1927 dest->str = ast_strdup(src->str);
1928 dest->type = src->type;
1929 dest->odd_even_indicator = src->odd_even_indicator;
1930 dest->valid = src->valid;
1933 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1936 init->type = guide->type;
1937 init->odd_even_indicator = guide->odd_even_indicator;
1938 init->valid = guide->valid;
1941 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1944 /* Don't set to self */
1948 if (src->str && src->str != dest->str) {
1949 ast_free(dest->str);
1950 dest->str = ast_strdup(src->str);
1953 dest->type = src->type;
1954 dest->odd_even_indicator = src->odd_even_indicator;
1955 dest->valid = src->valid;
1958 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1960 ast_free(doomed->str);
1964 void ast_party_id_init(struct ast_party_id *init)
1966 ast_party_name_init(&init->name);
1967 ast_party_number_init(&init->number);
1968 ast_party_subaddress_init(&init->subaddress);
1972 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1975 /* Don't copy to self */
1979 ast_party_name_copy(&dest->name, &src->name);
1980 ast_party_number_copy(&dest->number, &src->number);
1981 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1983 ast_free(dest->tag);
1984 dest->tag = ast_strdup(src->tag);
1987 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1989 ast_party_name_set_init(&init->name, &guide->name);
1990 ast_party_number_set_init(&init->number, &guide->number);
1991 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1995 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1998 /* Don't set to self */
2002 if (!update || update->name) {
2003 ast_party_name_set(&dest->name, &src->name);
2005 if (!update || update->number) {
2006 ast_party_number_set(&dest->number, &src->number);
2008 if (!update || update->subaddress) {
2009 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2012 if (src->tag && src->tag != dest->tag) {
2013 ast_free(dest->tag);
2014 dest->tag = ast_strdup(src->tag);
2018 void ast_party_id_free(struct ast_party_id *doomed)
2020 ast_party_name_free(&doomed->name);
2021 ast_party_number_free(&doomed->number);
2022 ast_party_subaddress_free(&doomed->subaddress);
2024 ast_free(doomed->tag);
2028 int ast_party_id_presentation(const struct ast_party_id *id)
2030 int number_priority;
2032 int number_screening;
2036 /* Determine name presentation priority. */
2037 if (!id->name.valid) {
2038 name_value = AST_PRES_UNAVAILABLE;
2041 name_value = id->name.presentation & AST_PRES_RESTRICTION;
2042 switch (name_value) {
2043 case AST_PRES_RESTRICTED:
2046 case AST_PRES_ALLOWED:
2049 case AST_PRES_UNAVAILABLE:
2053 name_value = AST_PRES_UNAVAILABLE;
2059 /* Determine number presentation priority. */
2060 if (!id->number.valid) {
2061 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2062 number_value = AST_PRES_UNAVAILABLE;
2063 number_priority = 3;
2065 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
2066 number_value = id->number.presentation & AST_PRES_RESTRICTION;
2067 switch (number_value) {
2068 case AST_PRES_RESTRICTED:
2069 number_priority = 0;
2071 case AST_PRES_ALLOWED:
2072 number_priority = 1;
2074 case AST_PRES_UNAVAILABLE:
2075 number_priority = 2;
2078 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2079 number_value = AST_PRES_UNAVAILABLE;
2080 number_priority = 3;
2085 /* Select the wining presentation value. */
2086 if (name_priority < number_priority) {
2087 number_value = name_value;
2090 return number_value | number_screening;
2093 void ast_party_dialed_init(struct ast_party_dialed *init)
2095 init->number.str = NULL;
2096 init->number.plan = 0;/* Unknown */
2097 ast_party_subaddress_init(&init->subaddress);
2098 init->transit_network_select = 0;
2101 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2104 /* Don't copy to self */
2108 ast_free(dest->number.str);
2109 dest->number.str = ast_strdup(src->number.str);
2110 dest->number.plan = src->number.plan;
2111 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2112 dest->transit_network_select = src->transit_network_select;
2115 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2117 init->number.str = NULL;
2118 init->number.plan = guide->number.plan;
2119 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2120 init->transit_network_select = guide->transit_network_select;
2123 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2125 if (src->number.str && src->number.str != dest->number.str) {
2126 ast_free(dest->number.str);
2127 dest->number.str = ast_strdup(src->number.str);
2129 dest->number.plan = src->number.plan;
2131 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2133 dest->transit_network_select = src->transit_network_select;
2136 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2138 ast_free(doomed->number.str);
2139 doomed->number.str = NULL;
2140 ast_party_subaddress_free(&doomed->subaddress);
2143 void ast_party_caller_init(struct ast_party_caller *init)
2145 ast_party_id_init(&init->id);
2146 ast_party_id_init(&init->ani);
2150 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2153 /* Don't copy to self */
2157 ast_party_id_copy(&dest->id, &src->id);
2158 ast_party_id_copy(&dest->ani, &src->ani);
2159 dest->ani2 = src->ani2;
2162 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2164 ast_party_id_set_init(&init->id, &guide->id);
2165 ast_party_id_set_init(&init->ani, &guide->ani);
2166 init->ani2 = guide->ani2;
2169 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2171 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2172 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2173 dest->ani2 = src->ani2;
2176 void ast_party_caller_free(struct ast_party_caller *doomed)
2178 ast_party_id_free(&doomed->id);
2179 ast_party_id_free(&doomed->ani);
2182 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2184 ast_party_id_init(&init->id);
2185 ast_party_id_init(&init->ani);
2187 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2190 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2193 /* Don't copy to self */
2197 ast_party_id_copy(&dest->id, &src->id);
2198 ast_party_id_copy(&dest->ani, &src->ani);
2199 dest->ani2 = src->ani2;
2200 dest->source = src->source;
2203 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2205 ast_party_id_set_init(&init->id, &guide->id);
2206 ast_party_id_set_init(&init->ani, &guide->ani);
2207 init->ani2 = guide->ani2;
2208 init->source = guide->source;
2211 void ast_party_connected_line_set(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src, const struct ast_set_party_connected_line *update)
2213 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2214 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2215 dest->ani2 = src->ani2;
2216 dest->source = src->source;
2219 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2221 connected->id = caller->id;
2222 connected->ani = caller->ani;
2223 connected->ani2 = caller->ani2;
2224 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2227 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2229 ast_party_id_free(&doomed->id);
2230 ast_party_id_free(&doomed->ani);
2233 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2235 ast_party_id_init(&init->from);
2236 ast_party_id_init(&init->to);
2238 init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2241 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2244 /* Don't copy to self */
2248 ast_party_id_copy(&dest->from, &src->from);
2249 ast_party_id_copy(&dest->to, &src->to);
2250 dest->count = src->count;
2251 dest->reason = src->reason;
2254 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2256 ast_party_id_set_init(&init->from, &guide->from);
2257 ast_party_id_set_init(&init->to, &guide->to);
2258 init->count = guide->count;
2259 init->reason = guide->reason;
2262 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2264 ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2265 ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2266 dest->reason = src->reason;
2267 dest->count = src->count;
2270 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2272 ast_party_id_free(&doomed->from);
2273 ast_party_id_free(&doomed->to);
2276 /*! \brief Free a channel structure */
2277 static void ast_channel_destructor(void *obj)
2279 struct ast_channel *chan = obj;
2284 struct ast_var_t *vardata;
2285 struct ast_frame *f;
2286 struct varshead *headp;
2287 struct ast_datastore *datastore;
2288 char device_name[AST_CHANNEL_NAME];
2291 /* The string fields were initialized. */
2292 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2293 ast_cel_check_retire_linkedid(chan);
2296 /* Get rid of each of the data stores on the channel */
2297 ast_channel_lock(chan);
2298 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
2299 /* Free the data store */
2300 ast_datastore_free(datastore);
2301 ast_channel_unlock(chan);
2303 /* Lock and unlock the channel just to be sure nobody has it locked still
2304 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2305 ast_channel_lock(chan);
2306 ast_channel_unlock(chan);
2308 if (chan->tech_pvt) {
2309 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
2310 ast_free(chan->tech_pvt);
2314 sched_context_destroy(chan->sched);
2319 /* The string fields were initialized. */
2320 ast_copy_string(device_name, chan->name, sizeof(device_name));
2321 if ((dashptr = strrchr(device_name, '-'))) {
2325 device_name[0] = '\0';
2328 /* Stop monitoring */
2330 chan->monitor->stop( chan, 0 );
2332 /* If there is native format music-on-hold state, free it */
2333 if (chan->music_state)
2334 ast_moh_cleanup(chan);
2336 /* Free translators */
2337 if (chan->readtrans)
2338 ast_translator_free_path(chan->readtrans);
2339 if (chan->writetrans)
2340 ast_translator_free_path(chan->writetrans);
2342 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
2344 ast_party_dialed_free(&chan->dialed);
2345 ast_party_caller_free(&chan->caller);
2346 ast_party_connected_line_free(&chan->connected);
2347 ast_party_redirecting_free(&chan->redirecting);
2349 /* Close pipes if appropriate */
2350 if ((fd = chan->alertpipe[0]) > -1)
2352 if ((fd = chan->alertpipe[1]) > -1)
2355 ast_timer_close(chan->timer);
2358 for (i = 0; i < AST_MAX_FDS; i++) {
2359 if (chan->epfd_data[i])
2360 free(chan->epfd_data[i]);
2364 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
2367 /* loop over the variables list, freeing all data and deleting list items */
2368 /* no need to lock the list, as the channel is already locked */
2369 headp = &chan->varshead;
2370 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2371 ast_var_delete(vardata);
2373 ast_app_group_discard(chan);
2375 /* Destroy the jitterbuffer */
2376 ast_jb_destroy(chan);
2379 ast_cdr_discard(chan->cdr);
2384 chan->zone = ast_tone_zone_unref(chan->zone);
2387 ast_string_field_free_memory(chan);
2389 if (device_name[0]) {
2391 * We have a device name to notify of a new state.
2393 * Queue an unknown state, because, while we know that this particular
2394 * instance is dead, we don't know the state of all other possible
2397 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2401 /*! \brief Free a dummy channel structure */
2402 static void ast_dummy_channel_destructor(void *obj)
2404 struct ast_channel *chan = obj;
2405 struct ast_var_t *vardata;
2406 struct varshead *headp;
2408 headp = &chan->varshead;
2410 ast_party_dialed_free(&chan->dialed);
2411 ast_party_caller_free(&chan->caller);
2412 ast_party_connected_line_free(&chan->connected);
2413 ast_party_redirecting_free(&chan->redirecting);
2415 /* loop over the variables list, freeing all data and deleting list items */
2416 /* no need to lock the list, as the channel is already locked */
2417 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2418 ast_var_delete(vardata);
2421 ast_cdr_discard(chan->cdr);
2425 ast_string_field_free_memory(chan);
2428 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2430 return ast_datastore_alloc(info, uid);
2433 int ast_channel_datastore_free(struct ast_datastore *datastore)
2435 return ast_datastore_free(datastore);
2438 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2440 struct ast_datastore *datastore = NULL, *datastore2;
2442 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
2443 if (datastore->inheritance > 0) {
2444 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2446 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2447 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2448 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
2455 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2459 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
2464 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2466 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
2469 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2471 struct ast_datastore *datastore = NULL;
2476 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
2477 if (datastore->info != info) {
2482 /* matched by type only */
2486 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2487 /* Matched by type AND uid */
2491 AST_LIST_TRAVERSE_SAFE_END;
2496 /*! Set the file descriptor on the channel */
2497 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2500 struct epoll_event ev;
2501 struct ast_epoll_data *aed = NULL;
2503 if (chan->fds[which] > -1) {
2504 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2505 aed = chan->epfd_data[which];
2508 /* If this new fd is valid, add it to the epoll */
2510 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2513 chan->epfd_data[which] = aed;
2517 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2519 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2521 /* We don't have to keep around this epoll data structure now */
2523 chan->epfd_data[which] = NULL;
2526 chan->fds[which] = fd;
2530 /*! Add a channel to an optimized waitfor */
2531 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2534 struct epoll_event ev;
2537 if (chan0->epfd == -1)
2540 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2541 for (i = 0; i < AST_MAX_FDS; i++) {
2542 if (chan1->fds[i] == -1)
2544 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2545 ev.data.ptr = chan1->epfd_data[i];
2546 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2553 /*! Delete a channel from an optimized waitfor */
2554 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2557 struct epoll_event ev;
2560 if (chan0->epfd == -1)
2563 for (i = 0; i < AST_MAX_FDS; i++) {
2564 if (chan1->fds[i] == -1)
2566 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2573 /*! \brief Softly hangup a channel, don't lock */
2574 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2576 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
2577 /* Inform channel driver that we need to be hung up, if it cares */
2578 chan->_softhangup |= cause;
2579 ast_queue_frame(chan, &ast_null_frame);
2580 /* Interrupt any poll call or such */
2581 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2582 pthread_kill(chan->blocker, SIGURG);
2586 /*! \brief Softly hangup a channel, lock */
2587 int ast_softhangup(struct ast_channel *chan, int cause)
2591 ast_channel_lock(chan);
2592 res = ast_softhangup_nolock(chan, cause);
2593 ast_channel_unlock(chan);
2598 static void free_translation(struct ast_channel *clonechan)
2600 if (clonechan->writetrans)
2601 ast_translator_free_path(clonechan->writetrans);
2602 if (clonechan->readtrans)
2603 ast_translator_free_path(clonechan->readtrans);
2604 clonechan->writetrans = NULL;
2605 clonechan->readtrans = NULL;
2606 clonechan->rawwriteformat = clonechan->nativeformats;
2607 clonechan->rawreadformat = clonechan->nativeformats;
2610 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2612 struct ast_channel *bridge;
2614 ast_channel_lock(chan);
2615 if (force || ast_strlen_zero(chan->hangupsource)) {
2616 ast_string_field_set(chan, hangupsource, source);
2618 bridge = ast_bridged_channel(chan);
2619 ast_channel_unlock(chan);
2621 if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
2622 ast_channel_lock(bridge);
2623 ast_string_field_set(chan, hangupsource, source);
2624 ast_channel_unlock(bridge);
2628 /*! \brief Hangup a channel */
2629 int ast_hangup(struct ast_channel *chan)
2632 char extra_str[64]; /* used for cel logging below */
2634 /* Don't actually hang up a channel that will masquerade as someone else, or
2635 if someone is going to masquerade as us */
2636 ast_channel_lock(chan);
2638 if (chan->audiohooks) {
2639 ast_audiohook_detach_list(chan->audiohooks);
2640 chan->audiohooks = NULL;
2643 ast_framehook_list_destroy(chan);
2645 ast_autoservice_stop(chan);
2648 ast_channel_unlock(chan);
2649 if (ast_do_masquerade(chan)) {
2650 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2652 ast_channel_lock(chan);
2656 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
2657 ast_channel_unlock(chan);
2660 /* If this channel is one which will be masqueraded into something,
2661 mark it as a zombie already, so we know to free it later */
2663 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2664 ast_channel_unlock(chan);
2667 ast_channel_unlock(chan);
2669 ao2_unlink(channels, chan);
2671 ast_channel_lock(chan);
2672 free_translation(chan);
2673 /* Close audio stream */
2675 ast_closestream(chan->stream);
2676 chan->stream = NULL;
2678 /* Close video stream */
2679 if (chan->vstream) {
2680 ast_closestream(chan->vstream);
2681 chan->vstream = NULL;
2684 sched_context_destroy(chan->sched);
2688 if (chan->generatordata) /* Clear any tone stuff remaining */
2689 if (chan->generator && chan->generator->release)
2690 chan->generator->release(chan, chan->generatordata);
2691 chan->generatordata = NULL;
2692 chan->generator = NULL;
2694 snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2695 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2697 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2698 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2699 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2700 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
2701 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2703 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
2704 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
2705 if (chan->tech->hangup)
2706 res = chan->tech->hangup(chan);
2708 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
2711 ast_channel_unlock(chan);
2713 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2716 "CallerIDNum: %s\r\n"
2717 "CallerIDName: %s\r\n"
2719 "Cause-txt: %s\r\n",
2722 S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<unknown>"),
2723 S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, "<unknown>"),
2725 ast_cause2str(chan->hangupcause)
2728 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
2729 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
2730 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2731 ast_channel_lock(chan);
2733 ast_cdr_end(chan->cdr);
2734 ast_cdr_detach(chan->cdr);
2736 ast_channel_unlock(chan);
2739 chan = ast_channel_release(chan);
2744 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2748 ast_channel_lock(chan);
2750 /* You can't answer an outbound call */
2751 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2752 ast_channel_unlock(chan);
2756 /* Stop if we're a zombie or need a soft hangup */
2757 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2758 ast_channel_unlock(chan);
2762 ast_channel_unlock(chan);
2764 switch (chan->_state) {
2765 case AST_STATE_RINGING:
2766 case AST_STATE_RING:
2767 ast_channel_lock(chan);
2768 if (chan->tech->answer) {
2769 res = chan->tech->answer(chan);
2771 ast_setstate(chan, AST_STATE_UP);
2773 ast_cdr_answer(chan->cdr);
2775 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2776 ast_channel_unlock(chan);
2779 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2780 /* Calling ast_cdr_answer when it it has previously been called
2781 * is essentially a no-op, so it is safe.
2784 ast_cdr_answer(chan->cdr);
2791 ast_indicate(chan, -1);
2792 chan->visible_indication = 0;
2797 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2800 enum ast_channel_state old_state;
2802 old_state = chan->_state;
2803 if ((res = ast_raw_answer(chan, cdr_answer))) {
2807 switch (old_state) {
2808 case AST_STATE_RINGING:
2809 case AST_STATE_RING:
2810 /* wait for media to start flowing, but don't wait any longer
2811 * than 'delay' or 500 milliseconds, whichever is longer
2814 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2815 struct ast_frame *cur, *new;
2816 int ms = MAX(delay, 500);
2817 unsigned int done = 0;
2819 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2822 ms = ast_waitfor(chan, ms);
2824 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
2829 ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
2832 cur = ast_read(chan);
2833 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2834 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2839 ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
2843 if ((new = ast_frisolate(cur)) != cur) {
2847 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2849 /* if a specific delay period was requested, continue
2850 * until that delay has passed. don't stop just because
2851 * incoming media has arrived.
2857 switch (new->frametype) {
2858 /* all of these frametypes qualify as 'media' */
2859 case AST_FRAME_VOICE:
2860 case AST_FRAME_VIDEO:
2861 case AST_FRAME_TEXT:
2862 case AST_FRAME_DTMF_BEGIN:
2863 case AST_FRAME_DTMF_END:
2864 case AST_FRAME_IMAGE:
2865 case AST_FRAME_HTML:
2866 case AST_FRAME_MODEM:
2869 case AST_FRAME_CONTROL:
2871 case AST_FRAME_NULL:
2882 ast_channel_lock(chan);
2883 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2884 ast_queue_frame_head(chan, cur);
2887 ast_channel_unlock(chan);
2898 int ast_answer(struct ast_channel *chan)
2900 return __ast_answer(chan, 0, 1);
2903 void ast_deactivate_generator(struct ast_channel *chan)
2905 ast_channel_lock(chan);
2906 if (chan->generatordata) {
2907 if (chan->generator && chan->generator->release)
2908 chan->generator->release(chan, chan->generatordata);
2909 chan->generatordata = NULL;
2910 chan->generator = NULL;
2911 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2912 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2913 ast_settimeout(chan, 0, NULL, NULL);
2915 ast_channel_unlock(chan);
2918 static int generator_force(const void *data)
2920 /* Called if generator doesn't have data */
2923 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2924 struct ast_channel *chan = (struct ast_channel *)data;
2926 ast_channel_lock(chan);
2927 tmp = chan->generatordata;
2928 chan->generatordata = NULL;
2929 if (chan->generator)
2930 generate = chan->generator->generate;
2931 ast_channel_unlock(chan);
2933 if (!tmp || !generate)
2936 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
2938 chan->generatordata = tmp;
2941 ast_debug(1, "Auto-deactivating generator\n");
2942 ast_deactivate_generator(chan);
2948 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2952 ast_channel_lock(chan);
2953 if (chan->generatordata) {
2954 if (chan->generator && chan->generator->release)
2955 chan->generator->release(chan, chan->generatordata);
2956 chan->generatordata = NULL;
2958 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2962 ast_settimeout(chan, 50, generator_force, chan);
2963 chan->generator = gen;
2965 ast_channel_unlock(chan);
2972 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2973 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2976 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2980 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2982 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2983 int *exception, int *outfd, int *ms)
2985 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2986 int *exception, int *outfd, int *ms)
2989 struct timeval start = { 0 , 0 };
2990 struct pollfd *pfds = NULL;
2995 struct timeval now = { 0, 0 };
2996 struct timeval whentohangup = { 0, 0 }, diff;
2997 struct ast_channel *winner = NULL;
3003 if ((sz = n * AST_MAX_FDS + nfds)) {
3004 pfds = alloca(sizeof(*pfds) * sz);
3005 fdmap = alloca(sizeof(*fdmap) * sz);
3013 /* Perform any pending masquerades */
3014 for (x = 0; x < n; x++) {
3015 if (c[x]->masq && ast_do_masquerade(c[x])) {
3016 ast_log(LOG_WARNING, "Masquerade failed\n");
3021 ast_channel_lock(c[x]);
3022 if (!ast_tvzero(c[x]->whentohangup)) {
3023 if (ast_tvzero(whentohangup))
3025 diff = ast_tvsub(c[x]->whentohangup, now);
3026 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3027 /* Should already be hungup */
3028 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3029 ast_channel_unlock(c[x]);
3032 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3033 whentohangup = diff;
3035 ast_channel_unlock(c[x]);
3037 /* Wait full interval */
3039 /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3040 if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3041 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
3042 if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
3045 } else if (!ast_tvzero(whentohangup) && rms < 0) {
3046 /* Tiny corner case... call would need to last >24 days */
3050 * Build the pollfd array, putting the channels' fds first,
3051 * followed by individual fds. Order is important because
3052 * individual fd's must have priority over channel fds.
3055 for (x = 0; x < n; x++) {
3056 for (y = 0; y < AST_MAX_FDS; y++) {
3057 fdmap[max].fdno = y; /* fd y is linked to this pfds */
3058 fdmap[max].chan = x; /* channel x is linked to this pfds */
3059 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
3061 CHECK_BLOCKING(c[x]);
3063 /* Add the individual fds */
3064 for (x = 0; x < nfds; x++) {
3065 fdmap[max].chan = -1;
3066 max += ast_add_fd(&pfds[max], fds[x]);
3070 start = ast_tvnow();
3072 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3077 res = ast_poll(pfds, max, kbrms);
3080 } while (!res && (rms > 0));
3082 res = ast_poll(pfds, max, rms);
3084 for (x = 0; x < n; x++)
3085 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
3086 if (res < 0) { /* Simulate a timeout if we were interrupted */
3091 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
3093 for (x = 0; x < n; x++) {
3094 if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
3095 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3101 if (res == 0) { /* no fd ready, reset timeout and done */
3102 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
3106 * Then check if any channel or fd has a pending event.
3107 * Remember to check channels first and fds last, as they
3108 * must have priority on setting 'winner'
3110 for (x = 0; x < max; x++) {
3111 res = pfds[x].revents;
3114 if (fdmap[x].chan >= 0) { /* this is a channel */
3115 winner = c[fdmap[x].chan]; /* override previous winners */
3117 ast_set_flag(winner, AST_FLAG_EXCEPTION);
3119 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3120 winner->fdno = fdmap[x].fdno;
3121 } else { /* this is an fd */
3123 *outfd = pfds[x].fd;
3125 *exception = (res & POLLPRI) ? -1 : 0;
3130 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3138 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3140 struct timeval start = { 0 , 0 };
3142 struct epoll_event ev[1];
3143 long diff, rms = *ms;
3144 struct ast_channel *winner = NULL;
3145 struct ast_epoll_data *aed = NULL;
3148 /* See if this channel needs to be masqueraded */
3149 if (chan->masq && ast_do_masquerade(chan)) {
3150 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
3155 ast_channel_lock(chan);
3156 /* Figure out their timeout */
3157 if (!ast_tvzero(chan->whentohangup)) {
3158 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
3159 /* They should already be hungup! */
3160 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3161 ast_channel_unlock(chan);
3164 /* If this value is smaller then the current one... make it priority */
3169 ast_channel_unlock(chan);
3171 /* Time to make this channel block... */
3172 CHECK_BLOCKING(chan);
3175 start = ast_tvnow();
3177 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3178 res = epoll_wait(chan->epfd, ev, 1, rms);
3181 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3183 /* Simulate a timeout if we were interrupted */
3190 /* If this channel has a timeout see if it expired */
3191 if (!ast_tvzero(chan->whentohangup)) {
3192 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
3193 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3198 /* No fd ready, reset timeout and be done for now */
3204 /* See what events are pending */
3205 aed = ev[0].data.ptr;
3206 chan->fdno = aed->which;
3207 if (ev[0].events & EPOLLPRI)
3208 ast_set_flag(chan, AST_FLAG_EXCEPTION);
3210 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3213 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3221 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3223 struct timeval start = { 0 , 0 };
3225 struct epoll_event ev[25] = { { 0, } };
3226 struct timeval now = { 0, 0 };
3227 long whentohangup = 0, diff = 0, rms = *ms;
3228 struct ast_channel *winner = NULL;
3230 for (i = 0; i < n; i++) {
3231 if (c[i]->masq && ast_do_masquerade(c[i])) {
3232 ast_log(LOG_WARNING, "Masquerade failed\n");
3237 ast_channel_lock(c[i]);
3238 if (!ast_tvzero(c[i]->whentohangup)) {
3239 if (whentohangup == 0)
3241 if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
3242 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3243 ast_channel_unlock(c[i]);
3246 if (!whentohangup || whentohangup > diff)
3247 whentohangup = diff;
3249 ast_channel_unlock(c[i]);
3250 CHECK_BLOCKING(c[i]);
3256 if (*ms >= 0 && *ms < rms)
3261 start = ast_tvnow();
3263 res = epoll_wait(c[0]->epfd, ev, 25, rms);
3265 for (i = 0; i < n; i++)
3266 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
3276 for (i = 0; i < n; i++) {
3277 if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
3278 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3290 for (i = 0; i < res; i++) {
3291 struct ast_epoll_data *aed = ev[i].data.ptr;
3293 if (!ev[i].events || !aed)
3297 if (ev[i].events & EPOLLPRI)
3298 ast_set_flag(winner, AST_FLAG_EXCEPTION);
3300 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3301 winner->fdno = aed->which;
3305 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3313 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3314 int *exception, int *outfd, int *ms)
3316 /* Clear all provided values in one place. */
3322 /* If no epoll file descriptor is available resort to classic nandfds */
3323 if (!n || nfds || c[0]->epfd == -1)
3324 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3325 else if (!nfds && n == 1)
3326 return ast_waitfor_nandfds_simple(c[0], ms);
3328 return ast_waitfor_nandfds_complex(c, n, ms);
3332 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3334 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3337 int ast_waitfor(struct ast_channel *c, int ms)
3339 int oldms = ms; /* -1 if no timeout */
3341 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3342 if ((ms < 0) && (oldms < 0))
3347 /* XXX never to be called with ms = -1 */
3348 int ast_waitfordigit(struct ast_channel *c, int ms)
3350 return ast_waitfordigit_full(c, ms, -1, -1);
3353 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3356 unsigned int real_rate = rate, max_rate;
3358 ast_channel_lock(c);
3360 if (c->timingfd == -1) {
3361 ast_channel_unlock(c);
3370 if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
3371 real_rate = max_rate;
3374 ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3376 res = ast_timer_set_rate(c->timer, real_rate);
3378 c->timingfunc = func;
3379 c->timingdata = data;
3381 ast_channel_unlock(c);
3386 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
3388 /* Stop if we're a zombie or need a soft hangup */
3389 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3392 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3393 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
3395 /* Wait for a digit, no more than ms milliseconds total. */
3398 struct ast_channel *rchan;
3402 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3404 if (!rchan && outfd < 0 && ms) {
3405 if (errno == 0 || errno == EINTR)
3407 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
3408 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3410 } else if (outfd > -1) {
3411 /* The FD we were watching has something waiting */
3412 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
3413 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3417 struct ast_frame *f = ast_read(c);
3421 switch (f->frametype) {
3422 case AST_FRAME_DTMF_BEGIN:
3424 case AST_FRAME_DTMF_END:
3425 res = f->subclass.integer;
3427 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3429 case AST_FRAME_CONTROL:
3430 switch (f->subclass.integer) {
3431 case AST_CONTROL_HANGUP:
3433 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3435 case AST_CONTROL_RINGING:
3436 case AST_CONTROL_ANSWER:
3437 case AST_CONTROL_SRCUPDATE:
3438 case AST_CONTROL_SRCCHANGE:
3439 case AST_CONTROL_CONNECTED_LINE:
3440 case AST_CONTROL_REDIRECTING:
3445 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
3449 case AST_FRAME_VOICE:
3450 /* Write audio if appropriate */
3452 if (write(audiofd, f->data.ptr, f->datalen) < 0) {
3453 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3464 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3466 return 0; /* Time is up */
3469 static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
3471 ast_manager_event(chan, EVENT_FLAG_DTMF,
3479 chan->name, chan->uniqueid, digit, direction, begin, end);
3482 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
3484 if (chan->generator && chan->generator->generate && chan->generatordata && !ast_internal_timing_enabled(chan)) {
3485 void *tmp = chan->generatordata;
3486 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = chan->generator->generate;
3490 if (chan->timingfunc) {
3491 ast_debug(1, "Generator got voice, switching to phase locked mode\n");
3492 ast_settimeout(chan, 0, NULL, NULL);
3495 chan->generatordata = NULL; /* reset, to let writes go through */
3497 if (f->subclass.codec != chan->writeformat) {
3499 factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass.codec));
3500 samples = (int) ( ((float) f->samples) * factor );
3502 samples = f->samples;
3505 /* This unlock is here based on two assumptions that hold true at this point in the
3506 * code. 1) this function is only called from within __ast_read() and 2) all generators
3507 * call ast_write() in their generate callback.
3509 * The reason this is added is so that when ast_write is called, the lock that occurs
3510 * there will not recursively lock the channel. Doing this will cause intended deadlock
3511 * avoidance not to work in deeper functions
3513 ast_channel_unlock(chan);
3514 res = generate(chan, tmp, f->datalen, samples);
3515 ast_channel_lock(chan);
3516 chan->generatordata = tmp;
3518 ast_debug(1, "Auto-deactivating generator\n");
3519 ast_deactivate_generator(chan);
3522 } else if (f->frametype == AST_FRAME_CNG) {
3523 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
3524 ast_debug(1, "Generator got CNG, switching to timed mode\n");
3525 ast_settimeout(chan, 50, generator_force, chan);
3530 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3532 struct ast_frame *fr = &chan->dtmff;
3534 fr->frametype = AST_FRAME_DTMF_END;
3535 fr->subclass.integer = f->subclass.integer;
3538 /* The only time this function will be called is for a frame that just came
3539 * out of the channel driver. So, we want to stick it on the tail of the
3542 ast_queue_frame(chan, fr);
3546 * \brief Determine whether or not we should ignore DTMF in the readq
3548 static inline int should_skip_dtmf(struct ast_channel *chan)
3550 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
3551 /* We're in the middle of emulating a digit, or DTMF has been
3552 * explicitly deferred. Skip this digit, then. */
3556 if (!ast_tvzero(chan->dtmf_tv) &&
3557 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3558 /* We're not in the middle of a digit, but it hasn't been long enough
3559 * since the last digit, so we'll have to skip DTMF for now. */
3567 * \brief calculates the number of samples to jump forward with in a monitor stream.
3569 * \note When using ast_seekstream() with the read and write streams of a monitor,
3570 * the number of samples to seek forward must be of the same sample rate as the stream
3571 * or else the jump will not be calculated correctly.
3573 * \retval number of samples to seek forward after rate conversion.
3575 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
3577 int diff = sample_rate - seek_rate;
3580 samples = samples / (float) (sample_rate / seek_rate);
3581 } else if (diff < 0) {
3582 samples = samples * (float) (seek_rate / sample_rate);
3588 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
3590 struct ast_frame *f = NULL; /* the return value */
3595 /* this function is very long so make sure there is only one return
3596 * point at the end (there are only two exceptions to this).
3600 if (ast_do_masquerade(chan))
3601 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
3603 f = &ast_null_frame;
3607 /* if here, no masq has happened, lock the channel and proceed */
3608 ast_channel_lock(chan);
3610 /* Stop if we're a zombie or need a soft hangup */
3611 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
3612 if (chan->generator)
3613 ast_deactivate_generator(chan);
3619 * The ast_waitfor() code records which of the channel's file descriptors reported that
3620 * data is available. In theory, ast_read() should only be called after ast_waitfor()
3621 * reports that a channel has data available for reading. However, there still may be
3622 * some edge cases throughout the code where ast_read() is called improperly. This can
3623 * potentially cause problems, so if this is a developer build, make a lot of noise if
3624 * this happens so that it can be addressed.
3626 if (chan->fdno == -1) {
3628 "ast_read() on chan '%s' called with no recorded file descriptor.\n",
3633 prestate = chan->_state;
3635 /* Read and ignore anything on the alertpipe, but read only
3636 one sizeof(blah) per frame that we send from it */
3637 if (chan->alertpipe[0] > -1) {
3638 int flags = fcntl(chan->alertpipe[0], F_GETFL);
3639 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
3640 * which immediately causes a deadlock scenario. Detect and prevent this. */
3641 if ((flags & O_NONBLOCK) == 0) {
3642 ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
3643 if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
3644 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
3645 f = &ast_null_frame;
3649 if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
3650 if (errno != EINTR && errno != EAGAIN)
3651 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
3655 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
3656 enum ast_timer_event res;
3658 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3660 res = ast_timer_get_event(chan->timer);
3663 case AST_TIMING_EVENT_EXPIRED:
3664 ast_timer_ack(chan->timer, 1);
3666 if (chan->timingfunc) {
3667 /* save a copy of func/data before unlocking the channel */
3668 int (*func)(const void *) = chan->timingfunc;
3669 void *data = chan->timingdata;
3671 ast_channel_unlock(chan);
3674 ast_timer_set_rate(chan->timer, 0);
3676 ast_channel_unlock(chan);
3679 /* cannot 'goto done' because the channel is already unlocked */
3680 return &ast_null_frame;
3682 case AST_TIMING_EVENT_CONTINUOUS:
3683 if (AST_LIST_EMPTY(&chan->readq) ||
3684 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
3685 ast_timer_disable_continuous(chan->timer);
3690 } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
3691 /* if the AST_GENERATOR_FD is set, call the generator with args
3692 * set to -1 so it can do whatever it needs to.
3694 void *tmp = chan->generatordata;
3695 chan->generatordata = NULL; /* reset to let ast_write get through */
3696 chan->generator->generate(chan, tmp, -1, -1);
3697 chan->generatordata = tmp;
3698 f = &ast_null_frame;
3703 /* Check for pending read queue */
3704 if (!AST_LIST_EMPTY(&chan->readq)) {
3705 int skip_dtmf = should_skip_dtmf(chan);
3707 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
3708 /* We have to be picky about which frame we pull off of the readq because
3709 * there are cases where we want to leave DTMF frames on the queue until
3710 * some later time. */
3712 if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
3716 AST_LIST_REMOVE_CURRENT(frame_list);
3719 AST_LIST_TRAVERSE_SAFE_END;
3722 /* There were no acceptable frames on the readq. */
3723 f = &ast_null_frame;
3724 if (chan->alertpipe[0] > -1) {
3726 /* Restore the state of the alertpipe since we aren't ready for any
3727 * of the frames in the readq. */
3728 if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
3729 ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
3734 /* Interpret hangup and return NULL */
3735 /* XXX why not the same for frames from the channel ? */
3736 if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
3737 cause = f->data.uint32;
3742 chan->blocker = pthread_self();
3743 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
3744 if (chan->tech->exception)
3745 f = chan->tech->exception(chan);
3747 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
3748 f = &ast_null_frame;
3750 /* Clear the exception flag */
3751 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3752 } else if (chan->tech->read)
3753 f = chan->tech->read(chan);
3755 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
3759 * Reset the recorded file descriptor that triggered this read so that we can
3760 * easily detect when ast_read() is called without properly using ast_waitfor().
3764 /* Perform the framehook read event here. After the frame enters the framehook list
3765 * there is no telling what will happen, <insert mad scientist laugh here>!!! */
3766 f = ast_framehook_list_read_event(chan->framehooks, f);
3769 struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
3770 struct ast_control_read_action_payload *read_action_payload;
3771 struct ast_party_connected_line connected;
3773 /* if the channel driver returned more than one frame, stuff the excess
3774 into the readq for the next ast_read call
3776 if (AST_LIST_NEXT(f, frame_list)) {
3777 ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
3778 ast_frfree(AST_LIST_NEXT(f, frame_list));
3779 AST_LIST_NEXT(f, frame_list) = NULL;
3782 switch (f->frametype) {
3783 case AST_FRAME_CONTROL:
3784 if (f->subclass.integer == AST_CONTROL_ANSWER) {
3785 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
3786 ast_debug(1, "Ignoring answer on an inbound call!\n");
3788 f = &ast_null_frame;
3789 } else if (prestate == AST_STATE_UP && ast_bridged_channel(chan)) {
3790 ast_debug(1, "Dropping duplicate answer!\n");
3792 f = &ast_null_frame;
3794 /* Answer the CDR */
3795 ast_setstate(chan, AST_STATE_UP);
3796 /* removed a call to ast_cdr_answer(chan->cdr) from here. */
3797 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
3799 } else if (f->subclass.integer == AST_CONTROL_READ_ACTION) {
3800 read_action_payload = f->data.ptr;
3801 switch (read_action_payload->action) {
3802 case AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO:
3803 ast_party_connected_line_init(&connected);