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())) {
1132 if (strcmp(ast_timer_get_name(tmp->timer), "timerfd")) {
1135 tmp->timingfd = ast_timer_fd(tmp->timer);
1139 if (pipe(tmp->alertpipe)) {
1140 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
1141 return ast_channel_unref(tmp);
1143 flags = fcntl(tmp->alertpipe[0], F_GETFL);
1144 if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
1145 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1146 return ast_channel_unref(tmp);
1148 flags = fcntl(tmp->alertpipe[1], F_GETFL);
1149 if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
1150 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1151 return ast_channel_unref(tmp);
1157 * This is the last place the channel constructor can fail.
1159 * The destructor takes advantage of this fact to ensure that the
1160 * AST_CEL_CHANNEL_END is not posted if we have not posted the
1161 * AST_CEL_CHANNEL_START yet.
1163 if ((ast_string_field_init(tmp, 128))) {
1164 return ast_channel_unref(tmp);
1167 /* Always watch the alertpipe */
1168 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
1169 /* And timing pipe */
1170 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
1173 tmp->_state = state;
1177 tmp->fin = global_fin;
1178 tmp->fout = global_fout;
1180 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1181 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
1182 ast_atomic_fetchadd_int(&uniqueint, 1));
1184 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
1185 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1188 if (!ast_strlen_zero(linkedid)) {
1189 ast_string_field_set(tmp, linkedid, linkedid);
1191 ast_string_field_set(tmp, linkedid, tmp->uniqueid);
1194 if (!ast_strlen_zero(name_fmt)) {
1195 char *slash, *slash2;
1196 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1197 * And they all use slightly different formats for their name string.
1198 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1199 * This means, that the stringfields must have a routine that takes the va_lists directly, and
1200 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1201 * This new function was written so this can be accomplished.
1203 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
1204 tech = ast_strdupa(tmp->name);
1205 if ((slash = strchr(tech, '/'))) {
1206 if ((slash2 = strchr(slash + 1, '/'))) {
1214 * Start the string with '-' so it becomes an empty string
1215 * in the destructor.
1217 ast_string_field_set(tmp, name, "-**Unknown**");
1220 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1222 /* These 4 variables need to be set up for the cdr_init() to work right */
1224 tmp->amaflags = amaflag;
1226 tmp->amaflags = ast_default_amaflags;
1228 if (!ast_strlen_zero(acctcode))
1229 ast_string_field_set(tmp, accountcode, acctcode);
1231 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
1233 if (!ast_strlen_zero(context))
1234 ast_copy_string(tmp->context, context, sizeof(tmp->context));
1236 strcpy(tmp->context, "default");
1238 if (!ast_strlen_zero(exten))
1239 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
1241 strcpy(tmp->exten, "s");
1245 tmp->cdr = ast_cdr_alloc();
1246 ast_cdr_init(tmp->cdr, tmp);
1247 ast_cdr_start(tmp->cdr);
1249 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1251 headp = &tmp->varshead;
1252 AST_LIST_HEAD_INIT_NOLOCK(headp);
1254 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
1256 AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
1258 ast_string_field_set(tmp, language, defaultlanguage);
1260 tmp->tech = &null_tech;
1262 ao2_link(channels, tmp);
1265 * And now, since the channel structure is built, and has its name, let's
1266 * call the manager event generator with this Newchannel event. This is the
1267 * proper and correct place to make this call, but you sure do have to pass
1268 * a lot of data into this func to do it here!
1270 if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1271 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1273 "ChannelState: %d\r\n"
1274 "ChannelStateDesc: %s\r\n"
1275 "CallerIDNum: %s\r\n"
1276 "CallerIDName: %s\r\n"
1277 "AccountCode: %s\r\n"
1283 ast_state2str(state),
1295 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1296 const char *cid_name, const char *acctcode,
1297 const char *exten, const char *context,
1298 const char *linkedid, const int amaflag,
1299 const char *file, int line, const char *function,
1300 const char *name_fmt, ...)
1303 struct ast_channel *result;
1305 va_start(ap1, name_fmt);
1306 va_start(ap2, name_fmt);
1307 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1308 linkedid, amaflag, file, line, function, name_fmt, ap1, ap2);
1315 /* only do the minimum amount of work needed here to make a channel
1316 * structure that can be used to expand channel vars */
1317 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1318 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1320 struct ast_channel *ast_dummy_channel_alloc(void)
1323 struct ast_channel *tmp;
1324 struct varshead *headp;
1326 #if defined(REF_DEBUG)
1327 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1328 file, line, function, 1);
1329 #elif defined(__AST_DEBUG_MALLOC)
1330 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1331 file, line, function, 0);
1333 tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor);
1336 /* Dummy channel structure allocation failure. */
1340 if ((ast_string_field_init(tmp, 128))) {
1341 return ast_channel_unref(tmp);
1344 headp = &tmp->varshead;
1345 AST_LIST_HEAD_INIT_NOLOCK(headp);
1350 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1352 struct ast_frame *f;
1353 struct ast_frame *cur;
1355 unsigned int new_frames = 0;
1356 unsigned int new_voice_frames = 0;
1357 unsigned int queued_frames = 0;
1358 unsigned int queued_voice_frames = 0;
1359 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1361 ast_channel_lock(chan);
1364 * Check the last frame on the queue if we are queuing the new
1367 cur = AST_LIST_LAST(&chan->readq);
1368 if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1369 switch (cur->subclass.integer) {
1370 case AST_CONTROL_END_OF_Q:
1371 if (fin->frametype == AST_FRAME_CONTROL
1372 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1374 * Destroy the end-of-Q marker frame so we can queue the hangup
1375 * frame in its place.
1377 AST_LIST_REMOVE(&chan->readq, cur, frame_list);
1381 * This has degenerated to a normal queue append anyway. Since
1382 * we just destroyed the last frame in the queue we must make
1383 * sure that "after" is NULL or bad things will happen.
1389 case AST_CONTROL_HANGUP:
1390 /* Don't queue anything. */
1391 ast_channel_unlock(chan);
1398 /* Build copies of all the new frames and count them */
1399 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1400 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1401 if (!(f = ast_frdup(cur))) {
1402 if (AST_LIST_FIRST(&frames)) {
1403 ast_frfree(AST_LIST_FIRST(&frames));
1405 ast_channel_unlock(chan);
1409 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1411 if (f->frametype == AST_FRAME_VOICE) {
1416 /* Count how many frames exist on the queue */
1417 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1419 if (cur->frametype == AST_FRAME_VOICE) {
1420 queued_voice_frames++;
1424 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1426 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", chan->name);
1427 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
1428 /* Save the most recent frame */
1429 if (!AST_LIST_NEXT(cur, frame_list)) {
1431 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1435 AST_LIST_REMOVE_CURRENT(frame_list);
1439 AST_LIST_TRAVERSE_SAFE_END;
1443 AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1446 AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1447 AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1449 AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1452 if (chan->alertpipe[1] > -1) {
1453 if (write(chan->alertpipe[1], &blah, new_frames * sizeof(blah)) != (new_frames * sizeof(blah))) {
1454 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1455 chan->name, queued_frames, strerror(errno));
1457 } else if (chan->timingfd > -1) {
1458 ast_timer_enable_continuous(chan->timer);
1459 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1460 pthread_kill(chan->blocker, SIGURG);
1463 ast_channel_unlock(chan);
1468 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1470 return __ast_queue_frame(chan, fin, 0, NULL);
1473 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1475 return __ast_queue_frame(chan, fin, 1, NULL);
1478 /*! \brief Queue a hangup frame for channel */
1479 int ast_queue_hangup(struct ast_channel *chan)
1481 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1482 /* Yeah, let's not change a lock-critical value without locking */
1483 if (!ast_channel_trylock(chan)) {
1484 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1485 ast_channel_unlock(chan);
1487 return ast_queue_frame(chan, &f);
1490 /*! \brief Queue a hangup frame for channel */
1491 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1493 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1496 f.data.uint32 = cause;
1498 /* Yeah, let's not change a lock-critical value without locking */
1499 if (!ast_channel_trylock(chan)) {
1500 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1502 f.data.uint32 = chan->hangupcause;
1504 ast_channel_unlock(chan);
1507 return ast_queue_frame(chan, &f);
1510 /*! \brief Queue a control frame */
1511 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1513 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1514 return ast_queue_frame(chan, &f);
1517 /*! \brief Queue a control frame with payload */
1518 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1519 const void *data, size_t datalen)
1521 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1522 return ast_queue_frame(chan, &f);
1525 /*! \brief Set defer DTMF flag on channel */
1526 int ast_channel_defer_dtmf(struct ast_channel *chan)
1531 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1532 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1537 /*! \brief Unset defer DTMF flag on channel */
1538 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1541 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1544 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1545 void *data, int ao2_flags)
1547 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1550 struct ast_channel_iterator {
1551 /* storage for non-dynamically allocated iterator */
1552 struct ao2_iterator simple_iterator;
1553 /* pointer to the actual iterator (simple_iterator or a dynamically
1554 * allocated iterator)
1556 struct ao2_iterator *active_iterator;
1559 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1561 ao2_iterator_destroy(i->active_iterator);
1567 static struct ast_channel_iterator *channel_iterator_search(const char *name,
1568 size_t name_len, const char *exten,
1569 const char *context)
1571 struct ast_channel_iterator *i;
1572 struct ast_channel tmp_chan = {
1574 /* This is sort of a hack. Basically, we're using an arbitrary field
1575 * in ast_channel to pass the name_len for a prefix match. If this
1576 * gets changed, then the compare callback must be changed, too. */
1580 if (!(i = ast_calloc(1, sizeof(*i)))) {
1585 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1589 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1592 if (!(i->active_iterator = ao2_find(channels, &tmp_chan,
1593 OBJ_MULTIPLE | ((!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0)))) {
1601 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1603 return channel_iterator_search(NULL, 0, exten, context);
1606 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1608 return channel_iterator_search(name, name_len, NULL, NULL);
1611 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1613 struct ast_channel_iterator *i;
1615 if (!(i = ast_calloc(1, sizeof(*i)))) {
1619 i->simple_iterator = ao2_iterator_init(channels, 0);
1620 i->active_iterator = &i->simple_iterator;
1625 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1627 return ao2_iterator_next(i->active_iterator);
1630 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1632 struct ast_channel *chan = obj, *cmp_args = arg;
1634 int ret = CMP_MATCH;
1636 /* This is sort of a hack. Basically, we're using an arbitrary field
1637 * in ast_channel to pass the name_len for a prefix match. If this
1638 * gets changed, then the uses of ao2_find() must be changed, too. */
1639 name_len = cmp_args->rings;
1641 ast_channel_lock(chan);
1643 if (!ast_strlen_zero(cmp_args->name)) { /* match by name */
1644 if ((!name_len && strcasecmp(chan->name, cmp_args->name)) ||
1645 (name_len && strncasecmp(chan->name, cmp_args->name, name_len))) {
1646 ret = 0; /* name match failed */
1648 } else if (!ast_strlen_zero(cmp_args->exten)) {
1649 if (cmp_args->context && strcasecmp(chan->context, cmp_args->context) &&
1650 strcasecmp(chan->macrocontext, cmp_args->context)) {
1651 ret = 0; /* context match failed */
1653 if (ret && strcasecmp(chan->exten, cmp_args->exten) &&
1654 strcasecmp(chan->macroexten, cmp_args->exten)) {
1655 ret = 0; /* exten match failed */
1657 } else if (!ast_strlen_zero(cmp_args->uniqueid)) {
1658 if ((!name_len && strcasecmp(chan->uniqueid, cmp_args->uniqueid)) ||
1659 (name_len && strncasecmp(chan->uniqueid, cmp_args->uniqueid, name_len))) {
1660 ret = 0; /* uniqueid match failed */
1666 ast_channel_unlock(chan);
1671 static struct ast_channel *ast_channel_get_full(const char *name, size_t name_len,
1672 const char *exten, const char *context)
1674 struct ast_channel tmp_chan = {
1676 /* This is sort of a hack. Basically, we're using an arbitrary field
1677 * in ast_channel to pass the name_len for a prefix match. If this
1678 * gets changed, then the compare callback must be changed, too. */
1681 struct ast_channel *chan;
1684 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1688 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1691 if ((chan = ao2_find(channels, &tmp_chan,
1692 (!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0))) {
1700 /* If name was specified, but the result was NULL,
1701 * try a search on uniqueid, instead. */
1704 struct ast_channel tmp_chan2 = {
1709 return ao2_find(channels, &tmp_chan2, 0);
1713 struct ast_channel *ast_channel_get_by_name(const char *name)
1715 return ast_channel_get_full(name, 0, NULL, NULL);
1718 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1720 return ast_channel_get_full(name, name_len, NULL, NULL);
1723 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1725 return ast_channel_get_full(NULL, 0, exten, context);
1728 int ast_is_deferrable_frame(const struct ast_frame *frame)
1730 /* Do not add a default entry in this switch statement. Each new
1731 * frame type should be addressed directly as to whether it should
1732 * be queued up or not.
1734 switch (frame->frametype) {
1735 case AST_FRAME_DTMF_END:
1736 case AST_FRAME_CONTROL:
1737 case AST_FRAME_TEXT:
1738 case AST_FRAME_IMAGE:
1739 case AST_FRAME_HTML:
1742 case AST_FRAME_DTMF_BEGIN:
1743 case AST_FRAME_VOICE:
1744 case AST_FRAME_VIDEO:
1745 case AST_FRAME_NULL:
1748 case AST_FRAME_MODEM:
1754 /*! \brief Wait, look for hangups and condition arg */
1755 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1757 struct ast_frame *f;
1758 struct ast_silence_generator *silgen = NULL;
1760 AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1762 AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1764 /* If no other generator is present, start silencegen while waiting */
1765 if (ast_opt_transmit_silence && !chan->generatordata) {
1766 silgen = ast_channel_start_silence_generator(chan);
1770 struct ast_frame *dup_f = NULL;
1771 if (cond && ((*cond)(data) == 0)) {
1774 ms = ast_waitfor(chan, ms);
1786 if (!ast_is_deferrable_frame(f)) {
1791 if ((dup_f = ast_frisolate(f))) {
1795 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1800 /* stop silgen if present */
1802 ast_channel_stop_silence_generator(chan, silgen);
1805 /* We need to free all the deferred frames, but we only need to
1806 * queue the deferred frames if there was no error and no
1807 * hangup was received
1809 ast_channel_lock(chan);
1810 while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1812 ast_queue_frame_head(chan, f);
1816 ast_channel_unlock(chan);
1821 /*! \brief Wait, look for hangups */
1822 int ast_safe_sleep(struct ast_channel *chan, int ms)
1824 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1827 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1829 /* Safe, even if already unlinked. */
1830 ao2_unlink(channels, chan);
1831 return ast_channel_unref(chan);
1834 void ast_party_name_init(struct ast_party_name *init)
1837 init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1838 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1842 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1845 /* Don't copy to self */
1849 ast_free(dest->str);
1850 dest->str = ast_strdup(src->str);
1851 dest->char_set = src->char_set;
1852 dest->presentation = src->presentation;
1853 dest->valid = src->valid;
1856 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1859 init->char_set = guide->char_set;
1860 init->presentation = guide->presentation;
1861 init->valid = guide->valid;
1864 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1867 /* Don't set to self */
1871 if (src->str && src->str != dest->str) {
1872 ast_free(dest->str);
1873 dest->str = ast_strdup(src->str);
1876 dest->char_set = src->char_set;
1877 dest->presentation = src->presentation;
1878 dest->valid = src->valid;
1881 void ast_party_name_free(struct ast_party_name *doomed)
1883 ast_free(doomed->str);
1887 void ast_party_number_init(struct ast_party_number *init)
1890 init->plan = 0;/* Unknown */
1891 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1895 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1898 /* Don't copy to self */
1902 ast_free(dest->str);
1903 dest->str = ast_strdup(src->str);
1904 dest->plan = src->plan;
1905 dest->presentation = src->presentation;
1906 dest->valid = src->valid;
1909 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1912 init->plan = guide->plan;
1913 init->presentation = guide->presentation;
1914 init->valid = guide->valid;
1917 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1920 /* Don't set to self */
1924 if (src->str && src->str != dest->str) {
1925 ast_free(dest->str);
1926 dest->str = ast_strdup(src->str);
1929 dest->plan = src->plan;
1930 dest->presentation = src->presentation;
1931 dest->valid = src->valid;
1934 void ast_party_number_free(struct ast_party_number *doomed)
1936 ast_free(doomed->str);
1940 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1944 init->odd_even_indicator = 0;
1948 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1951 /* Don't copy to self */
1955 ast_free(dest->str);
1956 dest->str = ast_strdup(src->str);
1957 dest->type = src->type;
1958 dest->odd_even_indicator = src->odd_even_indicator;
1959 dest->valid = src->valid;
1962 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1965 init->type = guide->type;
1966 init->odd_even_indicator = guide->odd_even_indicator;
1967 init->valid = guide->valid;
1970 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1973 /* Don't set to self */
1977 if (src->str && src->str != dest->str) {
1978 ast_free(dest->str);
1979 dest->str = ast_strdup(src->str);
1982 dest->type = src->type;
1983 dest->odd_even_indicator = src->odd_even_indicator;
1984 dest->valid = src->valid;
1987 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1989 ast_free(doomed->str);
1993 void ast_party_id_init(struct ast_party_id *init)
1995 ast_party_name_init(&init->name);
1996 ast_party_number_init(&init->number);
1997 ast_party_subaddress_init(&init->subaddress);
2001 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
2004 /* Don't copy to self */
2008 ast_party_name_copy(&dest->name, &src->name);
2009 ast_party_number_copy(&dest->number, &src->number);
2010 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2012 ast_free(dest->tag);
2013 dest->tag = ast_strdup(src->tag);
2016 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
2018 ast_party_name_set_init(&init->name, &guide->name);
2019 ast_party_number_set_init(&init->number, &guide->number);
2020 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2024 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
2027 /* Don't set to self */
2031 if (!update || update->name) {
2032 ast_party_name_set(&dest->name, &src->name);
2034 if (!update || update->number) {
2035 ast_party_number_set(&dest->number, &src->number);
2037 if (!update || update->subaddress) {
2038 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2041 if (src->tag && src->tag != dest->tag) {
2042 ast_free(dest->tag);
2043 dest->tag = ast_strdup(src->tag);
2047 void ast_party_id_free(struct ast_party_id *doomed)
2049 ast_party_name_free(&doomed->name);
2050 ast_party_number_free(&doomed->number);
2051 ast_party_subaddress_free(&doomed->subaddress);
2053 ast_free(doomed->tag);
2057 int ast_party_id_presentation(const struct ast_party_id *id)
2059 int number_priority;
2061 int number_screening;
2065 /* Determine name presentation priority. */
2066 if (!id->name.valid) {
2067 name_value = AST_PRES_UNAVAILABLE;
2070 name_value = id->name.presentation & AST_PRES_RESTRICTION;
2071 switch (name_value) {
2072 case AST_PRES_RESTRICTED:
2075 case AST_PRES_ALLOWED:
2078 case AST_PRES_UNAVAILABLE:
2082 name_value = AST_PRES_UNAVAILABLE;
2088 /* Determine number presentation priority. */
2089 if (!id->number.valid) {
2090 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2091 number_value = AST_PRES_UNAVAILABLE;
2092 number_priority = 3;
2094 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
2095 number_value = id->number.presentation & AST_PRES_RESTRICTION;
2096 switch (number_value) {
2097 case AST_PRES_RESTRICTED:
2098 number_priority = 0;
2100 case AST_PRES_ALLOWED:
2101 number_priority = 1;
2103 case AST_PRES_UNAVAILABLE:
2104 number_priority = 2;
2107 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2108 number_value = AST_PRES_UNAVAILABLE;
2109 number_priority = 3;
2114 /* Select the wining presentation value. */
2115 if (name_priority < number_priority) {
2116 number_value = name_value;
2119 return number_value | number_screening;
2122 void ast_party_dialed_init(struct ast_party_dialed *init)
2124 init->number.str = NULL;
2125 init->number.plan = 0;/* Unknown */
2126 ast_party_subaddress_init(&init->subaddress);
2127 init->transit_network_select = 0;
2130 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2133 /* Don't copy to self */
2137 ast_free(dest->number.str);
2138 dest->number.str = ast_strdup(src->number.str);
2139 dest->number.plan = src->number.plan;
2140 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2141 dest->transit_network_select = src->transit_network_select;
2144 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2146 init->number.str = NULL;
2147 init->number.plan = guide->number.plan;
2148 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2149 init->transit_network_select = guide->transit_network_select;
2152 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2154 if (src->number.str && src->number.str != dest->number.str) {
2155 ast_free(dest->number.str);
2156 dest->number.str = ast_strdup(src->number.str);
2158 dest->number.plan = src->number.plan;
2160 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2162 dest->transit_network_select = src->transit_network_select;
2165 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2167 ast_free(doomed->number.str);
2168 doomed->number.str = NULL;
2169 ast_party_subaddress_free(&doomed->subaddress);
2172 void ast_party_caller_init(struct ast_party_caller *init)
2174 ast_party_id_init(&init->id);
2175 ast_party_id_init(&init->ani);
2179 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2182 /* Don't copy to self */
2186 ast_party_id_copy(&dest->id, &src->id);
2187 ast_party_id_copy(&dest->ani, &src->ani);
2188 dest->ani2 = src->ani2;
2191 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2193 ast_party_id_set_init(&init->id, &guide->id);
2194 ast_party_id_set_init(&init->ani, &guide->ani);
2195 init->ani2 = guide->ani2;
2198 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2200 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2201 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2202 dest->ani2 = src->ani2;
2205 void ast_party_caller_free(struct ast_party_caller *doomed)
2207 ast_party_id_free(&doomed->id);
2208 ast_party_id_free(&doomed->ani);
2211 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2213 ast_party_id_init(&init->id);
2214 ast_party_id_init(&init->ani);
2216 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2219 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2222 /* Don't copy to self */
2226 ast_party_id_copy(&dest->id, &src->id);
2227 ast_party_id_copy(&dest->ani, &src->ani);
2228 dest->ani2 = src->ani2;
2229 dest->source = src->source;
2232 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2234 ast_party_id_set_init(&init->id, &guide->id);
2235 ast_party_id_set_init(&init->ani, &guide->ani);
2236 init->ani2 = guide->ani2;
2237 init->source = guide->source;
2240 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)
2242 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2243 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2244 dest->ani2 = src->ani2;
2245 dest->source = src->source;
2248 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2250 connected->id = caller->id;
2251 connected->ani = caller->ani;
2252 connected->ani2 = caller->ani2;
2253 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2256 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2258 ast_party_id_free(&doomed->id);
2259 ast_party_id_free(&doomed->ani);
2262 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2264 ast_party_id_init(&init->from);
2265 ast_party_id_init(&init->to);
2267 init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2270 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2273 /* Don't copy to self */
2277 ast_party_id_copy(&dest->from, &src->from);
2278 ast_party_id_copy(&dest->to, &src->to);
2279 dest->count = src->count;
2280 dest->reason = src->reason;
2283 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2285 ast_party_id_set_init(&init->from, &guide->from);
2286 ast_party_id_set_init(&init->to, &guide->to);
2287 init->count = guide->count;
2288 init->reason = guide->reason;
2291 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2293 ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2294 ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2295 dest->reason = src->reason;
2296 dest->count = src->count;
2299 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2301 ast_party_id_free(&doomed->from);
2302 ast_party_id_free(&doomed->to);
2305 /*! \brief Free a channel structure */
2306 static void ast_channel_destructor(void *obj)
2308 struct ast_channel *chan = obj;
2313 struct ast_var_t *vardata;
2314 struct ast_frame *f;
2315 struct varshead *headp;
2316 struct ast_datastore *datastore;
2317 char device_name[AST_CHANNEL_NAME];
2320 /* The string fields were initialized. */
2321 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2322 ast_cel_check_retire_linkedid(chan);
2325 /* Get rid of each of the data stores on the channel */
2326 ast_channel_lock(chan);
2327 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
2328 /* Free the data store */
2329 ast_datastore_free(datastore);
2330 ast_channel_unlock(chan);
2332 /* Lock and unlock the channel just to be sure nobody has it locked still
2333 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2334 ast_channel_lock(chan);
2335 ast_channel_unlock(chan);
2337 if (chan->tech_pvt) {
2338 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
2339 ast_free(chan->tech_pvt);
2343 sched_context_destroy(chan->sched);
2348 /* The string fields were initialized. */
2349 ast_copy_string(device_name, chan->name, sizeof(device_name));
2350 if ((dashptr = strrchr(device_name, '-'))) {
2354 device_name[0] = '\0';
2357 /* Stop monitoring */
2359 chan->monitor->stop( chan, 0 );
2361 /* If there is native format music-on-hold state, free it */
2362 if (chan->music_state)
2363 ast_moh_cleanup(chan);
2365 /* Free translators */
2366 if (chan->readtrans)
2367 ast_translator_free_path(chan->readtrans);
2368 if (chan->writetrans)
2369 ast_translator_free_path(chan->writetrans);
2371 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
2373 ast_party_dialed_free(&chan->dialed);
2374 ast_party_caller_free(&chan->caller);
2375 ast_party_connected_line_free(&chan->connected);
2376 ast_party_redirecting_free(&chan->redirecting);
2378 /* Close pipes if appropriate */
2379 if ((fd = chan->alertpipe[0]) > -1)
2381 if ((fd = chan->alertpipe[1]) > -1)
2384 ast_timer_close(chan->timer);
2387 for (i = 0; i < AST_MAX_FDS; i++) {
2388 if (chan->epfd_data[i])
2389 free(chan->epfd_data[i]);
2393 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
2396 /* loop over the variables list, freeing all data and deleting list items */
2397 /* no need to lock the list, as the channel is already locked */
2398 headp = &chan->varshead;
2399 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2400 ast_var_delete(vardata);
2402 ast_app_group_discard(chan);
2404 /* Destroy the jitterbuffer */
2405 ast_jb_destroy(chan);
2408 ast_cdr_discard(chan->cdr);
2413 chan->zone = ast_tone_zone_unref(chan->zone);
2416 ast_string_field_free_memory(chan);
2418 if (device_name[0]) {
2420 * We have a device name to notify of a new state.
2422 * Queue an unknown state, because, while we know that this particular
2423 * instance is dead, we don't know the state of all other possible
2426 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2430 /*! \brief Free a dummy channel structure */
2431 static void ast_dummy_channel_destructor(void *obj)
2433 struct ast_channel *chan = obj;
2434 struct ast_var_t *vardata;
2435 struct varshead *headp;
2437 headp = &chan->varshead;
2439 ast_party_dialed_free(&chan->dialed);
2440 ast_party_caller_free(&chan->caller);
2441 ast_party_connected_line_free(&chan->connected);
2442 ast_party_redirecting_free(&chan->redirecting);
2444 /* loop over the variables list, freeing all data and deleting list items */
2445 /* no need to lock the list, as the channel is already locked */
2446 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2447 ast_var_delete(vardata);
2450 ast_cdr_discard(chan->cdr);
2454 ast_string_field_free_memory(chan);
2457 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2459 return ast_datastore_alloc(info, uid);
2462 int ast_channel_datastore_free(struct ast_datastore *datastore)
2464 return ast_datastore_free(datastore);
2467 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2469 struct ast_datastore *datastore = NULL, *datastore2;
2471 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
2472 if (datastore->inheritance > 0) {
2473 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2475 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2476 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2477 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
2484 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2488 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
2493 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2495 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
2498 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2500 struct ast_datastore *datastore = NULL;
2505 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
2506 if (datastore->info != info) {
2511 /* matched by type only */
2515 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2516 /* Matched by type AND uid */
2520 AST_LIST_TRAVERSE_SAFE_END;
2525 /*! Set the file descriptor on the channel */
2526 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2529 struct epoll_event ev;
2530 struct ast_epoll_data *aed = NULL;
2532 if (chan->fds[which] > -1) {
2533 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2534 aed = chan->epfd_data[which];
2537 /* If this new fd is valid, add it to the epoll */
2539 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2542 chan->epfd_data[which] = aed;
2546 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2548 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2550 /* We don't have to keep around this epoll data structure now */
2552 chan->epfd_data[which] = NULL;
2555 chan->fds[which] = fd;
2559 /*! Add a channel to an optimized waitfor */
2560 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2563 struct epoll_event ev;
2566 if (chan0->epfd == -1)
2569 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2570 for (i = 0; i < AST_MAX_FDS; i++) {
2571 if (chan1->fds[i] == -1)
2573 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2574 ev.data.ptr = chan1->epfd_data[i];
2575 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2582 /*! Delete a channel from an optimized waitfor */
2583 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2586 struct epoll_event ev;
2589 if (chan0->epfd == -1)
2592 for (i = 0; i < AST_MAX_FDS; i++) {
2593 if (chan1->fds[i] == -1)
2595 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2602 /*! \brief Softly hangup a channel, don't lock */
2603 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2605 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
2606 /* Inform channel driver that we need to be hung up, if it cares */
2607 chan->_softhangup |= cause;
2608 ast_queue_frame(chan, &ast_null_frame);
2609 /* Interrupt any poll call or such */
2610 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2611 pthread_kill(chan->blocker, SIGURG);
2615 /*! \brief Softly hangup a channel, lock */
2616 int ast_softhangup(struct ast_channel *chan, int cause)
2620 ast_channel_lock(chan);
2621 res = ast_softhangup_nolock(chan, cause);
2622 ast_channel_unlock(chan);
2627 static void free_translation(struct ast_channel *clonechan)
2629 if (clonechan->writetrans)
2630 ast_translator_free_path(clonechan->writetrans);
2631 if (clonechan->readtrans)
2632 ast_translator_free_path(clonechan->readtrans);
2633 clonechan->writetrans = NULL;
2634 clonechan->readtrans = NULL;
2635 clonechan->rawwriteformat = clonechan->nativeformats;
2636 clonechan->rawreadformat = clonechan->nativeformats;
2639 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2641 struct ast_channel *bridge;
2643 ast_channel_lock(chan);
2644 if (force || ast_strlen_zero(chan->hangupsource)) {
2645 ast_string_field_set(chan, hangupsource, source);
2647 bridge = ast_bridged_channel(chan);
2648 ast_channel_unlock(chan);
2650 if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
2651 ast_channel_lock(bridge);
2652 ast_string_field_set(chan, hangupsource, source);
2653 ast_channel_unlock(bridge);
2657 /*! \brief Hangup a channel */
2658 int ast_hangup(struct ast_channel *chan)
2661 char extra_str[64]; /* used for cel logging below */
2663 /* Don't actually hang up a channel that will masquerade as someone else, or
2664 if someone is going to masquerade as us */
2665 ast_channel_lock(chan);
2667 if (chan->audiohooks) {
2668 ast_audiohook_detach_list(chan->audiohooks);
2669 chan->audiohooks = NULL;
2672 ast_framehook_list_destroy(chan);
2674 ast_autoservice_stop(chan);
2677 ast_channel_unlock(chan);
2678 if (ast_do_masquerade(chan)) {
2679 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2681 ast_channel_lock(chan);
2685 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
2686 ast_channel_unlock(chan);
2689 /* If this channel is one which will be masqueraded into something,
2690 mark it as a zombie already, so we know to free it later */
2692 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2693 ast_channel_unlock(chan);
2696 ast_channel_unlock(chan);
2698 ao2_unlink(channels, chan);
2700 ast_channel_lock(chan);
2701 free_translation(chan);
2702 /* Close audio stream */
2704 ast_closestream(chan->stream);
2705 chan->stream = NULL;
2707 /* Close video stream */
2708 if (chan->vstream) {
2709 ast_closestream(chan->vstream);
2710 chan->vstream = NULL;
2713 sched_context_destroy(chan->sched);
2717 if (chan->generatordata) /* Clear any tone stuff remaining */
2718 if (chan->generator && chan->generator->release)
2719 chan->generator->release(chan, chan->generatordata);
2720 chan->generatordata = NULL;
2721 chan->generator = NULL;
2723 snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2724 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2726 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2727 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2728 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2729 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
2730 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2732 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
2733 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
2734 if (chan->tech->hangup)
2735 res = chan->tech->hangup(chan);
2737 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
2740 ast_channel_unlock(chan);
2742 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2745 "CallerIDNum: %s\r\n"
2746 "CallerIDName: %s\r\n"
2748 "Cause-txt: %s\r\n",
2751 S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<unknown>"),
2752 S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, "<unknown>"),
2754 ast_cause2str(chan->hangupcause)
2757 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
2758 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
2759 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2760 ast_channel_lock(chan);
2762 ast_cdr_end(chan->cdr);
2763 ast_cdr_detach(chan->cdr);
2765 ast_channel_unlock(chan);
2768 chan = ast_channel_release(chan);
2773 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2777 ast_channel_lock(chan);
2779 /* You can't answer an outbound call */
2780 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2781 ast_channel_unlock(chan);
2785 /* Stop if we're a zombie or need a soft hangup */
2786 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2787 ast_channel_unlock(chan);
2791 ast_channel_unlock(chan);
2793 switch (chan->_state) {
2794 case AST_STATE_RINGING:
2795 case AST_STATE_RING:
2796 ast_channel_lock(chan);
2797 if (chan->tech->answer) {
2798 res = chan->tech->answer(chan);
2800 ast_setstate(chan, AST_STATE_UP);
2802 ast_cdr_answer(chan->cdr);
2804 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2805 ast_channel_unlock(chan);
2808 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2809 /* Calling ast_cdr_answer when it it has previously been called
2810 * is essentially a no-op, so it is safe.
2813 ast_cdr_answer(chan->cdr);
2820 ast_indicate(chan, -1);
2825 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2828 enum ast_channel_state old_state;
2830 old_state = chan->_state;
2831 if ((res = ast_raw_answer(chan, cdr_answer))) {
2835 switch (old_state) {
2836 case AST_STATE_RINGING:
2837 case AST_STATE_RING:
2838 /* wait for media to start flowing, but don't wait any longer
2839 * than 'delay' or 500 milliseconds, whichever is longer
2842 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2843 struct ast_frame *cur, *new;
2844 int ms = MAX(delay, 500);
2845 unsigned int done = 0;
2847 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2850 ms = ast_waitfor(chan, ms);
2852 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
2857 ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
2860 cur = ast_read(chan);
2861 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2862 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2867 ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
2871 if ((new = ast_frisolate(cur)) != cur) {
2875 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2877 /* if a specific delay period was requested, continue
2878 * until that delay has passed. don't stop just because
2879 * incoming media has arrived.
2885 switch (new->frametype) {
2886 /* all of these frametypes qualify as 'media' */
2887 case AST_FRAME_VOICE:
2888 case AST_FRAME_VIDEO:
2889 case AST_FRAME_TEXT:
2890 case AST_FRAME_DTMF_BEGIN:
2891 case AST_FRAME_DTMF_END:
2892 case AST_FRAME_IMAGE:
2893 case AST_FRAME_HTML:
2894 case AST_FRAME_MODEM:
2897 case AST_FRAME_CONTROL:
2899 case AST_FRAME_NULL:
2910 ast_channel_lock(chan);
2911 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2912 ast_queue_frame_head(chan, cur);
2915 ast_channel_unlock(chan);
2926 int ast_answer(struct ast_channel *chan)
2928 return __ast_answer(chan, 0, 1);
2931 void ast_deactivate_generator(struct ast_channel *chan)
2933 ast_channel_lock(chan);
2934 if (chan->generatordata) {
2935 if (chan->generator && chan->generator->release)
2936 chan->generator->release(chan, chan->generatordata);
2937 chan->generatordata = NULL;
2938 chan->generator = NULL;
2939 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2940 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2941 ast_settimeout(chan, 0, NULL, NULL);
2943 ast_channel_unlock(chan);
2946 static int generator_force(const void *data)
2948 /* Called if generator doesn't have data */
2951 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2952 struct ast_channel *chan = (struct ast_channel *)data;
2954 ast_channel_lock(chan);
2955 tmp = chan->generatordata;
2956 chan->generatordata = NULL;
2957 if (chan->generator)
2958 generate = chan->generator->generate;
2959 ast_channel_unlock(chan);
2961 if (!tmp || !generate)
2964 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
2966 chan->generatordata = tmp;
2969 ast_debug(1, "Auto-deactivating generator\n");
2970 ast_deactivate_generator(chan);
2976 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2980 ast_channel_lock(chan);
2981 if (chan->generatordata) {
2982 if (chan->generator && chan->generator->release)
2983 chan->generator->release(chan, chan->generatordata);
2984 chan->generatordata = NULL;
2986 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2990 ast_settimeout(chan, 50, generator_force, chan);
2991 chan->generator = gen;
2993 ast_channel_unlock(chan);
3000 /*! \brief Wait for x amount of time on a file descriptor to have input. */
3001 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
3004 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
3008 /*! \brief Wait for x amount of time on a file descriptor to have input. */
3010 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
3011 int *exception, int *outfd, int *ms)
3013 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3014 int *exception, int *outfd, int *ms)
3017 struct timeval start = { 0 , 0 };
3018 struct pollfd *pfds = NULL;
3023 struct timeval now = { 0, 0 };
3024 struct timeval whentohangup = { 0, 0 }, diff;
3025 struct ast_channel *winner = NULL;
3031 if ((sz = n * AST_MAX_FDS + nfds)) {
3032 pfds = alloca(sizeof(*pfds) * sz);
3033 fdmap = alloca(sizeof(*fdmap) * sz);
3041 /* Perform any pending masquerades */
3042 for (x = 0; x < n; x++) {
3043 if (c[x]->masq && ast_do_masquerade(c[x])) {
3044 ast_log(LOG_WARNING, "Masquerade failed\n");
3049 ast_channel_lock(c[x]);
3050 if (!ast_tvzero(c[x]->whentohangup)) {
3051 if (ast_tvzero(whentohangup))
3053 diff = ast_tvsub(c[x]->whentohangup, now);
3054 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3055 /* Should already be hungup */
3056 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3057 ast_channel_unlock(c[x]);
3060 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3061 whentohangup = diff;
3063 ast_channel_unlock(c[x]);
3065 /* Wait full interval */
3067 /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3068 if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3069 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
3070 if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
3073 } else if (!ast_tvzero(whentohangup) && rms < 0) {
3074 /* Tiny corner case... call would need to last >24 days */
3078 * Build the pollfd array, putting the channels' fds first,
3079 * followed by individual fds. Order is important because
3080 * individual fd's must have priority over channel fds.
3083 for (x = 0; x < n; x++) {
3084 for (y = 0; y < AST_MAX_FDS; y++) {
3085 fdmap[max].fdno = y; /* fd y is linked to this pfds */
3086 fdmap[max].chan = x; /* channel x is linked to this pfds */
3087 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
3089 CHECK_BLOCKING(c[x]);
3091 /* Add the individual fds */
3092 for (x = 0; x < nfds; x++) {
3093 fdmap[max].chan = -1;
3094 max += ast_add_fd(&pfds[max], fds[x]);
3098 start = ast_tvnow();
3100 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3105 res = ast_poll(pfds, max, kbrms);
3108 } while (!res && (rms > 0));
3110 res = ast_poll(pfds, max, rms);
3112 for (x = 0; x < n; x++)
3113 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
3114 if (res < 0) { /* Simulate a timeout if we were interrupted */
3119 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
3121 for (x = 0; x < n; x++) {
3122 if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
3123 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3129 if (res == 0) { /* no fd ready, reset timeout and done */
3130 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
3134 * Then check if any channel or fd has a pending event.
3135 * Remember to check channels first and fds last, as they
3136 * must have priority on setting 'winner'
3138 for (x = 0; x < max; x++) {
3139 res = pfds[x].revents;
3142 if (fdmap[x].chan >= 0) { /* this is a channel */
3143 winner = c[fdmap[x].chan]; /* override previous winners */
3145 ast_set_flag(winner, AST_FLAG_EXCEPTION);
3147 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3148 winner->fdno = fdmap[x].fdno;
3149 } else { /* this is an fd */
3151 *outfd = pfds[x].fd;
3153 *exception = (res & POLLPRI) ? -1 : 0;
3158 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3166 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3168 struct timeval start = { 0 , 0 };
3170 struct epoll_event ev[1];
3171 long diff, rms = *ms;
3172 struct ast_channel *winner = NULL;
3173 struct ast_epoll_data *aed = NULL;
3176 /* See if this channel needs to be masqueraded */
3177 if (chan->masq && ast_do_masquerade(chan)) {
3178 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
3183 ast_channel_lock(chan);
3184 /* Figure out their timeout */
3185 if (!ast_tvzero(chan->whentohangup)) {
3186 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
3187 /* They should already be hungup! */
3188 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3189 ast_channel_unlock(chan);
3192 /* If this value is smaller then the current one... make it priority */
3197 ast_channel_unlock(chan);
3199 /* Time to make this channel block... */
3200 CHECK_BLOCKING(chan);
3203 start = ast_tvnow();
3205 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3206 res = epoll_wait(chan->epfd, ev, 1, rms);
3209 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3211 /* Simulate a timeout if we were interrupted */
3218 /* If this channel has a timeout see if it expired */
3219 if (!ast_tvzero(chan->whentohangup)) {
3220 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
3221 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3226 /* No fd ready, reset timeout and be done for now */
3232 /* See what events are pending */
3233 aed = ev[0].data.ptr;
3234 chan->fdno = aed->which;
3235 if (ev[0].events & EPOLLPRI)
3236 ast_set_flag(chan, AST_FLAG_EXCEPTION);
3238 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3241 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3249 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3251 struct timeval start = { 0 , 0 };
3253 struct epoll_event ev[25] = { { 0, } };
3254 struct timeval now = { 0, 0 };
3255 long whentohangup = 0, diff = 0, rms = *ms;
3256 struct ast_channel *winner = NULL;
3258 for (i = 0; i < n; i++) {
3259 if (c[i]->masq && ast_do_masquerade(c[i])) {
3260 ast_log(LOG_WARNING, "Masquerade failed\n");
3265 ast_channel_lock(c[i]);
3266 if (!ast_tvzero(c[i]->whentohangup)) {
3267 if (whentohangup == 0)
3269 if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
3270 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3271 ast_channel_unlock(c[i]);
3274 if (!whentohangup || whentohangup > diff)
3275 whentohangup = diff;
3277 ast_channel_unlock(c[i]);
3278 CHECK_BLOCKING(c[i]);
3284 if (*ms >= 0 && *ms < rms)
3289 start = ast_tvnow();
3291 res = epoll_wait(c[0]->epfd, ev, 25, rms);
3293 for (i = 0; i < n; i++)
3294 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
3304 for (i = 0; i < n; i++) {
3305 if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
3306 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3318 for (i = 0; i < res; i++) {
3319 struct ast_epoll_data *aed = ev[i].data.ptr;
3321 if (!ev[i].events || !aed)