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/threadstorage.h"
62 #include "asterisk/slinfactory.h"
63 #include "asterisk/audiohook.h"
64 #include "asterisk/framehook.h"
65 #include "asterisk/timing.h"
66 #include "asterisk/autochan.h"
67 #include "asterisk/stringfields.h"
68 #include "asterisk/global_datastores.h"
69 #include "asterisk/data.h"
70 #include "asterisk/channel_internal.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;
99 unsigned long global_fin, global_fout;
101 AST_THREADSTORAGE(state2str_threadbuf);
102 #define STATE2STR_BUFSIZE 32
104 /*! Default amount of time to use when emulating a digit as a begin and end
106 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
108 /*! Minimum amount of time between the end of the last digit and the beginning
109 * of a new one - 45ms */
110 #define AST_MIN_DTMF_GAP 45
112 /*! \brief List of channel drivers */
114 const struct ast_channel_tech *tech;
115 AST_LIST_ENTRY(chanlist) list;
119 /*! \brief Structure to hold channel context backtrace data */
120 struct ast_chan_trace_data {
122 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
125 /*! \brief Structure to save contexts where an ast_chan has been into */
126 struct ast_chan_trace {
127 char context[AST_MAX_CONTEXT];
128 char exten[AST_MAX_EXTENSION];
130 AST_LIST_ENTRY(ast_chan_trace) entry;
134 /*! \brief the list of registered channel types */
135 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
138 #define NUM_CHANNEL_BUCKETS 61
140 #define NUM_CHANNEL_BUCKETS 1567
143 /*! \brief All active channels on the system */
144 static struct ao2_container *channels;
146 /*! \brief map AST_CAUSE's to readable string representations
150 static const struct {
155 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
156 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
157 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
158 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
159 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
160 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
161 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
162 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
163 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
164 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
165 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
166 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
167 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
168 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
169 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
170 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
171 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
172 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
173 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
174 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
175 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
176 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
177 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
178 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
179 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
180 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
181 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
182 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
183 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
184 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
185 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
186 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
187 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
188 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
189 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
190 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
191 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
192 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
193 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
194 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
195 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
196 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
197 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
198 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
201 struct ast_variable *ast_channeltype_list(void)
204 struct ast_variable *var = NULL, *prev = NULL;
206 AST_RWLIST_RDLOCK(&backends);
207 AST_RWLIST_TRAVERSE(&backends, cl, list) {
209 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
212 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
216 AST_RWLIST_UNLOCK(&backends);
221 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
222 static const char *party_number_ton2str(int ton)
224 #if defined(HAVE_PRI)
225 switch ((ton >> 4) & 0x07) {
226 case PRI_TON_INTERNATIONAL:
227 return "International";
228 case PRI_TON_NATIONAL:
230 case PRI_TON_NET_SPECIFIC:
231 return "Network Specific";
232 case PRI_TON_SUBSCRIBER:
234 case PRI_TON_ABBREVIATED:
235 return "Abbreviated";
236 case PRI_TON_RESERVED:
238 case PRI_TON_UNKNOWN:
242 #endif /* defined(HAVE_PRI) */
245 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
247 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
248 static const char *party_number_plan2str(int plan)
250 #if defined(HAVE_PRI)
251 switch (plan & 0x0F) {
253 case PRI_NPI_UNKNOWN:
255 case PRI_NPI_E163_E164:
256 return "Public (E.163/E.164)";
258 return "Data (X.121)";
260 return "Telex (F.69)";
261 case PRI_NPI_NATIONAL:
262 return "National Standard";
263 case PRI_NPI_PRIVATE:
265 case PRI_NPI_RESERVED:
268 #endif /* defined(HAVE_PRI) */
271 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
273 /*! \brief Show channel types - CLI command */
274 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
276 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
282 e->command = "core show channeltypes";
284 "Usage: core show channeltypes\n"
285 " Lists available channel types registered in your\n"
286 " Asterisk server.\n";
293 return CLI_SHOWUSAGE;
295 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
296 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
298 AST_RWLIST_RDLOCK(&backends);
299 AST_RWLIST_TRAVERSE(&backends, cl, list) {
300 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
301 (cl->tech->devicestate) ? "yes" : "no",
302 (cl->tech->indicate) ? "yes" : "no",
303 (cl->tech->transfer) ? "yes" : "no");
306 AST_RWLIST_UNLOCK(&backends);
308 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
315 static char *complete_channeltypes(struct ast_cli_args *a)
325 wordlen = strlen(a->word);
327 AST_RWLIST_RDLOCK(&backends);
328 AST_RWLIST_TRAVERSE(&backends, cl, list) {
329 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
330 ret = ast_strdup(cl->tech->type);
334 AST_RWLIST_UNLOCK(&backends);
339 /*! \brief Show details about a channel driver - CLI command */
340 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
342 struct chanlist *cl = NULL;
347 e->command = "core show channeltype";
349 "Usage: core show channeltype <name>\n"
350 " Show details about the specified channel type, <name>.\n";
353 return complete_channeltypes(a);
357 return CLI_SHOWUSAGE;
359 AST_RWLIST_RDLOCK(&backends);
361 AST_RWLIST_TRAVERSE(&backends, cl, list) {
362 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
368 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
369 AST_RWLIST_UNLOCK(&backends);
374 "-- Info about channel driver: %s --\n"
375 " Device State: %s\n"
378 " Capabilities: %s\n"
382 " Image Support: %s\n"
383 " Text Support: %s\n",
385 (cl->tech->devicestate) ? "yes" : "no",
386 (cl->tech->indicate) ? "yes" : "no",
387 (cl->tech->transfer) ? "yes" : "no",
388 ast_getformatname_multiple(buf, sizeof(buf), cl->tech->capabilities),
389 (cl->tech->send_digit_begin) ? "yes" : "no",
390 (cl->tech->send_digit_end) ? "yes" : "no",
391 (cl->tech->send_html) ? "yes" : "no",
392 (cl->tech->send_image) ? "yes" : "no",
393 (cl->tech->send_text) ? "yes" : "no"
397 AST_RWLIST_UNLOCK(&backends);
402 static struct ast_cli_entry cli_channel[] = {
403 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
404 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
407 static struct ast_frame *kill_read(struct ast_channel *chan)
409 /* Hangup channel. */
413 static struct ast_frame *kill_exception(struct ast_channel *chan)
415 /* Hangup channel. */
419 static int kill_write(struct ast_channel *chan, struct ast_frame *frame)
421 /* Hangup channel. */
425 static int kill_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
427 /* No problem fixing up the channel. */
431 static int kill_hangup(struct ast_channel *chan)
433 ast_channel_tech_pvt_set(chan, NULL);
438 * \brief Kill the channel channel driver technology descriptor.
441 * The purpose of this channel technology is to encourage the
442 * channel to hangup as quickly as possible.
444 * \note Used by DTMF atxfer and zombie channels.
446 const struct ast_channel_tech ast_kill_tech = {
448 .description = "Kill channel (should not see this)",
450 .exception = kill_exception,
453 .hangup = kill_hangup,
457 /*! \brief Destructor for the channel trace datastore */
458 static void ast_chan_trace_destroy_cb(void *data)
460 struct ast_chan_trace *trace;
461 struct ast_chan_trace_data *traced = data;
462 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
468 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
469 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
471 .destroy = ast_chan_trace_destroy_cb
474 /*! \brief Put the channel backtrace in a string */
475 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
478 struct ast_chan_trace *trace;
479 struct ast_chan_trace_data *traced;
480 struct ast_datastore *store;
482 ast_channel_lock(chan);
483 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
485 ast_channel_unlock(chan);
488 traced = store->data;
490 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
491 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
492 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
498 ast_channel_unlock(chan);
502 /* !\brief Whether or not context tracing is enabled */
503 int ast_channel_trace_is_enabled(struct ast_channel *chan)
505 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
508 return ((struct ast_chan_trace_data *)store->data)->enabled;
511 /*! \brief Update the context backtrace data if tracing is enabled */
512 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
514 struct ast_chan_trace *trace;
515 if (!traced->enabled)
517 /* If the last saved context does not match the current one
518 OR we have not saved any context so far, then save the current context */
519 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan))) ||
520 (AST_LIST_EMPTY(&traced->trace))) {
521 /* Just do some debug logging */
522 if (AST_LIST_EMPTY(&traced->trace))
523 ast_debug(1, "Setting initial trace context to %s\n", ast_channel_context(chan));
525 ast_debug(1, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan));
526 /* alloc or bail out */
527 trace = ast_malloc(sizeof(*trace));
530 /* save the current location and store it in the trace list */
531 ast_copy_string(trace->context, ast_channel_context(chan), sizeof(trace->context));
532 ast_copy_string(trace->exten, ast_channel_exten(chan), sizeof(trace->exten));
533 trace->priority = ast_channel_priority(chan);
534 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
539 /*! \brief Update the context backtrace if tracing is enabled */
540 int ast_channel_trace_update(struct ast_channel *chan)
542 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
545 return ast_channel_trace_data_update(chan, store->data);
548 /*! \brief Enable context tracing in the channel */
549 int ast_channel_trace_enable(struct ast_channel *chan)
551 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
552 struct ast_chan_trace_data *traced;
554 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
557 traced = ast_calloc(1, sizeof(*traced));
559 ast_datastore_free(store);
562 store->data = traced;
563 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
564 ast_channel_datastore_add(chan, store);
566 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
567 ast_channel_trace_data_update(chan, store->data);
571 /*! \brief Disable context tracing in the channel */
572 int ast_channel_trace_disable(struct ast_channel *chan)
574 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
577 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
580 #endif /* CHANNEL_TRACE */
582 /*! \brief Checks to see if a channel is needing hang up */
583 int ast_check_hangup(struct ast_channel *chan)
585 if (ast_channel_softhangup_internal_flag(chan)) /* yes if soft hangup flag set */
587 if (ast_tvzero(*ast_channel_whentohangup(chan))) /* no if no hangup scheduled */
589 if (ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()) > 0) /* no if hangup time has not come yet. */
591 ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()));
592 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT); /* record event */
596 int ast_check_hangup_locked(struct ast_channel *chan)
599 ast_channel_lock(chan);
600 res = ast_check_hangup(chan);
601 ast_channel_unlock(chan);
605 void ast_channel_softhangup_withcause_locked(struct ast_channel *chan, int causecode)
607 ast_channel_lock(chan);
610 ast_debug(1, "Setting hangupcause of channel %s to %d (is %d now)\n",
611 ast_channel_name(chan), causecode, ast_channel_hangupcause(chan));
613 ast_channel_hangupcause_set(chan, causecode);
616 ast_softhangup_nolock(chan, AST_SOFTHANGUP_EXPLICIT);
618 ast_channel_unlock(chan);
621 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
623 struct ast_channel *chan = obj;
625 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
630 void ast_begin_shutdown(int hangup)
635 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
639 /*! \brief returns number of active/allocated channels */
640 int ast_active_channels(void)
642 return channels ? ao2_container_count(channels) : 0;
645 int ast_undestroyed_channels(void)
647 return ast_atomic_fetchadd_int(&chancount, 0);
650 /*! \brief Cancel a shutdown in progress */
651 void ast_cancel_shutdown(void)
656 /*! \brief Returns non-zero if Asterisk is being shut down */
657 int ast_shutting_down(void)
659 return shutting_down;
662 /*! \brief Set when to hangup channel */
663 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
665 if (ast_tvzero(offset)) {
666 ast_channel_whentohangup_set(chan, &offset);
668 struct timeval tv = ast_tvadd(offset, ast_tvnow());
669 ast_channel_whentohangup_set(chan, &tv);
671 ast_queue_frame(chan, &ast_null_frame);
675 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
677 struct timeval when = { offset, };
678 ast_channel_setwhentohangup_tv(chan, when);
681 /*! \brief Compare a offset with when to hangup channel */
682 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
684 struct timeval whentohangup;
686 if (ast_tvzero(*ast_channel_whentohangup(chan)))
687 return ast_tvzero(offset) ? 0 : -1;
689 if (ast_tvzero(offset))
692 whentohangup = ast_tvadd(offset, ast_tvnow());
694 return ast_tvdiff_ms(whentohangup, *ast_channel_whentohangup(chan));
697 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
699 struct timeval when = { offset, };
700 return ast_channel_cmpwhentohangup_tv(chan, when);
703 /*! \brief Register a new telephony channel in Asterisk */
704 int ast_channel_register(const struct ast_channel_tech *tech)
706 struct chanlist *chan;
708 AST_RWLIST_WRLOCK(&backends);
710 AST_RWLIST_TRAVERSE(&backends, chan, list) {
711 if (!strcasecmp(tech->type, chan->tech->type)) {
712 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
713 AST_RWLIST_UNLOCK(&backends);
718 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
719 AST_RWLIST_UNLOCK(&backends);
723 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
725 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
727 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
729 AST_RWLIST_UNLOCK(&backends);
734 /*! \brief Unregister channel driver */
735 void ast_channel_unregister(const struct ast_channel_tech *tech)
737 struct chanlist *chan;
739 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
741 AST_RWLIST_WRLOCK(&backends);
743 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
744 if (chan->tech == tech) {
745 AST_LIST_REMOVE_CURRENT(list);
747 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
751 AST_LIST_TRAVERSE_SAFE_END;
753 AST_RWLIST_UNLOCK(&backends);
756 /*! \brief Get handle to channel driver based on name */
757 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
759 struct chanlist *chanls;
760 const struct ast_channel_tech *ret = NULL;
762 AST_RWLIST_RDLOCK(&backends);
764 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
765 if (!strcasecmp(name, chanls->tech->type)) {
771 AST_RWLIST_UNLOCK(&backends);
776 /*! \brief Gives the string form of a given hangup cause */
777 const char *ast_cause2str(int cause)
781 for (x = 0; x < ARRAY_LEN(causes); x++) {
782 if (causes[x].cause == cause)
783 return causes[x].desc;
789 /*! \brief Convert a symbolic hangup cause to number */
790 int ast_str2cause(const char *name)
794 for (x = 0; x < ARRAY_LEN(causes); x++)
795 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
796 return causes[x].cause;
801 /*! \brief Gives the string form of a given channel state.
802 \note This function is not reentrant.
804 const char *ast_state2str(enum ast_channel_state state)
811 case AST_STATE_RESERVED:
813 case AST_STATE_OFFHOOK:
815 case AST_STATE_DIALING:
819 case AST_STATE_RINGING:
825 case AST_STATE_DIALING_OFFHOOK:
826 return "Dialing Offhook";
827 case AST_STATE_PRERING:
830 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
832 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
837 /*! \brief Gives the string form of a given transfer capability */
838 char *ast_transfercapability2str(int transfercapability)
840 switch (transfercapability) {
841 case AST_TRANS_CAP_SPEECH:
843 case AST_TRANS_CAP_DIGITAL:
845 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
846 return "RESTRICTED_DIGITAL";
847 case AST_TRANS_CAP_3_1K_AUDIO:
849 case AST_TRANS_CAP_DIGITAL_W_TONES:
850 return "DIGITAL_W_TONES";
851 case AST_TRANS_CAP_VIDEO:
858 /*! \brief Pick the best audio codec */
859 struct ast_format *ast_best_codec(struct ast_format_cap *cap, struct ast_format *result)
861 /* This just our opinion, expressed in code. We are asked to choose
862 the best codec to use, given no information */
863 static const enum ast_format_id prefs[] =
865 /*! Okay, ulaw is used by all telephony equipment, so start with it */
867 /*! Unless of course, you're a silly European, so then prefer ALAW */
873 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
875 /*! Okay, well, signed linear is easy to translate into other stuff */
876 AST_FORMAT_SLINEAR192,
877 AST_FORMAT_SLINEAR96,
878 AST_FORMAT_SLINEAR48,
879 AST_FORMAT_SLINEAR44,
880 AST_FORMAT_SLINEAR32,
881 AST_FORMAT_SLINEAR24,
882 AST_FORMAT_SLINEAR16,
883 AST_FORMAT_SLINEAR12,
885 /*! G.726 is standard ADPCM, in RFC3551 packing order */
887 /*! G.726 is standard ADPCM, in AAL2 packing order */
888 AST_FORMAT_G726_AAL2,
889 /*! ADPCM has great sound quality and is still pretty easy to translate */
891 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
892 translate and sounds pretty good */
894 /*! iLBC is not too bad */
896 /*! Speex is free, but computationally more expensive than GSM */
900 /*! SILK is pretty awesome. */
902 /*! CELT supports crazy high sample rates */
904 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
907 /*! G.729a is faster than 723 and slightly less expensive */
909 /*! Down to G.723.1 which is proprietary but at least designed for voice */
915 /* Find the first preferred codec in the format given */
916 for (x = 0; x < ARRAY_LEN(prefs); x++) {
917 if (ast_format_cap_best_byid(cap, prefs[x], result)) {
922 ast_format_clear(result);
923 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
928 static const struct ast_channel_tech null_tech = {
930 .description = "Null channel (should not see this)",
933 static void ast_channel_destructor(void *obj);
934 static void ast_dummy_channel_destructor(void *obj);
936 /*! \brief Create a new channel structure */
937 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
938 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
939 const char *acctcode, const char *exten, const char *context,
940 const char *linkedid, const int amaflag, const char *file, int line,
941 const char *function, const char *name_fmt, va_list ap)
943 struct ast_channel *tmp;
944 struct varshead *headp;
945 char *tech = "", *tech2 = NULL;
946 struct ast_format_cap *nativeformats;
947 struct ast_sched_context *schedctx;
948 struct ast_timer *timer;
950 /* If shutting down, don't allocate any new channels */
951 if (ast_shutting_down()) {
952 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
956 if (!(tmp = ast_channel_internal_alloc(ast_channel_destructor))) {
957 /* Channel structure allocation failure. */
960 if (!(nativeformats = ast_format_cap_alloc())) {
962 /* format capabilities structure allocation failure */
965 ast_channel_nativeformats_set(tmp, nativeformats);
968 * Init file descriptors to unopened state so
969 * the destructor can know not to close them.
971 ast_channel_timingfd_set(tmp, -1);
972 ast_channel_internal_alertpipe_clear(tmp);
973 ast_channel_internal_fd_clear_all(tmp);
976 ast_channel_epfd(tmp) = epoll_create(25);
979 if (!(schedctx = ast_sched_context_create())) {
980 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
981 return ast_channel_unref(tmp);
983 ast_channel_sched_set(tmp, schedctx);
985 ast_party_dialed_init(ast_channel_dialed(tmp));
986 ast_party_caller_init(ast_channel_caller(tmp));
987 ast_party_connected_line_init(ast_channel_connected(tmp));
988 ast_party_redirecting_init(ast_channel_redirecting(tmp));
991 ast_channel_caller(tmp)->id.name.valid = 1;
992 ast_channel_caller(tmp)->id.name.str = ast_strdup(cid_name);
993 if (!ast_channel_caller(tmp)->id.name.str) {
994 return ast_channel_unref(tmp);
998 ast_channel_caller(tmp)->id.number.valid = 1;
999 ast_channel_caller(tmp)->id.number.str = ast_strdup(cid_num);
1000 if (!ast_channel_caller(tmp)->id.number.str) {
1001 return ast_channel_unref(tmp);
1005 if ((timer = ast_timer_open())) {
1006 ast_channel_timer_set(tmp, timer);
1007 if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
1010 ast_channel_timingfd_set(tmp, ast_timer_fd(ast_channel_timer(tmp)));
1014 * This is the last place the channel constructor can fail.
1016 * The destructor takes advantage of this fact to ensure that the
1017 * AST_CEL_CHANNEL_END is not posted if we have not posted the
1018 * AST_CEL_CHANNEL_START yet.
1021 if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
1022 return ast_channel_unref(tmp);
1025 /* Always watch the alertpipe */
1026 ast_channel_set_fd(tmp, AST_ALERT_FD, ast_channel_internal_alert_readfd(tmp));
1027 /* And timing pipe */
1028 ast_channel_set_fd(tmp, AST_TIMING_FD, ast_channel_timingfd(tmp));
1031 ast_channel_state_set(tmp, state);
1033 ast_channel_streamid_set(tmp, -1);
1035 ast_channel_fin_set(tmp, global_fin);
1036 ast_channel_fout_set(tmp, global_fout);
1038 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1039 ast_channel_uniqueid_build(tmp, "%li.%d", (long) time(NULL),
1040 ast_atomic_fetchadd_int(&uniqueint, 1));
1042 ast_channel_uniqueid_build(tmp, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
1043 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1046 if (!ast_strlen_zero(linkedid)) {
1047 ast_channel_linkedid_set(tmp, linkedid);
1049 ast_channel_linkedid_set(tmp, ast_channel_uniqueid(tmp));
1052 if (!ast_strlen_zero(name_fmt)) {
1053 char *slash, *slash2;
1054 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1055 * And they all use slightly different formats for their name string.
1056 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1057 * This means, that the stringfields must have a routine that takes the va_lists directly, and
1058 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1059 * This new function was written so this can be accomplished.
1061 ast_channel_name_build_va(tmp, name_fmt, ap);
1062 tech = ast_strdupa(ast_channel_name(tmp));
1063 if ((slash = strchr(tech, '/'))) {
1064 if ((slash2 = strchr(slash + 1, '/'))) {
1072 * Start the string with '-' so it becomes an empty string
1073 * in the destructor.
1075 ast_channel_name_set(tmp, "-**Unknown**");
1078 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1080 /* These 4 variables need to be set up for the cdr_init() to work right */
1082 ast_channel_amaflags_set(tmp, amaflag);
1084 ast_channel_amaflags_set(tmp, ast_default_amaflags);
1087 if (!ast_strlen_zero(acctcode))
1088 ast_channel_accountcode_set(tmp, acctcode);
1090 ast_channel_accountcode_set(tmp, ast_default_accountcode);
1092 ast_channel_context_set(tmp, S_OR(context, "default"));
1093 ast_channel_exten_set(tmp, S_OR(exten, "s"));
1094 ast_channel_priority_set(tmp, 1);
1096 ast_channel_cdr_set(tmp, ast_cdr_alloc());
1097 ast_cdr_init(ast_channel_cdr(tmp), tmp);
1098 ast_cdr_start(ast_channel_cdr(tmp));
1100 ast_atomic_fetchadd_int(&chancount, +1);
1101 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1103 headp = ast_channel_varshead(tmp);
1104 AST_LIST_HEAD_INIT_NOLOCK(headp);
1106 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1108 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_autochans(tmp));
1110 ast_channel_language_set(tmp, defaultlanguage);
1112 ast_channel_tech_set(tmp, &null_tech);
1114 ao2_link(channels, tmp);
1117 * And now, since the channel structure is built, and has its name, let's
1118 * call the manager event generator with this Newchannel event. This is the
1119 * proper and correct place to make this call, but you sure do have to pass
1120 * a lot of data into this func to do it here!
1122 if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1123 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1125 "ChannelState: %d\r\n"
1126 "ChannelStateDesc: %s\r\n"
1127 "CallerIDNum: %s\r\n"
1128 "CallerIDName: %s\r\n"
1129 "AccountCode: %s\r\n"
1133 ast_channel_name(tmp),
1135 ast_state2str(state),
1138 ast_channel_accountcode(tmp),
1141 ast_channel_uniqueid(tmp));
1144 ast_channel_internal_finalize(tmp);
1148 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1149 const char *cid_name, const char *acctcode,
1150 const char *exten, const char *context,
1151 const char *linkedid, const int amaflag,
1152 const char *file, int line, const char *function,
1153 const char *name_fmt, ...)
1156 struct ast_channel *result;
1158 va_start(ap, name_fmt);
1159 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1160 linkedid, amaflag, file, line, function, name_fmt, ap);
1166 /* only do the minimum amount of work needed here to make a channel
1167 * structure that can be used to expand channel vars */
1168 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1169 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1171 struct ast_channel *ast_dummy_channel_alloc(void)
1174 struct ast_channel *tmp;
1175 struct varshead *headp;
1177 if (!(tmp = ast_channel_internal_alloc(ast_dummy_channel_destructor))) {
1178 /* Dummy channel structure allocation failure. */
1182 headp = ast_channel_varshead(tmp);
1183 AST_LIST_HEAD_INIT_NOLOCK(headp);
1188 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1190 struct ast_frame *f;
1191 struct ast_frame *cur;
1192 unsigned int new_frames = 0;
1193 unsigned int new_voice_frames = 0;
1194 unsigned int queued_frames = 0;
1195 unsigned int queued_voice_frames = 0;
1196 AST_LIST_HEAD_NOLOCK(,ast_frame) frames;
1198 ast_channel_lock(chan);
1201 * Check the last frame on the queue if we are queuing the new
1204 cur = AST_LIST_LAST(ast_channel_readq(chan));
1205 if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1206 switch (cur->subclass.integer) {
1207 case AST_CONTROL_END_OF_Q:
1208 if (fin->frametype == AST_FRAME_CONTROL
1209 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1211 * Destroy the end-of-Q marker frame so we can queue the hangup
1212 * frame in its place.
1214 AST_LIST_REMOVE(ast_channel_readq(chan), cur, frame_list);
1218 * This has degenerated to a normal queue append anyway. Since
1219 * we just destroyed the last frame in the queue we must make
1220 * sure that "after" is NULL or bad things will happen.
1226 case AST_CONTROL_HANGUP:
1227 /* Don't queue anything. */
1228 ast_channel_unlock(chan);
1235 /* Build copies of all the new frames and count them */
1236 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1237 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1238 if (!(f = ast_frdup(cur))) {
1239 if (AST_LIST_FIRST(&frames)) {
1240 ast_frfree(AST_LIST_FIRST(&frames));
1242 ast_channel_unlock(chan);
1246 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1248 if (f->frametype == AST_FRAME_VOICE) {
1253 /* Count how many frames exist on the queue */
1254 AST_LIST_TRAVERSE(ast_channel_readq(chan), cur, frame_list) {
1256 if (cur->frametype == AST_FRAME_VOICE) {
1257 queued_voice_frames++;
1261 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1263 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1264 AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), cur, frame_list) {
1265 /* Save the most recent frame */
1266 if (!AST_LIST_NEXT(cur, frame_list)) {
1268 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1272 AST_LIST_REMOVE_CURRENT(frame_list);
1276 AST_LIST_TRAVERSE_SAFE_END;
1280 AST_LIST_INSERT_LIST_AFTER(ast_channel_readq(chan), &frames, after, frame_list);
1283 AST_LIST_APPEND_LIST(&frames, ast_channel_readq(chan), frame_list);
1284 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_readq(chan));
1286 AST_LIST_APPEND_LIST(ast_channel_readq(chan), &frames, frame_list);
1289 if (ast_channel_alert_writable(chan)) {
1290 if (ast_channel_alert_write(chan)) {
1291 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1292 ast_channel_name(chan), queued_frames, strerror(errno));
1294 } else if (ast_channel_timingfd(chan) > -1) {
1295 ast_timer_enable_continuous(ast_channel_timer(chan));
1296 } else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
1297 pthread_kill(ast_channel_blocker(chan), SIGURG);
1300 ast_channel_unlock(chan);
1305 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1307 return __ast_queue_frame(chan, fin, 0, NULL);
1310 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1312 return __ast_queue_frame(chan, fin, 1, NULL);
1315 /*! \brief Queue a hangup frame for channel */
1316 int ast_queue_hangup(struct ast_channel *chan)
1318 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1321 /* Yeah, let's not change a lock-critical value without locking */
1322 ast_channel_lock(chan);
1323 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1325 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1328 ast_channel_name(chan),
1329 ast_channel_uniqueid(chan));
1331 res = ast_queue_frame(chan, &f);
1332 ast_channel_unlock(chan);
1336 /*! \brief Queue a hangup frame for channel */
1337 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1339 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1343 f.data.uint32 = cause;
1346 /* Yeah, let's not change a lock-critical value without locking */
1347 ast_channel_lock(chan);
1348 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1350 f.data.uint32 = ast_channel_hangupcause(chan);
1353 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1357 ast_channel_name(chan),
1358 ast_channel_uniqueid(chan),
1361 res = ast_queue_frame(chan, &f);
1362 ast_channel_unlock(chan);
1366 /*! \brief Queue a control frame */
1367 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1369 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1370 return ast_queue_frame(chan, &f);
1373 /*! \brief Queue a control frame with payload */
1374 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1375 const void *data, size_t datalen)
1377 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1378 return ast_queue_frame(chan, &f);
1381 /*! \brief Set defer DTMF flag on channel */
1382 int ast_channel_defer_dtmf(struct ast_channel *chan)
1387 pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1388 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1393 /*! \brief Unset defer DTMF flag on channel */
1394 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1397 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1400 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1401 void *data, int ao2_flags)
1403 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1406 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1408 struct ast_channel *chan = obj;
1409 const char *name = arg;
1410 size_t name_len = *(size_t *) data;
1411 int ret = CMP_MATCH;
1413 if (ast_strlen_zero(name)) {
1414 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1418 ast_channel_lock(chan);
1419 if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1420 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1421 ret = 0; /* name match failed, keep looking */
1423 ast_channel_unlock(chan);
1428 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1430 struct ast_channel *chan = obj;
1431 char *context = arg;
1433 int ret = CMP_MATCH;
1435 if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1436 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1440 ast_channel_lock(chan);
1441 if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1442 ret = 0; /* Context match failed, continue */
1443 } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1444 ret = 0; /* Extension match failed, continue */
1446 ast_channel_unlock(chan);
1451 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1453 struct ast_channel *chan = obj;
1454 char *uniqueid = arg;
1455 size_t id_len = *(size_t *) data;
1456 int ret = CMP_MATCH;
1458 if (ast_strlen_zero(uniqueid)) {
1459 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1463 ast_channel_lock(chan);
1464 if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1465 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1466 ret = 0; /* uniqueid match failed, keep looking */
1468 ast_channel_unlock(chan);
1473 struct ast_channel_iterator {
1474 /* storage for non-dynamically allocated iterator */
1475 struct ao2_iterator simple_iterator;
1476 /* pointer to the actual iterator (simple_iterator or a dynamically
1477 * allocated iterator)
1479 struct ao2_iterator *active_iterator;
1482 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1484 ao2_iterator_destroy(i->active_iterator);
1490 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1492 struct ast_channel_iterator *i;
1493 char *l_exten = (char *) exten;
1494 char *l_context = (char *) context;
1496 if (!(i = ast_calloc(1, sizeof(*i)))) {
1500 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1501 l_context, l_exten, OBJ_MULTIPLE);
1502 if (!i->active_iterator) {
1510 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1512 struct ast_channel_iterator *i;
1513 char *l_name = (char *) name;
1515 if (!(i = ast_calloc(1, sizeof(*i)))) {
1519 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1521 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1522 if (!i->active_iterator) {
1530 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1532 struct ast_channel_iterator *i;
1534 if (!(i = ast_calloc(1, sizeof(*i)))) {
1538 i->simple_iterator = ao2_iterator_init(channels, 0);
1539 i->active_iterator = &i->simple_iterator;
1544 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1546 return ao2_iterator_next(i->active_iterator);
1549 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1550 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1552 ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1556 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1558 struct ast_channel *chan;
1559 char *l_name = (char *) name;
1561 chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1562 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1567 if (ast_strlen_zero(l_name)) {
1568 /* We didn't have a name to search for so quit. */
1572 /* Now try a search for uniqueid. */
1573 return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1576 struct ast_channel *ast_channel_get_by_name(const char *name)
1578 return ast_channel_get_by_name_prefix(name, 0);
1581 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1583 char *l_exten = (char *) exten;
1584 char *l_context = (char *) context;
1586 return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1589 int ast_is_deferrable_frame(const struct ast_frame *frame)
1591 /* Do not add a default entry in this switch statement. Each new
1592 * frame type should be addressed directly as to whether it should
1593 * be queued up or not.
1595 switch (frame->frametype) {
1596 case AST_FRAME_CONTROL:
1597 case AST_FRAME_TEXT:
1598 case AST_FRAME_IMAGE:
1599 case AST_FRAME_HTML:
1602 case AST_FRAME_DTMF_END:
1603 case AST_FRAME_DTMF_BEGIN:
1604 case AST_FRAME_VOICE:
1605 case AST_FRAME_VIDEO:
1606 case AST_FRAME_NULL:
1609 case AST_FRAME_MODEM:
1615 /*! \brief Wait, look for hangups and condition arg */
1616 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1618 struct ast_frame *f;
1619 struct ast_silence_generator *silgen = NULL;
1621 AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1623 AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1625 /* If no other generator is present, start silencegen while waiting */
1626 if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1627 silgen = ast_channel_start_silence_generator(chan);
1631 struct ast_frame *dup_f = NULL;
1632 if (cond && ((*cond)(data) == 0)) {
1635 ms = ast_waitfor(chan, ms);
1647 if (!ast_is_deferrable_frame(f)) {
1652 if ((dup_f = ast_frisolate(f))) {
1656 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1661 /* stop silgen if present */
1663 ast_channel_stop_silence_generator(chan, silgen);
1666 /* We need to free all the deferred frames, but we only need to
1667 * queue the deferred frames if there was no error and no
1668 * hangup was received
1670 ast_channel_lock(chan);
1671 while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1673 ast_queue_frame_head(chan, f);
1677 ast_channel_unlock(chan);
1682 /*! \brief Wait, look for hangups */
1683 int ast_safe_sleep(struct ast_channel *chan, int ms)
1685 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1688 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1690 /* Safe, even if already unlinked. */
1691 ao2_unlink(channels, chan);
1692 return ast_channel_unref(chan);
1695 void ast_party_name_init(struct ast_party_name *init)
1698 init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1699 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1703 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1706 /* Don't copy to self */
1710 ast_free(dest->str);
1711 dest->str = ast_strdup(src->str);
1712 dest->char_set = src->char_set;
1713 dest->presentation = src->presentation;
1714 dest->valid = src->valid;
1717 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1720 init->char_set = guide->char_set;
1721 init->presentation = guide->presentation;
1722 init->valid = guide->valid;
1725 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1728 /* Don't set to self */
1732 if (src->str && src->str != dest->str) {
1733 ast_free(dest->str);
1734 dest->str = ast_strdup(src->str);
1737 dest->char_set = src->char_set;
1738 dest->presentation = src->presentation;
1739 dest->valid = src->valid;
1742 void ast_party_name_free(struct ast_party_name *doomed)
1744 ast_free(doomed->str);
1748 void ast_party_number_init(struct ast_party_number *init)
1751 init->plan = 0;/* Unknown */
1752 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1756 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1759 /* Don't copy to self */
1763 ast_free(dest->str);
1764 dest->str = ast_strdup(src->str);
1765 dest->plan = src->plan;
1766 dest->presentation = src->presentation;
1767 dest->valid = src->valid;
1770 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1773 init->plan = guide->plan;
1774 init->presentation = guide->presentation;
1775 init->valid = guide->valid;
1778 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1781 /* Don't set to self */
1785 if (src->str && src->str != dest->str) {
1786 ast_free(dest->str);
1787 dest->str = ast_strdup(src->str);
1790 dest->plan = src->plan;
1791 dest->presentation = src->presentation;
1792 dest->valid = src->valid;
1795 void ast_party_number_free(struct ast_party_number *doomed)
1797 ast_free(doomed->str);
1801 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1805 init->odd_even_indicator = 0;
1809 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1812 /* Don't copy to self */
1816 ast_free(dest->str);
1817 dest->str = ast_strdup(src->str);
1818 dest->type = src->type;
1819 dest->odd_even_indicator = src->odd_even_indicator;
1820 dest->valid = src->valid;
1823 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1826 init->type = guide->type;
1827 init->odd_even_indicator = guide->odd_even_indicator;
1828 init->valid = guide->valid;
1831 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1834 /* Don't set to self */
1838 if (src->str && src->str != dest->str) {
1839 ast_free(dest->str);
1840 dest->str = ast_strdup(src->str);
1843 dest->type = src->type;
1844 dest->odd_even_indicator = src->odd_even_indicator;
1845 dest->valid = src->valid;
1848 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1850 ast_free(doomed->str);
1854 void ast_party_id_init(struct ast_party_id *init)
1856 ast_party_name_init(&init->name);
1857 ast_party_number_init(&init->number);
1858 ast_party_subaddress_init(&init->subaddress);
1862 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1865 /* Don't copy to self */
1869 ast_party_name_copy(&dest->name, &src->name);
1870 ast_party_number_copy(&dest->number, &src->number);
1871 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1873 ast_free(dest->tag);
1874 dest->tag = ast_strdup(src->tag);
1877 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1879 ast_party_name_set_init(&init->name, &guide->name);
1880 ast_party_number_set_init(&init->number, &guide->number);
1881 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1885 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1888 /* Don't set to self */
1892 if (!update || update->name) {
1893 ast_party_name_set(&dest->name, &src->name);
1895 if (!update || update->number) {
1896 ast_party_number_set(&dest->number, &src->number);
1898 if (!update || update->subaddress) {
1899 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1902 if (src->tag && src->tag != dest->tag) {
1903 ast_free(dest->tag);
1904 dest->tag = ast_strdup(src->tag);
1908 void ast_party_id_free(struct ast_party_id *doomed)
1910 ast_party_name_free(&doomed->name);
1911 ast_party_number_free(&doomed->number);
1912 ast_party_subaddress_free(&doomed->subaddress);
1914 ast_free(doomed->tag);
1918 int ast_party_id_presentation(const struct ast_party_id *id)
1920 int number_priority;
1922 int number_screening;
1926 /* Determine name presentation priority. */
1927 if (!id->name.valid) {
1928 name_value = AST_PRES_UNAVAILABLE;
1931 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1932 switch (name_value) {
1933 case AST_PRES_RESTRICTED:
1936 case AST_PRES_ALLOWED:
1939 case AST_PRES_UNAVAILABLE:
1943 name_value = AST_PRES_UNAVAILABLE;
1949 /* Determine number presentation priority. */
1950 if (!id->number.valid) {
1951 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1952 number_value = AST_PRES_UNAVAILABLE;
1953 number_priority = 3;
1955 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1956 number_value = id->number.presentation & AST_PRES_RESTRICTION;
1957 switch (number_value) {
1958 case AST_PRES_RESTRICTED:
1959 number_priority = 0;
1961 case AST_PRES_ALLOWED:
1962 number_priority = 1;
1964 case AST_PRES_UNAVAILABLE:
1965 number_priority = 2;
1968 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1969 number_value = AST_PRES_UNAVAILABLE;
1970 number_priority = 3;
1975 /* Select the wining presentation value. */
1976 if (name_priority < number_priority) {
1977 number_value = name_value;
1979 if (number_value == AST_PRES_UNAVAILABLE) {
1980 return AST_PRES_NUMBER_NOT_AVAILABLE;
1983 return number_value | number_screening;
1986 void ast_party_dialed_init(struct ast_party_dialed *init)
1988 init->number.str = NULL;
1989 init->number.plan = 0;/* Unknown */
1990 ast_party_subaddress_init(&init->subaddress);
1991 init->transit_network_select = 0;
1994 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1997 /* Don't copy to self */
2001 ast_free(dest->number.str);
2002 dest->number.str = ast_strdup(src->number.str);
2003 dest->number.plan = src->number.plan;
2004 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2005 dest->transit_network_select = src->transit_network_select;
2008 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2010 init->number.str = NULL;
2011 init->number.plan = guide->number.plan;
2012 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2013 init->transit_network_select = guide->transit_network_select;
2016 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2018 if (src->number.str && src->number.str != dest->number.str) {
2019 ast_free(dest->number.str);
2020 dest->number.str = ast_strdup(src->number.str);
2022 dest->number.plan = src->number.plan;
2024 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2026 dest->transit_network_select = src->transit_network_select;
2029 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2031 ast_free(doomed->number.str);
2032 doomed->number.str = NULL;
2033 ast_party_subaddress_free(&doomed->subaddress);
2036 void ast_party_caller_init(struct ast_party_caller *init)
2038 ast_party_id_init(&init->id);
2039 ast_party_id_init(&init->ani);
2043 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2046 /* Don't copy to self */
2050 ast_party_id_copy(&dest->id, &src->id);
2051 ast_party_id_copy(&dest->ani, &src->ani);
2052 dest->ani2 = src->ani2;
2055 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2057 ast_party_id_set_init(&init->id, &guide->id);
2058 ast_party_id_set_init(&init->ani, &guide->ani);
2059 init->ani2 = guide->ani2;
2062 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2064 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2065 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2066 dest->ani2 = src->ani2;
2069 void ast_party_caller_free(struct ast_party_caller *doomed)
2071 ast_party_id_free(&doomed->id);
2072 ast_party_id_free(&doomed->ani);
2075 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2077 ast_party_id_init(&init->id);
2078 ast_party_id_init(&init->ani);
2080 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2083 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2086 /* Don't copy to self */
2090 ast_party_id_copy(&dest->id, &src->id);
2091 ast_party_id_copy(&dest->ani, &src->ani);
2092 dest->ani2 = src->ani2;
2093 dest->source = src->source;
2096 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2098 ast_party_id_set_init(&init->id, &guide->id);
2099 ast_party_id_set_init(&init->ani, &guide->ani);
2100 init->ani2 = guide->ani2;
2101 init->source = guide->source;
2104 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)
2106 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2107 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2108 dest->ani2 = src->ani2;
2109 dest->source = src->source;
2112 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2114 connected->id = caller->id;
2115 connected->ani = caller->ani;
2116 connected->ani2 = caller->ani2;
2117 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2120 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2122 ast_party_id_free(&doomed->id);
2123 ast_party_id_free(&doomed->ani);
2126 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2128 ast_party_id_init(&init->orig);
2129 ast_party_id_init(&init->from);
2130 ast_party_id_init(&init->to);
2132 init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2133 init->orig_reason = AST_REDIRECTING_REASON_UNKNOWN;
2136 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2139 /* Don't copy to self */
2143 ast_party_id_copy(&dest->orig, &src->orig);
2144 ast_party_id_copy(&dest->from, &src->from);
2145 ast_party_id_copy(&dest->to, &src->to);
2146 dest->count = src->count;
2147 dest->reason = src->reason;
2148 dest->orig_reason = src->orig_reason;
2151 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2153 ast_party_id_set_init(&init->orig, &guide->orig);
2154 ast_party_id_set_init(&init->from, &guide->from);
2155 ast_party_id_set_init(&init->to, &guide->to);
2156 init->count = guide->count;
2157 init->reason = guide->reason;
2158 init->orig_reason = guide->orig_reason;
2161 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2163 ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2164 ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2165 ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2166 dest->count = src->count;
2167 dest->reason = src->reason;
2168 dest->orig_reason = src->orig_reason;
2171 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2173 ast_party_id_free(&doomed->orig);
2174 ast_party_id_free(&doomed->from);
2175 ast_party_id_free(&doomed->to);
2178 /*! \brief Free a channel structure */
2179 static void ast_channel_destructor(void *obj)
2181 struct ast_channel *chan = obj;
2185 struct ast_var_t *vardata;
2186 struct ast_frame *f;
2187 struct varshead *headp;
2188 struct ast_datastore *datastore;
2189 char device_name[AST_CHANNEL_NAME];
2190 struct ast_callid *callid;
2192 if (ast_channel_internal_is_finalized(chan)) {
2193 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2194 ast_cel_check_retire_linkedid(chan);
2197 /* Get rid of each of the data stores on the channel */
2198 ast_channel_lock(chan);
2199 while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2200 /* Free the data store */
2201 ast_datastore_free(datastore);
2203 /* While the channel is locked, take the reference to its callid while we tear down the call. */
2204 callid = ast_channel_callid(chan);
2205 ast_channel_callid_cleanup(chan);
2207 ast_channel_unlock(chan);
2209 /* Lock and unlock the channel just to be sure nobody has it locked still
2210 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2211 ast_channel_lock(chan);
2212 ast_channel_unlock(chan);
2214 if (ast_channel_tech_pvt(chan)) {
2215 ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2216 ast_free(ast_channel_tech_pvt(chan));
2219 if (ast_channel_sched(chan)) {
2220 ast_sched_context_destroy(ast_channel_sched(chan));
2223 if (ast_channel_internal_is_finalized(chan)) {
2226 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2227 if ((dashptr = strrchr(device_name, '-'))) {
2231 device_name[0] = '\0';
2234 /* Stop monitoring */
2235 if (ast_channel_monitor(chan))
2236 ast_channel_monitor(chan)->stop( chan, 0 );
2238 /* If there is native format music-on-hold state, free it */
2239 if (ast_channel_music_state(chan))
2240 ast_moh_cleanup(chan);
2242 /* Free translators */
2243 if (ast_channel_readtrans(chan))
2244 ast_translator_free_path(ast_channel_readtrans(chan));
2245 if (ast_channel_writetrans(chan))
2246 ast_translator_free_path(ast_channel_writetrans(chan));
2247 if (ast_channel_pbx(chan))
2248 ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2250 ast_party_dialed_free(ast_channel_dialed(chan));
2251 ast_party_caller_free(ast_channel_caller(chan));
2252 ast_party_connected_line_free(ast_channel_connected(chan));
2253 ast_party_redirecting_free(ast_channel_redirecting(chan));
2255 /* Close pipes if appropriate */
2256 ast_channel_internal_alertpipe_close(chan);
2257 if (ast_channel_timer(chan)) {
2258 ast_timer_close(ast_channel_timer(chan));
2261 for (i = 0; i < AST_MAX_FDS; i++) {
2262 if (ast_channel_internal_epfd_data(chan, i)) {
2263 ast_free(ast_channel_internal_epfd_data(chan, i));
2266 close(ast_channel_epfd(chan));
2268 while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2271 /* loop over the variables list, freeing all data and deleting list items */
2272 /* no need to lock the list, as the channel is already locked */
2273 headp = ast_channel_varshead(chan);
2274 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2275 ast_var_delete(vardata);
2277 ast_app_group_discard(chan);
2279 /* Destroy the jitterbuffer */
2280 ast_jb_destroy(chan);
2282 if (ast_channel_cdr(chan)) {
2283 ast_cdr_discard(ast_channel_cdr(chan));
2284 ast_channel_cdr_set(chan, NULL);
2287 if (ast_channel_zone(chan)) {
2288 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2291 ast_channel_internal_cleanup(chan);
2293 if (device_name[0]) {
2295 * We have a device name to notify of a new state.
2297 * Queue an unknown state, because, while we know that this particular
2298 * instance is dead, we don't know the state of all other possible
2301 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2304 ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2306 ast_callid_unref(callid);
2308 ast_atomic_fetchadd_int(&chancount, -1);
2311 /*! \brief Free a dummy channel structure */
2312 static void ast_dummy_channel_destructor(void *obj)
2314 struct ast_channel *chan = obj;
2315 struct ast_var_t *vardata;
2316 struct varshead *headp;
2318 headp = ast_channel_varshead(chan);
2320 ast_party_dialed_free(ast_channel_dialed(chan));
2321 ast_party_caller_free(ast_channel_caller(chan));
2322 ast_party_connected_line_free(ast_channel_connected(chan));
2323 ast_party_redirecting_free(ast_channel_redirecting(chan));
2325 /* loop over the variables list, freeing all data and deleting list items */
2326 /* no need to lock the list, as the channel is already locked */
2327 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2328 ast_var_delete(vardata);
2330 if (ast_channel_cdr(chan)) {
2331 ast_cdr_discard(ast_channel_cdr(chan));
2332 ast_channel_cdr_set(chan, NULL);
2335 ast_channel_internal_cleanup(chan);
2338 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2340 return ast_datastore_alloc(info, uid);
2343 int ast_channel_datastore_free(struct ast_datastore *datastore)
2345 return ast_datastore_free(datastore);
2348 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2350 struct ast_datastore *datastore = NULL, *datastore2;
2352 AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2353 if (datastore->inheritance > 0) {
2354 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2356 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2357 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2358 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2365 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2369 AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2374 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2376 return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2379 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2381 struct ast_datastore *datastore = NULL;
2386 AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2387 if (datastore->info != info) {
2392 /* matched by type only */
2396 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2397 /* Matched by type AND uid */
2405 /*! Set the file descriptor on the channel */
2406 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2409 struct epoll_event ev;
2410 struct ast_epoll_data *aed = NULL;
2412 if (ast_channel_fd_isset(chan, which)) {
2413 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2414 aed = ast_channel_internal_epfd_data(chan, which);
2417 /* If this new fd is valid, add it to the epoll */
2419 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2422 ast_channel_internal_epfd_data_set(chan, which, aed);
2426 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2428 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2430 /* We don't have to keep around this epoll data structure now */
2432 ast_channel_epfd_data_set(chan, which, NULL);
2435 ast_channel_internal_fd_set(chan, which, fd);
2439 /*! Add a channel to an optimized waitfor */
2440 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2443 struct epoll_event ev;
2446 if (ast_channel_epfd(chan0) == -1)
2449 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2450 for (i = 0; i < AST_MAX_FDS; i++) {
2451 if (!ast_channel_fd_isset(chan1, i)) {
2454 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2455 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2456 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2463 /*! Delete a channel from an optimized waitfor */
2464 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2467 struct epoll_event ev;
2470 if (ast_channel_epfd(chan0) == -1)
2473 for (i = 0; i < AST_MAX_FDS; i++) {
2474 if (!ast_channel_fd_isset(chan1, i)) {
2477 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2484 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2486 ast_channel_lock(chan);
2488 ast_channel_softhangup_internal_flag_clear(chan, flag);
2490 if (!ast_channel_softhangup_internal_flag(chan)) {
2491 struct ast_frame *fr;
2493 /* If we have completely cleared the softhangup flag,
2494 * then we need to fully abort the hangup process. This requires
2495 * pulling the END_OF_Q frame out of the channel frame queue if it
2496 * still happens to be there. */
2498 fr = AST_LIST_LAST(ast_channel_readq(chan));
2499 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2500 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2501 AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2506 ast_channel_unlock(chan);
2509 /*! \brief Softly hangup a channel, don't lock */
2510 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2512 ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2513 /* Inform channel driver that we need to be hung up, if it cares */
2514 ast_channel_softhangup_internal_flag_add(chan, cause);
2515 ast_queue_frame(chan, &ast_null_frame);
2516 /* Interrupt any poll call or such */
2517 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2518 pthread_kill(ast_channel_blocker(chan), SIGURG);
2522 /*! \brief Softly hangup a channel, lock */
2523 int ast_softhangup(struct ast_channel *chan, int cause)
2527 ast_channel_lock(chan);
2528 res = ast_softhangup_nolock(chan, cause);
2529 manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2533 ast_channel_name(chan),
2534 ast_channel_uniqueid(chan),
2536 ast_channel_unlock(chan);
2541 static void free_translation(struct ast_channel *clonechan)
2543 if (ast_channel_writetrans(clonechan))
2544 ast_translator_free_path(ast_channel_writetrans(clonechan));
2545 if (ast_channel_readtrans(clonechan))
2546 ast_translator_free_path(ast_channel_readtrans(clonechan));
2547 ast_channel_writetrans_set(clonechan, NULL);
2548 ast_channel_readtrans_set(clonechan, NULL);
2549 if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2550 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2551 ast_format_clear(ast_channel_rawreadformat(clonechan));
2553 struct ast_format tmpfmt;
2554 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2555 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2556 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2560 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2562 struct ast_channel *bridge;
2564 ast_channel_lock(chan);
2565 if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2566 ast_channel_hangupsource_set(chan, source);
2568 bridge = ast_bridged_channel(chan);
2569 ast_channel_unlock(chan);
2571 if (bridge && (force || ast_strlen_zero(ast_channel_hangupsource(bridge)))) {
2572 ast_channel_lock(bridge);
2573 ast_channel_hangupsource_set(chan, source);
2574 ast_channel_unlock(bridge);
2578 static void destroy_hooks(struct ast_channel *chan)
2580 if (ast_channel_audiohooks(chan)) {
2581 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2582 ast_channel_audiohooks_set(chan, NULL);
2585 ast_framehook_list_destroy(chan);
2588 /*! \brief Hangup a channel */
2589 int ast_hangup(struct ast_channel *chan)
2591 char extra_str[64]; /* used for cel logging below */
2594 ast_autoservice_stop(chan);
2596 ast_channel_lock(chan);
2599 * Do the masquerade if someone is setup to masquerade into us.
2601 * NOTE: We must hold the channel lock after testing for a
2602 * pending masquerade and setting the channel as a zombie to
2603 * prevent __ast_channel_masquerade() from setting up a
2604 * masquerade with a dead channel.
2606 while (ast_channel_masq(chan)) {
2607 ast_channel_unlock(chan);
2608 ast_do_masquerade(chan);
2609 ast_channel_lock(chan);
2612 if (ast_channel_masqr(chan)) {
2614 * This channel is one which will be masqueraded into something.
2615 * Mark it as a zombie already so ast_do_masquerade() will know
2618 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2619 destroy_hooks(chan);
2620 ast_channel_unlock(chan);
2624 /* Mark as a zombie so a masquerade cannot be setup on this channel. */
2625 if (!(was_zombie = ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE))) {
2626 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2629 ast_channel_unlock(chan);
2630 ao2_unlink(channels, chan);
2631 ast_channel_lock(chan);
2633 destroy_hooks(chan);
2635 free_translation(chan);
2636 /* Close audio stream */
2637 if (ast_channel_stream(chan)) {
2638 ast_closestream(ast_channel_stream(chan));
2639 ast_channel_stream_set(chan, NULL);
2641 /* Close video stream */
2642 if (ast_channel_vstream(chan)) {
2643 ast_closestream(ast_channel_vstream(chan));
2644 ast_channel_vstream_set(chan, NULL);
2646 if (ast_channel_sched(chan)) {
2647 ast_sched_context_destroy(ast_channel_sched(chan));
2648 ast_channel_sched_set(chan, NULL);
2651 if (ast_channel_generatordata(chan)) { /* Clear any tone stuff remaining */
2652 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2653 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2656 ast_channel_generatordata_set(chan, NULL);
2657 ast_channel_generator_set(chan, NULL);
2659 snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", ast_channel_hangupcause(chan), ast_channel_hangupsource(chan), S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2660 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2662 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2663 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2664 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2665 (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2666 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2669 ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2671 if (ast_channel_tech(chan)->hangup) {
2672 ast_channel_tech(chan)->hangup(chan);
2675 ast_debug(1, "Hanging up zombie '%s'\n", ast_channel_name(chan));
2678 ast_channel_unlock(chan);
2681 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2684 "CallerIDNum: %s\r\n"
2685 "CallerIDName: %s\r\n"
2686 "ConnectedLineNum: %s\r\n"
2687 "ConnectedLineName: %s\r\n"
2689 "Cause-txt: %s\r\n",
2690 ast_channel_name(chan),
2691 ast_channel_uniqueid(chan),
2692 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
2693 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
2694 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
2695 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
2696 ast_channel_hangupcause(chan),
2697 ast_cause2str(ast_channel_hangupcause(chan))
2700 if (ast_channel_cdr(chan) && !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_BRIDGED) &&
2701 !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_POST_DISABLED) &&
2702 (ast_channel_cdr(chan)->disposition != AST_CDR_NULL || ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_DIALED))) {
2703 ast_channel_lock(chan);
2704 ast_cdr_end(ast_channel_cdr(chan));
2705 ast_cdr_detach(ast_channel_cdr(chan));
2706 ast_channel_cdr_set(chan, NULL);
2707 ast_channel_unlock(chan);
2710 ast_channel_unref(chan);
2715 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2719 ast_channel_lock(chan);
2721 /* You can't answer an outbound call */
2722 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2723 ast_channel_unlock(chan);
2727 /* Stop if we're a zombie or need a soft hangup */
2728 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2729 ast_channel_unlock(chan);
2733 ast_channel_unlock(chan);
2735 switch (ast_channel_state(chan)) {
2736 case AST_STATE_RINGING:
2737 case AST_STATE_RING:
2738 ast_channel_lock(chan);
2739 if (ast_channel_tech(chan)->answer) {
2740 res = ast_channel_tech(chan)->answer(chan);
2742 ast_setstate(chan, AST_STATE_UP);
2744 ast_cdr_answer(ast_channel_cdr(chan));
2746 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2747 ast_channel_unlock(chan);
2750 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2751 /* Calling ast_cdr_answer when it it has previously been called
2752 * is essentially a no-op, so it is safe.
2755 ast_cdr_answer(ast_channel_cdr(chan));
2762 ast_indicate(chan, -1);
2767 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2770 enum ast_channel_state old_state;
2772 old_state = ast_channel_state(chan);
2773 if ((res = ast_raw_answer(chan, cdr_answer))) {
2777 switch (old_state) {
2778 case AST_STATE_RINGING:
2779 case AST_STATE_RING:
2780 /* wait for media to start flowing, but don't wait any longer
2781 * than 'delay' or 500 milliseconds, whichever is longer
2784 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2785 struct ast_frame *cur, *new;
2786 int ms = MAX(delay, 500);
2787 unsigned int done = 0;
2789 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2792 ms = ast_waitfor(chan, ms);
2794 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2799 ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", ast_channel_name(chan), MAX(delay, 500));
2802 cur = ast_read(chan);
2803 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2804 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2809 ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2813 if ((new = ast_frisolate(cur)) != cur) {
2817 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2819 /* if a specific delay period was requested, continue
2820 * until that delay has passed. don't stop just because
2821 * incoming media has arrived.
2827 switch (new->frametype) {
2828 /* all of these frametypes qualify as 'media' */
2829 case AST_FRAME_VOICE:
2830 case AST_FRAME_VIDEO:
2831 case AST_FRAME_TEXT:
2832 case AST_FRAME_DTMF_BEGIN:
2833 case AST_FRAME_DTMF_END:
2834 case AST_FRAME_IMAGE:
2835 case AST_FRAME_HTML:
2836 case AST_FRAME_MODEM:
2839 case AST_FRAME_CONTROL:
2841 case AST_FRAME_NULL:
2852 ast_channel_lock(chan);
2853 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2854 ast_queue_frame_head(chan, cur);
2857 ast_channel_unlock(chan);
2868 int ast_answer(struct ast_channel *chan)
2870 return __ast_answer(chan, 0, 1);
2873 void ast_deactivate_generator(struct ast_channel *chan)
2875 ast_channel_lock(chan);
2876 if (ast_channel_generatordata(chan)) {
2877 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2878 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2880 ast_channel_generatordata_set(chan, NULL);
2881 ast_channel_generator_set(chan, NULL);
2882 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2883 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
2884 ast_settimeout(chan, 0, NULL, NULL);
2886 ast_channel_unlock(chan);
2889 static void generator_write_format_change(struct ast_channel *chan)
2891 ast_channel_lock(chan);
2892 if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
2893 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
2895 ast_channel_unlock(chan);
2898 static int generator_force(const void *data)
2900 /* Called if generator doesn't have data */
2903 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2904 struct ast_channel *chan = (struct ast_channel *)data;
2906 ast_channel_lock(chan);
2907 tmp = ast_channel_generatordata(chan);
2908 ast_channel_generatordata_set(chan, NULL);
2909 if (ast_channel_generator(chan))
2910 generate = ast_channel_generator(chan)->generate;
2911 ast_channel_unlock(chan);
2913 if (!tmp || !generate)
2916 res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
2918 ast_channel_generatordata_set(chan, tmp);
2921 ast_debug(1, "Auto-deactivating generator\n");
2922 ast_deactivate_generator(chan);
2928 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2931 void *generatordata = NULL;
2933 ast_channel_lock(chan);
2934 if (ast_channel_generatordata(chan)) {
2935 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2936 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2939 if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
2942 ast_channel_generatordata_set(chan, generatordata);
2944 ast_settimeout(chan, 50, generator_force, chan);
2945 ast_channel_generator_set(chan, gen);
2947 ast_channel_unlock(chan);
2954 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2955 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2958 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2962 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2964 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2965 int *exception, int *outfd, int *ms)
2967 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2968 int *exception, int *outfd, int *ms)
2971 struct timeval start = { 0 , 0 };
2972 struct pollfd *pfds = NULL;
2977 struct timeval now = { 0, 0 };
2978 struct timeval whentohangup = { 0, 0 }, diff;
2979 struct ast_channel *winner = NULL;
2992 if ((sz = n * AST_MAX_FDS + nfds)) {
2993 pfds = alloca(sizeof(*pfds) * sz);
2994 fdmap = alloca(sizeof(*fdmap) * sz);
2996 /* nothing to allocate and no FDs to check */
3000 /* Perform any pending masquerades */
3001 for (x = 0; x < n; x++) {
3002 while (ast_channel_masq(c[x])) {
3003 ast_do_masquerade(c[x]);
3006 ast_channel_lock(c[x]);
3007 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
3008 if (ast_tvzero(whentohangup))
3010 diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
3011 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3012 /* Should already be hungup */
3013 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3014 ast_channel_unlock(c[x]);
3017 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3018 whentohangup = diff;
3020 ast_channel_unlock(c[x]);
3022 /* Wait full interval */
3024 /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3025 if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3026 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
3027 if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
3030 } else if (!ast_tvzero(whentohangup) && rms < 0) {
3031 /* Tiny corner case... call would need to last >24 days */
3035 * Build the pollfd array, putting the channels' fds first,
3036 * followed by individual fds. Order is important because
3037 * individual fd's must have priority over channel fds.
3040 for (x = 0; x < n; x++) {
3041 for (y = 0; y < AST_MAX_FDS; y++) {
3042 fdmap[max].fdno = y; /* fd y is linked to this pfds */
3043 fdmap[max].chan = x; /* channel x is linked to this pfds */
3044 max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3046 CHECK_BLOCKING(c[x]);
3048 /* Add the individual fds */
3049 for (x = 0; x < nfds; x++) {
3050 fdmap[max].chan = -1;
3051 max += ast_add_fd(&pfds[max], fds[x]);
3055 start = ast_tvnow();
3058 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3061 if (kbrms > 600000) {
3064 res = ast_poll(pfds, max, kbrms);
3068 } while (!res && (rms > 0));
3070 res = ast_poll(pfds, max, rms);
3072 for (x = 0; x < n; x++) {
3073 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3075 if (res < 0) { /* Simulate a timeout if we were interrupted */
3076 if (errno != EINTR) {
3081 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
3083 for (x = 0; x < n; x++) {
3084 if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3085 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3086 if (winner == NULL) {
3092 if (res == 0) { /* no fd ready, reset timeout and done */
3093 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
3097 * Then check if any channel or fd has a pending event.
3098 * Remember to check channels first and fds last, as they
3099 * must have priority on setting 'winner'
3101 for (x = 0; x < max; x++) {
3102 res = pfds[x].revents;
3106 if (fdmap[x].chan >= 0) { /* this is a channel */
3107 winner = c[fdmap[x].chan]; /* override previous winners */
3108 if (res & POLLPRI) {
3109 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3111 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3113 ast_channel_fdno_set(winner, fdmap[x].fdno);
3114 } else { /* this is an fd */
3116 *outfd = pfds[x].fd;
3119 *exception = (res & POLLPRI) ? -1 : 0;
3125 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3134 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3136 struct timeval start = { 0 , 0 };
3138 struct epoll_event ev[1];
3139 long diff, rms = *ms;
3140 struct ast_channel *winner = NULL;
3141 struct ast_epoll_data *aed = NULL;
3144 /* See if this channel needs to be masqueraded */
3145 while (ast_channel_masq(chan)) {
3146 ast_do_masquerade(chan);
3149 ast_channel_lock(chan);
3150 /* Figure out their timeout */
3151 if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3152 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow())) < 0) {
3153 /* They should already be hungup! */
3154 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3155 ast_channel_unlock(chan);
3158 /* If this value is smaller then the current one... make it priority */
3164 ast_channel_unlock(chan);
3166 /* Time to make this channel block... */
3167 CHECK_BLOCKING(chan);
3170 start = ast_tvnow();
3173 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3174 res = epoll_wait(ast_channel_epfd(chan), ev, 1, rms);
3177 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
3179 /* Simulate a timeout if we were interrupted */
3181 if (errno != EINTR) {
3187 /* If this channel has a timeout see if it expired */
3188 if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3189 if (ast_tvdiff_ms(ast_tvnow(), *ast_channel_whentohangup(chan)) >= 0) {
3190 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3195 /* No fd ready, reset timeout and be done for now */
3201 /* See what events are pending */
3202 aed = ev[0].data.ptr;
3203 ast_channel_fdno_set(chan, aed->which);
3204 if (ev[0].events & EPOLLPRI) {
3205 ast_set_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3207 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3211 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3220 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3222 struct timeval start = { 0 , 0 };
3224 struct epoll_event ev[25] = { { 0, } };
3225 struct timeval now = { 0, 0 };
3226 long whentohangup = 0, diff = 0, rms = *ms;
3227 struct ast_channel *winner = NULL;
3229 for (i = 0; i < n; i++) {
3230 while (ast_channel_masq(c[i])) {
3231 ast_do_masquerade(c[i]);
3234 ast_channel_lock(c[i]);
3235 if (!ast_tvzero(*ast_channel_whentohangup(c[i]))) {
3236 if (whentohangup == 0) {
3239 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(c[i]), now)) < 0) {
3240 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3241 ast_channel_unlock(c[i]);
3244 if (!whentohangup || whentohangup > diff) {
3245 whentohangup = diff;
3248 ast_channel_unlock(c[i]);
3249 CHECK_BLOCKING(c[i]);
3255 if (*ms >= 0 && *ms < rms) {
3261 start = ast_tvnow();
3264 res = epoll_wait(ast_channel_epfd(c[0]), ev, 25, rms);
3266 for (i = 0; i < n; i++) {
3267 ast_clear_flag(ast_channel_flags(c[i]), AST_FLAG_BLOCKING);
3271 if (errno != EINTR) {
3279 for (i = 0; i < n; i++) {
3280 if (!ast_tvzero(*ast_channel_whentohangup(c[i])) && ast_tvdiff_ms(now, *ast_channel_whentohangup(c[i])) >= 0) {
3281 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3294 for (i = 0; i < res; i++) {
3295 struct ast_epoll_data *aed = ev[i].data.ptr;
3297 if (!ev[i].events || !aed) {
3302 if (ev[i].events & EPOLLPRI) {
3303 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3305 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3307 ast_channel_fdno_set(winner, aed->which);
3311 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3320 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3321 int *exception, int *outfd, int *ms)
3323 /* Clear all provided values in one place. */
3331 /* If no epoll file descriptor is available resort to classic nandfds */
3332 if (!n || nfds || ast_channel_epfd(c[0]) == -1) {
3333 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3334 } else if (!nfds && n == 1) {
3335 return ast_waitfor_nandfds_simple(c[0], ms);
3337 return ast_waitfor_nandfds_complex(c, n, ms);
3342 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3344 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3347 int ast_waitfor(struct ast_channel *c, int ms)
3349 int oldms = ms; /* -1 if no timeout */
3351 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3352 if ((ms < 0) && (oldms < 0)) {
3358 /* XXX never to be called with ms = -1 */
3359 int ast_waitfordigit(struct ast_channel *c, int ms)