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>
27 <support_level>core</support_level>
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34 #include "asterisk/_private.h"
40 #include "asterisk/paths.h" /* use ast_config_AST_SYSTEM_NAME */
42 #include "asterisk/pbx.h"
43 #include "asterisk/frame.h"
44 #include "asterisk/mod_format.h"
45 #include "asterisk/sched.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/musiconhold.h"
48 #include "asterisk/say.h"
49 #include "asterisk/file.h"
50 #include "asterisk/cli.h"
51 #include "asterisk/translate.h"
52 #include "asterisk/manager.h"
53 #include "asterisk/cel.h"
54 #include "asterisk/chanvars.h"
55 #include "asterisk/linkedlists.h"
56 #include "asterisk/indications.h"
57 #include "asterisk/monitor.h"
58 #include "asterisk/causes.h"
59 #include "asterisk/callerid.h"
60 #include "asterisk/utils.h"
61 #include "asterisk/lock.h"
62 #include "asterisk/app.h"
63 #include "asterisk/transcap.h"
64 #include "asterisk/devicestate.h"
65 #include "asterisk/threadstorage.h"
66 #include "asterisk/slinfactory.h"
67 #include "asterisk/audiohook.h"
68 #include "asterisk/framehook.h"
69 #include "asterisk/timing.h"
70 #include "asterisk/autochan.h"
71 #include "asterisk/stringfields.h"
72 #include "asterisk/global_datastores.h"
73 #include "asterisk/data.h"
74 #include "asterisk/channel_internal.h"
77 #include <sys/epoll.h>
80 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
83 #endif /* defined(HAVE_PRI) */
84 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
86 struct ast_epoll_data {
87 struct ast_channel *chan;
91 /* uncomment if you have problems with 'monitoring' synchronized files */
93 #define MONITOR_CONSTANT_DELAY
94 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
97 /*! \brief Prevent new channel allocation if shutting down. */
98 static int shutting_down;
100 static int uniqueint;
101 static int chancount;
103 unsigned long global_fin, global_fout;
105 AST_THREADSTORAGE(state2str_threadbuf);
106 #define STATE2STR_BUFSIZE 32
108 /*! Default amount of time to use when emulating a digit as a begin and end
110 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
112 /*! Minimum amount of time between the end of the last digit and the beginning
113 * of a new one - 45ms */
114 #define AST_MIN_DTMF_GAP 45
116 /*! \brief List of channel drivers */
118 const struct ast_channel_tech *tech;
119 AST_LIST_ENTRY(chanlist) list;
123 /*! \brief Structure to hold channel context backtrace data */
124 struct ast_chan_trace_data {
126 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
129 /*! \brief Structure to save contexts where an ast_chan has been into */
130 struct ast_chan_trace {
131 char context[AST_MAX_CONTEXT];
132 char exten[AST_MAX_EXTENSION];
134 AST_LIST_ENTRY(ast_chan_trace) entry;
138 /*! \brief the list of registered channel types */
139 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
142 #define NUM_CHANNEL_BUCKETS 61
144 #define NUM_CHANNEL_BUCKETS 1567
147 /*! \brief All active channels on the system */
148 static struct ao2_container *channels;
150 /*! \brief map AST_CAUSE's to readable string representations
154 static const struct {
159 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
160 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
161 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
162 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
163 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
164 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
165 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
166 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
167 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
168 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
169 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
170 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
171 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
172 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
173 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
174 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
175 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
176 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
177 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
178 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
179 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
180 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
181 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
182 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
183 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
184 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
185 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
186 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
187 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
188 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
189 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
190 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
191 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
192 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
193 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
194 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
195 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
196 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
197 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
198 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
199 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
200 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
201 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
202 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
205 struct ast_variable *ast_channeltype_list(void)
208 struct ast_variable *var = NULL, *prev = NULL;
210 AST_RWLIST_RDLOCK(&backends);
211 AST_RWLIST_TRAVERSE(&backends, cl, list) {
213 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
216 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
220 AST_RWLIST_UNLOCK(&backends);
225 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
226 static const char *party_number_ton2str(int ton)
228 #if defined(HAVE_PRI)
229 switch ((ton >> 4) & 0x07) {
230 case PRI_TON_INTERNATIONAL:
231 return "International";
232 case PRI_TON_NATIONAL:
234 case PRI_TON_NET_SPECIFIC:
235 return "Network Specific";
236 case PRI_TON_SUBSCRIBER:
238 case PRI_TON_ABBREVIATED:
239 return "Abbreviated";
240 case PRI_TON_RESERVED:
242 case PRI_TON_UNKNOWN:
246 #endif /* defined(HAVE_PRI) */
249 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
251 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
252 static const char *party_number_plan2str(int plan)
254 #if defined(HAVE_PRI)
255 switch (plan & 0x0F) {
257 case PRI_NPI_UNKNOWN:
259 case PRI_NPI_E163_E164:
260 return "Public (E.163/E.164)";
262 return "Data (X.121)";
264 return "Telex (F.69)";
265 case PRI_NPI_NATIONAL:
266 return "National Standard";
267 case PRI_NPI_PRIVATE:
269 case PRI_NPI_RESERVED:
272 #endif /* defined(HAVE_PRI) */
275 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
277 /*! \brief Show channel types - CLI command */
278 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
280 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
286 e->command = "core show channeltypes";
288 "Usage: core show channeltypes\n"
289 " Lists available channel types registered in your\n"
290 " Asterisk server.\n";
297 return CLI_SHOWUSAGE;
299 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
300 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
302 AST_RWLIST_RDLOCK(&backends);
303 AST_RWLIST_TRAVERSE(&backends, cl, list) {
304 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
305 (cl->tech->devicestate) ? "yes" : "no",
306 (cl->tech->indicate) ? "yes" : "no",
307 (cl->tech->transfer) ? "yes" : "no");
310 AST_RWLIST_UNLOCK(&backends);
312 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
319 static char *complete_channeltypes(struct ast_cli_args *a)
329 wordlen = strlen(a->word);
331 AST_RWLIST_RDLOCK(&backends);
332 AST_RWLIST_TRAVERSE(&backends, cl, list) {
333 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
334 ret = ast_strdup(cl->tech->type);
338 AST_RWLIST_UNLOCK(&backends);
343 /*! \brief Show details about a channel driver - CLI command */
344 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
346 struct chanlist *cl = NULL;
351 e->command = "core show channeltype";
353 "Usage: core show channeltype <name>\n"
354 " Show details about the specified channel type, <name>.\n";
357 return complete_channeltypes(a);
361 return CLI_SHOWUSAGE;
363 AST_RWLIST_RDLOCK(&backends);
365 AST_RWLIST_TRAVERSE(&backends, cl, list) {
366 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
372 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
373 AST_RWLIST_UNLOCK(&backends);
378 "-- Info about channel driver: %s --\n"
379 " Device State: %s\n"
382 " Capabilities: %s\n"
386 " Image Support: %s\n"
387 " Text Support: %s\n",
389 (cl->tech->devicestate) ? "yes" : "no",
390 (cl->tech->indicate) ? "yes" : "no",
391 (cl->tech->transfer) ? "yes" : "no",
392 ast_getformatname_multiple(buf, sizeof(buf), cl->tech->capabilities),
393 (cl->tech->send_digit_begin) ? "yes" : "no",
394 (cl->tech->send_digit_end) ? "yes" : "no",
395 (cl->tech->send_html) ? "yes" : "no",
396 (cl->tech->send_image) ? "yes" : "no",
397 (cl->tech->send_text) ? "yes" : "no"
401 AST_RWLIST_UNLOCK(&backends);
406 static struct ast_cli_entry cli_channel[] = {
407 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
408 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
411 static struct ast_frame *kill_read(struct ast_channel *chan)
413 /* Hangup channel. */
417 static struct ast_frame *kill_exception(struct ast_channel *chan)
419 /* Hangup channel. */
423 static int kill_write(struct ast_channel *chan, struct ast_frame *frame)
425 /* Hangup channel. */
429 static int kill_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
431 /* No problem fixing up the channel. */
435 static int kill_hangup(struct ast_channel *chan)
437 ast_channel_tech_pvt_set(chan, NULL);
442 * \brief Kill the channel channel driver technology descriptor.
445 * The purpose of this channel technology is to encourage the
446 * channel to hangup as quickly as possible.
448 * \note Used by DTMF atxfer and zombie channels.
450 const struct ast_channel_tech ast_kill_tech = {
452 .description = "Kill channel (should not see this)",
454 .exception = kill_exception,
457 .hangup = kill_hangup,
461 /*! \brief Destructor for the channel trace datastore */
462 static void ast_chan_trace_destroy_cb(void *data)
464 struct ast_chan_trace *trace;
465 struct ast_chan_trace_data *traced = data;
466 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
472 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
473 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
475 .destroy = ast_chan_trace_destroy_cb
478 /*! \brief Put the channel backtrace in a string */
479 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
482 struct ast_chan_trace *trace;
483 struct ast_chan_trace_data *traced;
484 struct ast_datastore *store;
486 ast_channel_lock(chan);
487 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
489 ast_channel_unlock(chan);
492 traced = store->data;
494 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
495 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
496 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
502 ast_channel_unlock(chan);
506 /* !\brief Whether or not context tracing is enabled */
507 int ast_channel_trace_is_enabled(struct ast_channel *chan)
509 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
512 return ((struct ast_chan_trace_data *)store->data)->enabled;
515 /*! \brief Update the context backtrace data if tracing is enabled */
516 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
518 struct ast_chan_trace *trace;
519 if (!traced->enabled)
521 /* If the last saved context does not match the current one
522 OR we have not saved any context so far, then save the current context */
523 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan))) ||
524 (AST_LIST_EMPTY(&traced->trace))) {
525 /* Just do some debug logging */
526 if (AST_LIST_EMPTY(&traced->trace))
527 ast_debug(1, "Setting initial trace context to %s\n", ast_channel_context(chan));
529 ast_debug(1, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan));
530 /* alloc or bail out */
531 trace = ast_malloc(sizeof(*trace));
534 /* save the current location and store it in the trace list */
535 ast_copy_string(trace->context, ast_channel_context(chan), sizeof(trace->context));
536 ast_copy_string(trace->exten, ast_channel_exten(chan), sizeof(trace->exten));
537 trace->priority = ast_channel_priority(chan);
538 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
543 /*! \brief Update the context backtrace if tracing is enabled */
544 int ast_channel_trace_update(struct ast_channel *chan)
546 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
549 return ast_channel_trace_data_update(chan, store->data);
552 /*! \brief Enable context tracing in the channel */
553 int ast_channel_trace_enable(struct ast_channel *chan)
555 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
556 struct ast_chan_trace_data *traced;
558 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
561 traced = ast_calloc(1, sizeof(*traced));
563 ast_datastore_free(store);
566 store->data = traced;
567 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
568 ast_channel_datastore_add(chan, store);
570 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
571 ast_channel_trace_data_update(chan, store->data);
575 /*! \brief Disable context tracing in the channel */
576 int ast_channel_trace_disable(struct ast_channel *chan)
578 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
581 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
584 #endif /* CHANNEL_TRACE */
586 /*! \brief Checks to see if a channel is needing hang up */
587 int ast_check_hangup(struct ast_channel *chan)
589 if (ast_channel_softhangup_internal_flag(chan)) /* yes if soft hangup flag set */
591 if (ast_tvzero(*ast_channel_whentohangup(chan))) /* no if no hangup scheduled */
593 if (ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()) > 0) /* no if hangup time has not come yet. */
595 ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()));
596 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT); /* record event */
600 int ast_check_hangup_locked(struct ast_channel *chan)
603 ast_channel_lock(chan);
604 res = ast_check_hangup(chan);
605 ast_channel_unlock(chan);
609 void ast_channel_softhangup_withcause_locked(struct ast_channel *chan, int causecode)
611 ast_channel_lock(chan);
614 ast_debug(1, "Setting hangupcause of channel %s to %d (is %d now)\n",
615 ast_channel_name(chan), causecode, ast_channel_hangupcause(chan));
617 ast_channel_hangupcause_set(chan, causecode);
620 ast_softhangup_nolock(chan, AST_SOFTHANGUP_EXPLICIT);
622 ast_channel_unlock(chan);
625 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
627 struct ast_channel *chan = obj;
629 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
634 void ast_begin_shutdown(int hangup)
639 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
643 /*! \brief returns number of active/allocated channels */
644 int ast_active_channels(void)
646 return channels ? ao2_container_count(channels) : 0;
649 int ast_undestroyed_channels(void)
651 return ast_atomic_fetchadd_int(&chancount, 0);
654 /*! \brief Cancel a shutdown in progress */
655 void ast_cancel_shutdown(void)
660 /*! \brief Returns non-zero if Asterisk is being shut down */
661 int ast_shutting_down(void)
663 return shutting_down;
666 /*! \brief Set when to hangup channel */
667 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
669 if (ast_tvzero(offset)) {
670 ast_channel_whentohangup_set(chan, &offset);
672 struct timeval tv = ast_tvadd(offset, ast_tvnow());
673 ast_channel_whentohangup_set(chan, &tv);
675 ast_queue_frame(chan, &ast_null_frame);
679 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
681 struct timeval when = { offset, };
682 ast_channel_setwhentohangup_tv(chan, when);
685 /*! \brief Compare a offset with when to hangup channel */
686 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
688 struct timeval whentohangup;
690 if (ast_tvzero(*ast_channel_whentohangup(chan)))
691 return ast_tvzero(offset) ? 0 : -1;
693 if (ast_tvzero(offset))
696 whentohangup = ast_tvadd(offset, ast_tvnow());
698 return ast_tvdiff_ms(whentohangup, *ast_channel_whentohangup(chan));
701 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
703 struct timeval when = { offset, };
704 return ast_channel_cmpwhentohangup_tv(chan, when);
707 /*! \brief Register a new telephony channel in Asterisk */
708 int ast_channel_register(const struct ast_channel_tech *tech)
710 struct chanlist *chan;
712 AST_RWLIST_WRLOCK(&backends);
714 AST_RWLIST_TRAVERSE(&backends, chan, list) {
715 if (!strcasecmp(tech->type, chan->tech->type)) {
716 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
717 AST_RWLIST_UNLOCK(&backends);
722 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
723 AST_RWLIST_UNLOCK(&backends);
727 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
729 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
731 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
733 AST_RWLIST_UNLOCK(&backends);
738 /*! \brief Unregister channel driver */
739 void ast_channel_unregister(const struct ast_channel_tech *tech)
741 struct chanlist *chan;
743 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
745 AST_RWLIST_WRLOCK(&backends);
747 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
748 if (chan->tech == tech) {
749 AST_LIST_REMOVE_CURRENT(list);
751 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
755 AST_LIST_TRAVERSE_SAFE_END;
757 AST_RWLIST_UNLOCK(&backends);
760 /*! \brief Get handle to channel driver based on name */
761 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
763 struct chanlist *chanls;
764 const struct ast_channel_tech *ret = NULL;
766 AST_RWLIST_RDLOCK(&backends);
768 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
769 if (!strcasecmp(name, chanls->tech->type)) {
775 AST_RWLIST_UNLOCK(&backends);
780 /*! \brief Gives the string form of a given hangup cause */
781 const char *ast_cause2str(int cause)
785 for (x = 0; x < ARRAY_LEN(causes); x++) {
786 if (causes[x].cause == cause)
787 return causes[x].desc;
793 /*! \brief Convert a symbolic hangup cause to number */
794 int ast_str2cause(const char *name)
798 for (x = 0; x < ARRAY_LEN(causes); x++)
799 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
800 return causes[x].cause;
805 /*! \brief Gives the string form of a given channel state.
806 \note This function is not reentrant.
808 const char *ast_state2str(enum ast_channel_state state)
815 case AST_STATE_RESERVED:
817 case AST_STATE_OFFHOOK:
819 case AST_STATE_DIALING:
823 case AST_STATE_RINGING:
829 case AST_STATE_DIALING_OFFHOOK:
830 return "Dialing Offhook";
831 case AST_STATE_PRERING:
834 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
836 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
841 /*! \brief Gives the string form of a given transfer capability */
842 char *ast_transfercapability2str(int transfercapability)
844 switch (transfercapability) {
845 case AST_TRANS_CAP_SPEECH:
847 case AST_TRANS_CAP_DIGITAL:
849 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
850 return "RESTRICTED_DIGITAL";
851 case AST_TRANS_CAP_3_1K_AUDIO:
853 case AST_TRANS_CAP_DIGITAL_W_TONES:
854 return "DIGITAL_W_TONES";
855 case AST_TRANS_CAP_VIDEO:
862 /*! \brief Pick the best audio codec */
863 struct ast_format *ast_best_codec(struct ast_format_cap *cap, struct ast_format *result)
865 /* This just our opinion, expressed in code. We are asked to choose
866 the best codec to use, given no information */
867 static const enum ast_format_id prefs[] =
869 /*! Okay, ulaw is used by all telephony equipment, so start with it */
871 /*! Unless of course, you're a silly European, so then prefer ALAW */
877 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
879 /*! Okay, well, signed linear is easy to translate into other stuff */
880 AST_FORMAT_SLINEAR192,
881 AST_FORMAT_SLINEAR96,
882 AST_FORMAT_SLINEAR48,
883 AST_FORMAT_SLINEAR44,
884 AST_FORMAT_SLINEAR32,
885 AST_FORMAT_SLINEAR24,
886 AST_FORMAT_SLINEAR16,
887 AST_FORMAT_SLINEAR12,
889 /*! G.726 is standard ADPCM, in RFC3551 packing order */
891 /*! G.726 is standard ADPCM, in AAL2 packing order */
892 AST_FORMAT_G726_AAL2,
893 /*! ADPCM has great sound quality and is still pretty easy to translate */
895 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
896 translate and sounds pretty good */
898 /*! iLBC is not too bad */
900 /*! Speex is free, but computationally more expensive than GSM */
904 /*! SILK is pretty awesome. */
906 /*! CELT supports crazy high sample rates */
908 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
911 /*! G.729a is faster than 723 and slightly less expensive */
913 /*! Down to G.723.1 which is proprietary but at least designed for voice */
919 /* Find the first preferred codec in the format given */
920 for (x = 0; x < ARRAY_LEN(prefs); x++) {
921 if (ast_format_cap_best_byid(cap, prefs[x], result)) {
926 ast_format_clear(result);
927 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
932 static const struct ast_channel_tech null_tech = {
934 .description = "Null channel (should not see this)",
937 static void ast_channel_destructor(void *obj);
938 static void ast_dummy_channel_destructor(void *obj);
940 /*! \brief Create a new channel structure */
941 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
942 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
943 const char *acctcode, const char *exten, const char *context,
944 const char *linkedid, const int amaflag, const char *file, int line,
945 const char *function, const char *name_fmt, va_list ap)
947 struct ast_channel *tmp;
948 struct varshead *headp;
949 char *tech = "", *tech2 = NULL;
950 struct ast_format_cap *nativeformats;
951 struct ast_sched_context *schedctx;
952 struct ast_timer *timer;
954 /* If shutting down, don't allocate any new channels */
955 if (ast_shutting_down()) {
956 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
960 if (!(tmp = ast_channel_internal_alloc(ast_channel_destructor))) {
961 /* Channel structure allocation failure. */
964 if (!(nativeformats = ast_format_cap_alloc())) {
966 /* format capabilities structure allocation failure */
969 ast_channel_nativeformats_set(tmp, nativeformats);
972 * Init file descriptors to unopened state so
973 * the destructor can know not to close them.
975 ast_channel_timingfd_set(tmp, -1);
976 ast_channel_internal_alertpipe_clear(tmp);
977 ast_channel_internal_fd_clear_all(tmp);
980 ast_channel_epfd(tmp) = epoll_create(25);
983 if (!(schedctx = ast_sched_context_create())) {
984 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
985 return ast_channel_unref(tmp);
987 ast_channel_sched_set(tmp, schedctx);
989 ast_party_dialed_init(ast_channel_dialed(tmp));
990 ast_party_caller_init(ast_channel_caller(tmp));
991 ast_party_connected_line_init(ast_channel_connected(tmp));
992 ast_party_redirecting_init(ast_channel_redirecting(tmp));
995 ast_channel_caller(tmp)->id.name.valid = 1;
996 ast_channel_caller(tmp)->id.name.str = ast_strdup(cid_name);
997 if (!ast_channel_caller(tmp)->id.name.str) {
998 return ast_channel_unref(tmp);
1002 ast_channel_caller(tmp)->id.number.valid = 1;
1003 ast_channel_caller(tmp)->id.number.str = ast_strdup(cid_num);
1004 if (!ast_channel_caller(tmp)->id.number.str) {
1005 return ast_channel_unref(tmp);
1009 if ((timer = ast_timer_open())) {
1010 ast_channel_timer_set(tmp, timer);
1011 if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
1014 ast_channel_timingfd_set(tmp, ast_timer_fd(ast_channel_timer(tmp)));
1018 * This is the last place the channel constructor can fail.
1020 * The destructor takes advantage of this fact to ensure that the
1021 * AST_CEL_CHANNEL_END is not posted if we have not posted the
1022 * AST_CEL_CHANNEL_START yet.
1025 if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
1026 return ast_channel_unref(tmp);
1029 /* Always watch the alertpipe */
1030 ast_channel_set_fd(tmp, AST_ALERT_FD, ast_channel_internal_alert_readfd(tmp));
1031 /* And timing pipe */
1032 ast_channel_set_fd(tmp, AST_TIMING_FD, ast_channel_timingfd(tmp));
1035 ast_channel_state_set(tmp, state);
1037 ast_channel_streamid_set(tmp, -1);
1039 ast_channel_fin_set(tmp, global_fin);
1040 ast_channel_fout_set(tmp, global_fout);
1042 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1043 ast_channel_uniqueid_build(tmp, "%li.%d", (long) time(NULL),
1044 ast_atomic_fetchadd_int(&uniqueint, 1));
1046 ast_channel_uniqueid_build(tmp, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
1047 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1050 if (!ast_strlen_zero(linkedid)) {
1051 ast_channel_linkedid_set(tmp, linkedid);
1053 ast_channel_linkedid_set(tmp, ast_channel_uniqueid(tmp));
1056 if (!ast_strlen_zero(name_fmt)) {
1057 char *slash, *slash2;
1058 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1059 * And they all use slightly different formats for their name string.
1060 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1061 * This means, that the stringfields must have a routine that takes the va_lists directly, and
1062 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1063 * This new function was written so this can be accomplished.
1065 ast_channel_name_build_va(tmp, name_fmt, ap);
1066 tech = ast_strdupa(ast_channel_name(tmp));
1067 if ((slash = strchr(tech, '/'))) {
1068 if ((slash2 = strchr(slash + 1, '/'))) {
1076 * Start the string with '-' so it becomes an empty string
1077 * in the destructor.
1079 ast_channel_name_set(tmp, "-**Unknown**");
1082 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1084 /* These 4 variables need to be set up for the cdr_init() to work right */
1086 ast_channel_amaflags_set(tmp, amaflag);
1088 ast_channel_amaflags_set(tmp, ast_default_amaflags);
1091 if (!ast_strlen_zero(acctcode))
1092 ast_channel_accountcode_set(tmp, acctcode);
1094 ast_channel_accountcode_set(tmp, ast_default_accountcode);
1096 ast_channel_context_set(tmp, S_OR(context, "default"));
1097 ast_channel_exten_set(tmp, S_OR(exten, "s"));
1098 ast_channel_priority_set(tmp, 1);
1100 ast_channel_cdr_set(tmp, ast_cdr_alloc());
1101 ast_cdr_init(ast_channel_cdr(tmp), tmp);
1102 ast_cdr_start(ast_channel_cdr(tmp));
1104 ast_atomic_fetchadd_int(&chancount, +1);
1105 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1107 headp = ast_channel_varshead(tmp);
1108 AST_LIST_HEAD_INIT_NOLOCK(headp);
1110 ast_pbx_hangup_handler_init(tmp);
1111 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1113 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_autochans(tmp));
1115 ast_channel_language_set(tmp, defaultlanguage);
1117 ast_channel_tech_set(tmp, &null_tech);
1119 ao2_link(channels, tmp);
1122 * And now, since the channel structure is built, and has its name, let's
1123 * call the manager event generator with this Newchannel event. This is the
1124 * proper and correct place to make this call, but you sure do have to pass
1125 * a lot of data into this func to do it here!
1127 if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1128 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1130 "ChannelState: %d\r\n"
1131 "ChannelStateDesc: %s\r\n"
1132 "CallerIDNum: %s\r\n"
1133 "CallerIDName: %s\r\n"
1134 "AccountCode: %s\r\n"
1138 ast_channel_name(tmp),
1140 ast_state2str(state),
1143 ast_channel_accountcode(tmp),
1146 ast_channel_uniqueid(tmp));
1149 ast_channel_internal_finalize(tmp);
1153 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1154 const char *cid_name, const char *acctcode,
1155 const char *exten, const char *context,
1156 const char *linkedid, const int amaflag,
1157 const char *file, int line, const char *function,
1158 const char *name_fmt, ...)
1161 struct ast_channel *result;
1163 va_start(ap, name_fmt);
1164 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1165 linkedid, amaflag, file, line, function, name_fmt, ap);
1171 /* only do the minimum amount of work needed here to make a channel
1172 * structure that can be used to expand channel vars */
1173 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1174 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1176 struct ast_channel *ast_dummy_channel_alloc(void)
1179 struct ast_channel *tmp;
1180 struct varshead *headp;
1182 if (!(tmp = ast_channel_internal_alloc(ast_dummy_channel_destructor))) {
1183 /* Dummy channel structure allocation failure. */
1187 ast_pbx_hangup_handler_init(tmp);
1188 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1190 headp = ast_channel_varshead(tmp);
1191 AST_LIST_HEAD_INIT_NOLOCK(headp);
1196 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1198 struct ast_frame *f;
1199 struct ast_frame *cur;
1200 unsigned int new_frames = 0;
1201 unsigned int new_voice_frames = 0;
1202 unsigned int queued_frames = 0;
1203 unsigned int queued_voice_frames = 0;
1204 AST_LIST_HEAD_NOLOCK(,ast_frame) frames;
1206 ast_channel_lock(chan);
1209 * Check the last frame on the queue if we are queuing the new
1212 cur = AST_LIST_LAST(ast_channel_readq(chan));
1213 if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1214 switch (cur->subclass.integer) {
1215 case AST_CONTROL_END_OF_Q:
1216 if (fin->frametype == AST_FRAME_CONTROL
1217 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1219 * Destroy the end-of-Q marker frame so we can queue the hangup
1220 * frame in its place.
1222 AST_LIST_REMOVE(ast_channel_readq(chan), cur, frame_list);
1226 * This has degenerated to a normal queue append anyway. Since
1227 * we just destroyed the last frame in the queue we must make
1228 * sure that "after" is NULL or bad things will happen.
1234 case AST_CONTROL_HANGUP:
1235 /* Don't queue anything. */
1236 ast_channel_unlock(chan);
1243 /* Build copies of all the new frames and count them */
1244 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1245 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1246 if (!(f = ast_frdup(cur))) {
1247 if (AST_LIST_FIRST(&frames)) {
1248 ast_frfree(AST_LIST_FIRST(&frames));
1250 ast_channel_unlock(chan);
1254 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1256 if (f->frametype == AST_FRAME_VOICE) {
1261 /* Count how many frames exist on the queue */
1262 AST_LIST_TRAVERSE(ast_channel_readq(chan), cur, frame_list) {
1264 if (cur->frametype == AST_FRAME_VOICE) {
1265 queued_voice_frames++;
1269 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1271 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1272 AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), cur, frame_list) {
1273 /* Save the most recent frame */
1274 if (!AST_LIST_NEXT(cur, frame_list)) {
1276 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1280 AST_LIST_REMOVE_CURRENT(frame_list);
1284 AST_LIST_TRAVERSE_SAFE_END;
1288 AST_LIST_INSERT_LIST_AFTER(ast_channel_readq(chan), &frames, after, frame_list);
1291 AST_LIST_APPEND_LIST(&frames, ast_channel_readq(chan), frame_list);
1292 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_readq(chan));
1294 AST_LIST_APPEND_LIST(ast_channel_readq(chan), &frames, frame_list);
1297 if (ast_channel_alert_writable(chan)) {
1298 if (ast_channel_alert_write(chan)) {
1299 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1300 ast_channel_name(chan), queued_frames, strerror(errno));
1302 } else if (ast_channel_timingfd(chan) > -1) {
1303 ast_timer_enable_continuous(ast_channel_timer(chan));
1304 } else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
1305 pthread_kill(ast_channel_blocker(chan), SIGURG);
1308 ast_channel_unlock(chan);
1313 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1315 return __ast_queue_frame(chan, fin, 0, NULL);
1318 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1320 return __ast_queue_frame(chan, fin, 1, NULL);
1323 /*! \brief Queue a hangup frame for channel */
1324 int ast_queue_hangup(struct ast_channel *chan)
1326 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1329 /* Yeah, let's not change a lock-critical value without locking */
1330 ast_channel_lock(chan);
1331 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1333 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1336 ast_channel_name(chan),
1337 ast_channel_uniqueid(chan));
1339 res = ast_queue_frame(chan, &f);
1340 ast_channel_unlock(chan);
1344 /*! \brief Queue a hangup frame for channel */
1345 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1347 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1351 f.data.uint32 = cause;
1354 /* Yeah, let's not change a lock-critical value without locking */
1355 ast_channel_lock(chan);
1356 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1358 f.data.uint32 = ast_channel_hangupcause(chan);
1361 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1365 ast_channel_name(chan),
1366 ast_channel_uniqueid(chan),
1369 res = ast_queue_frame(chan, &f);
1370 ast_channel_unlock(chan);
1374 /*! \brief Queue a control frame */
1375 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1377 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1378 return ast_queue_frame(chan, &f);
1381 /*! \brief Queue a control frame with payload */
1382 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1383 const void *data, size_t datalen)
1385 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1386 return ast_queue_frame(chan, &f);
1389 /*! \brief Set defer DTMF flag on channel */
1390 int ast_channel_defer_dtmf(struct ast_channel *chan)
1395 pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1396 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1401 /*! \brief Unset defer DTMF flag on channel */
1402 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1405 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1408 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1409 void *data, int ao2_flags)
1411 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1414 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1416 struct ast_channel *chan = obj;
1417 const char *name = arg;
1418 size_t name_len = *(size_t *) data;
1419 int ret = CMP_MATCH;
1421 if (ast_strlen_zero(name)) {
1422 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1426 ast_channel_lock(chan);
1427 if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1428 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1429 ret = 0; /* name match failed, keep looking */
1431 ast_channel_unlock(chan);
1436 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1438 struct ast_channel *chan = obj;
1439 char *context = arg;
1441 int ret = CMP_MATCH;
1443 if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1444 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1448 ast_channel_lock(chan);
1449 if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1450 ret = 0; /* Context match failed, continue */
1451 } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1452 ret = 0; /* Extension match failed, continue */
1454 ast_channel_unlock(chan);
1459 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1461 struct ast_channel *chan = obj;
1462 char *uniqueid = arg;
1463 size_t id_len = *(size_t *) data;
1464 int ret = CMP_MATCH;
1466 if (ast_strlen_zero(uniqueid)) {
1467 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1471 ast_channel_lock(chan);
1472 if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1473 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1474 ret = 0; /* uniqueid match failed, keep looking */
1476 ast_channel_unlock(chan);
1481 struct ast_channel_iterator {
1482 /* storage for non-dynamically allocated iterator */
1483 struct ao2_iterator simple_iterator;
1484 /* pointer to the actual iterator (simple_iterator or a dynamically
1485 * allocated iterator)
1487 struct ao2_iterator *active_iterator;
1490 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1492 ao2_iterator_destroy(i->active_iterator);
1498 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1500 struct ast_channel_iterator *i;
1501 char *l_exten = (char *) exten;
1502 char *l_context = (char *) context;
1504 if (!(i = ast_calloc(1, sizeof(*i)))) {
1508 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1509 l_context, l_exten, OBJ_MULTIPLE);
1510 if (!i->active_iterator) {
1518 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1520 struct ast_channel_iterator *i;
1521 char *l_name = (char *) name;
1523 if (!(i = ast_calloc(1, sizeof(*i)))) {
1527 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1529 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1530 if (!i->active_iterator) {
1538 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1540 struct ast_channel_iterator *i;
1542 if (!(i = ast_calloc(1, sizeof(*i)))) {
1546 i->simple_iterator = ao2_iterator_init(channels, 0);
1547 i->active_iterator = &i->simple_iterator;
1552 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1554 return ao2_iterator_next(i->active_iterator);
1557 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1558 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1560 ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1564 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1566 struct ast_channel *chan;
1567 char *l_name = (char *) name;
1569 chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1570 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1575 if (ast_strlen_zero(l_name)) {
1576 /* We didn't have a name to search for so quit. */
1580 /* Now try a search for uniqueid. */
1581 return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1584 struct ast_channel *ast_channel_get_by_name(const char *name)
1586 return ast_channel_get_by_name_prefix(name, 0);
1589 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1591 char *l_exten = (char *) exten;
1592 char *l_context = (char *) context;
1594 return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1597 int ast_is_deferrable_frame(const struct ast_frame *frame)
1599 /* Do not add a default entry in this switch statement. Each new
1600 * frame type should be addressed directly as to whether it should
1601 * be queued up or not.
1603 switch (frame->frametype) {
1604 case AST_FRAME_CONTROL:
1605 case AST_FRAME_TEXT:
1606 case AST_FRAME_IMAGE:
1607 case AST_FRAME_HTML:
1610 case AST_FRAME_DTMF_END:
1611 case AST_FRAME_DTMF_BEGIN:
1612 case AST_FRAME_VOICE:
1613 case AST_FRAME_VIDEO:
1614 case AST_FRAME_NULL:
1617 case AST_FRAME_MODEM:
1623 /*! \brief Wait, look for hangups and condition arg */
1624 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1626 struct ast_frame *f;
1627 struct ast_silence_generator *silgen = NULL;
1629 AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1631 AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1633 /* If no other generator is present, start silencegen while waiting */
1634 if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1635 silgen = ast_channel_start_silence_generator(chan);
1639 struct ast_frame *dup_f = NULL;
1640 if (cond && ((*cond)(data) == 0)) {
1643 ms = ast_waitfor(chan, ms);
1655 if (!ast_is_deferrable_frame(f)) {
1660 if ((dup_f = ast_frisolate(f))) {
1664 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1669 /* stop silgen if present */
1671 ast_channel_stop_silence_generator(chan, silgen);
1674 /* We need to free all the deferred frames, but we only need to
1675 * queue the deferred frames if there was no error and no
1676 * hangup was received
1678 ast_channel_lock(chan);
1679 while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1681 ast_queue_frame_head(chan, f);
1685 ast_channel_unlock(chan);
1690 /*! \brief Wait, look for hangups */
1691 int ast_safe_sleep(struct ast_channel *chan, int ms)
1693 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1696 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1698 /* Safe, even if already unlinked. */
1699 ao2_unlink(channels, chan);
1700 return ast_channel_unref(chan);
1703 void ast_party_name_init(struct ast_party_name *init)
1706 init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1707 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1711 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1714 /* Don't copy to self */
1718 ast_free(dest->str);
1719 dest->str = ast_strdup(src->str);
1720 dest->char_set = src->char_set;
1721 dest->presentation = src->presentation;
1722 dest->valid = src->valid;
1725 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1728 init->char_set = guide->char_set;
1729 init->presentation = guide->presentation;
1730 init->valid = guide->valid;
1733 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1736 /* Don't set to self */
1740 if (src->str && src->str != dest->str) {
1741 ast_free(dest->str);
1742 dest->str = ast_strdup(src->str);
1745 dest->char_set = src->char_set;
1746 dest->presentation = src->presentation;
1747 dest->valid = src->valid;
1750 void ast_party_name_free(struct ast_party_name *doomed)
1752 ast_free(doomed->str);
1756 void ast_party_number_init(struct ast_party_number *init)
1759 init->plan = 0;/* Unknown */
1760 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1764 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1767 /* Don't copy to self */
1771 ast_free(dest->str);
1772 dest->str = ast_strdup(src->str);
1773 dest->plan = src->plan;
1774 dest->presentation = src->presentation;
1775 dest->valid = src->valid;
1778 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1781 init->plan = guide->plan;
1782 init->presentation = guide->presentation;
1783 init->valid = guide->valid;
1786 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1789 /* Don't set to self */
1793 if (src->str && src->str != dest->str) {
1794 ast_free(dest->str);
1795 dest->str = ast_strdup(src->str);
1798 dest->plan = src->plan;
1799 dest->presentation = src->presentation;
1800 dest->valid = src->valid;
1803 void ast_party_number_free(struct ast_party_number *doomed)
1805 ast_free(doomed->str);
1809 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1813 init->odd_even_indicator = 0;
1817 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1820 /* Don't copy to self */
1824 ast_free(dest->str);
1825 dest->str = ast_strdup(src->str);
1826 dest->type = src->type;
1827 dest->odd_even_indicator = src->odd_even_indicator;
1828 dest->valid = src->valid;
1831 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1834 init->type = guide->type;
1835 init->odd_even_indicator = guide->odd_even_indicator;
1836 init->valid = guide->valid;
1839 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1842 /* Don't set to self */
1846 if (src->str && src->str != dest->str) {
1847 ast_free(dest->str);
1848 dest->str = ast_strdup(src->str);
1851 dest->type = src->type;
1852 dest->odd_even_indicator = src->odd_even_indicator;
1853 dest->valid = src->valid;
1856 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1858 ast_free(doomed->str);
1862 void ast_party_id_init(struct ast_party_id *init)
1864 ast_party_name_init(&init->name);
1865 ast_party_number_init(&init->number);
1866 ast_party_subaddress_init(&init->subaddress);
1870 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1873 /* Don't copy to self */
1877 ast_party_name_copy(&dest->name, &src->name);
1878 ast_party_number_copy(&dest->number, &src->number);
1879 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1881 ast_free(dest->tag);
1882 dest->tag = ast_strdup(src->tag);
1885 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1887 ast_party_name_set_init(&init->name, &guide->name);
1888 ast_party_number_set_init(&init->number, &guide->number);
1889 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1893 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1896 /* Don't set to self */
1900 if (!update || update->name) {
1901 ast_party_name_set(&dest->name, &src->name);
1903 if (!update || update->number) {
1904 ast_party_number_set(&dest->number, &src->number);
1906 if (!update || update->subaddress) {
1907 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1910 if (src->tag && src->tag != dest->tag) {
1911 ast_free(dest->tag);
1912 dest->tag = ast_strdup(src->tag);
1916 void ast_party_id_free(struct ast_party_id *doomed)
1918 ast_party_name_free(&doomed->name);
1919 ast_party_number_free(&doomed->number);
1920 ast_party_subaddress_free(&doomed->subaddress);
1922 ast_free(doomed->tag);
1926 int ast_party_id_presentation(const struct ast_party_id *id)
1928 int number_priority;
1930 int number_screening;
1934 /* Determine name presentation priority. */
1935 if (!id->name.valid) {
1936 name_value = AST_PRES_UNAVAILABLE;
1939 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1940 switch (name_value) {
1941 case AST_PRES_RESTRICTED:
1944 case AST_PRES_ALLOWED:
1947 case AST_PRES_UNAVAILABLE:
1951 name_value = AST_PRES_UNAVAILABLE;
1957 /* Determine number presentation priority. */
1958 if (!id->number.valid) {
1959 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1960 number_value = AST_PRES_UNAVAILABLE;
1961 number_priority = 3;
1963 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1964 number_value = id->number.presentation & AST_PRES_RESTRICTION;
1965 switch (number_value) {
1966 case AST_PRES_RESTRICTED:
1967 number_priority = 0;
1969 case AST_PRES_ALLOWED:
1970 number_priority = 1;
1972 case AST_PRES_UNAVAILABLE:
1973 number_priority = 2;
1976 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1977 number_value = AST_PRES_UNAVAILABLE;
1978 number_priority = 3;
1983 /* Select the wining presentation value. */
1984 if (name_priority < number_priority) {
1985 number_value = name_value;
1987 if (number_value == AST_PRES_UNAVAILABLE) {
1988 return AST_PRES_NUMBER_NOT_AVAILABLE;
1991 return number_value | number_screening;
1994 void ast_party_dialed_init(struct ast_party_dialed *init)
1996 init->number.str = NULL;
1997 init->number.plan = 0;/* Unknown */
1998 ast_party_subaddress_init(&init->subaddress);
1999 init->transit_network_select = 0;
2002 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2005 /* Don't copy to self */
2009 ast_free(dest->number.str);
2010 dest->number.str = ast_strdup(src->number.str);
2011 dest->number.plan = src->number.plan;
2012 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2013 dest->transit_network_select = src->transit_network_select;
2016 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2018 init->number.str = NULL;
2019 init->number.plan = guide->number.plan;
2020 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2021 init->transit_network_select = guide->transit_network_select;
2024 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2026 if (src->number.str && src->number.str != dest->number.str) {
2027 ast_free(dest->number.str);
2028 dest->number.str = ast_strdup(src->number.str);
2030 dest->number.plan = src->number.plan;
2032 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2034 dest->transit_network_select = src->transit_network_select;
2037 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2039 ast_free(doomed->number.str);
2040 doomed->number.str = NULL;
2041 ast_party_subaddress_free(&doomed->subaddress);
2044 void ast_party_caller_init(struct ast_party_caller *init)
2046 ast_party_id_init(&init->id);
2047 ast_party_id_init(&init->ani);
2051 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2054 /* Don't copy to self */
2058 ast_party_id_copy(&dest->id, &src->id);
2059 ast_party_id_copy(&dest->ani, &src->ani);
2060 dest->ani2 = src->ani2;
2063 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2065 ast_party_id_set_init(&init->id, &guide->id);
2066 ast_party_id_set_init(&init->ani, &guide->ani);
2067 init->ani2 = guide->ani2;
2070 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2072 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2073 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2074 dest->ani2 = src->ani2;
2077 void ast_party_caller_free(struct ast_party_caller *doomed)
2079 ast_party_id_free(&doomed->id);
2080 ast_party_id_free(&doomed->ani);
2083 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2085 ast_party_id_init(&init->id);
2086 ast_party_id_init(&init->ani);
2088 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2091 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2094 /* Don't copy to self */
2098 ast_party_id_copy(&dest->id, &src->id);
2099 ast_party_id_copy(&dest->ani, &src->ani);
2100 dest->ani2 = src->ani2;
2101 dest->source = src->source;
2104 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2106 ast_party_id_set_init(&init->id, &guide->id);
2107 ast_party_id_set_init(&init->ani, &guide->ani);
2108 init->ani2 = guide->ani2;
2109 init->source = guide->source;
2112 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)
2114 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2115 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2116 dest->ani2 = src->ani2;
2117 dest->source = src->source;
2120 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2122 connected->id = caller->id;
2123 connected->ani = caller->ani;
2124 connected->ani2 = caller->ani2;
2125 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2128 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2130 ast_party_id_free(&doomed->id);
2131 ast_party_id_free(&doomed->ani);
2134 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2136 ast_party_id_init(&init->orig);
2137 ast_party_id_init(&init->from);
2138 ast_party_id_init(&init->to);
2140 init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2141 init->orig_reason = AST_REDIRECTING_REASON_UNKNOWN;
2144 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2147 /* Don't copy to self */
2151 ast_party_id_copy(&dest->orig, &src->orig);
2152 ast_party_id_copy(&dest->from, &src->from);
2153 ast_party_id_copy(&dest->to, &src->to);
2154 dest->count = src->count;
2155 dest->reason = src->reason;
2156 dest->orig_reason = src->orig_reason;
2159 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2161 ast_party_id_set_init(&init->orig, &guide->orig);
2162 ast_party_id_set_init(&init->from, &guide->from);
2163 ast_party_id_set_init(&init->to, &guide->to);
2164 init->count = guide->count;
2165 init->reason = guide->reason;
2166 init->orig_reason = guide->orig_reason;
2169 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2171 ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2172 ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2173 ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2174 dest->count = src->count;
2175 dest->reason = src->reason;
2176 dest->orig_reason = src->orig_reason;
2179 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2181 ast_party_id_free(&doomed->orig);
2182 ast_party_id_free(&doomed->from);
2183 ast_party_id_free(&doomed->to);
2186 /*! \brief Free a channel structure */
2187 static void ast_channel_destructor(void *obj)
2189 struct ast_channel *chan = obj;
2193 struct ast_var_t *vardata;
2194 struct ast_frame *f;
2195 struct varshead *headp;
2196 struct ast_datastore *datastore;
2197 char device_name[AST_CHANNEL_NAME];
2198 struct ast_callid *callid;
2200 if (ast_channel_internal_is_finalized(chan)) {
2201 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2202 ast_cel_check_retire_linkedid(chan);
2205 ast_pbx_hangup_handler_destroy(chan);
2207 ast_channel_lock(chan);
2209 /* Get rid of each of the data stores on the channel */
2210 while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2211 /* Free the data store */
2212 ast_datastore_free(datastore);
2214 /* While the channel is locked, take the reference to its callid while we tear down the call. */
2215 callid = ast_channel_callid(chan);
2216 ast_channel_callid_cleanup(chan);
2218 ast_channel_unlock(chan);
2220 /* Lock and unlock the channel just to be sure nobody has it locked still
2221 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2222 ast_channel_lock(chan);
2223 ast_channel_unlock(chan);
2225 if (ast_channel_tech_pvt(chan)) {
2226 ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2227 ast_free(ast_channel_tech_pvt(chan));
2230 if (ast_channel_sched(chan)) {
2231 ast_sched_context_destroy(ast_channel_sched(chan));
2234 if (ast_channel_internal_is_finalized(chan)) {
2237 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2238 if ((dashptr = strrchr(device_name, '-'))) {
2242 device_name[0] = '\0';
2245 /* Stop monitoring */
2246 if (ast_channel_monitor(chan))
2247 ast_channel_monitor(chan)->stop( chan, 0 );
2249 /* If there is native format music-on-hold state, free it */
2250 if (ast_channel_music_state(chan))
2251 ast_moh_cleanup(chan);
2253 /* Free translators */
2254 if (ast_channel_readtrans(chan))
2255 ast_translator_free_path(ast_channel_readtrans(chan));
2256 if (ast_channel_writetrans(chan))
2257 ast_translator_free_path(ast_channel_writetrans(chan));
2258 if (ast_channel_pbx(chan))
2259 ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2261 ast_party_dialed_free(ast_channel_dialed(chan));
2262 ast_party_caller_free(ast_channel_caller(chan));
2263 ast_party_connected_line_free(ast_channel_connected(chan));
2264 ast_party_redirecting_free(ast_channel_redirecting(chan));
2266 /* Close pipes if appropriate */
2267 ast_channel_internal_alertpipe_close(chan);
2268 if (ast_channel_timer(chan)) {
2269 ast_timer_close(ast_channel_timer(chan));
2272 for (i = 0; i < AST_MAX_FDS; i++) {
2273 if (ast_channel_internal_epfd_data(chan, i)) {
2274 ast_free(ast_channel_internal_epfd_data(chan, i));
2277 close(ast_channel_epfd(chan));
2279 while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2282 /* loop over the variables list, freeing all data and deleting list items */
2283 /* no need to lock the list, as the channel is already locked */
2284 headp = ast_channel_varshead(chan);
2285 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2286 ast_var_delete(vardata);
2288 ast_app_group_discard(chan);
2290 /* Destroy the jitterbuffer */
2291 ast_jb_destroy(chan);
2293 if (ast_channel_cdr(chan)) {
2294 ast_cdr_discard(ast_channel_cdr(chan));
2295 ast_channel_cdr_set(chan, NULL);
2298 if (ast_channel_zone(chan)) {
2299 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2302 ast_channel_internal_cleanup(chan);
2304 if (device_name[0]) {
2306 * We have a device name to notify of a new state.
2308 * Queue an unknown state, because, while we know that this particular
2309 * instance is dead, we don't know the state of all other possible
2312 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2315 ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2317 ast_callid_unref(callid);
2319 ast_atomic_fetchadd_int(&chancount, -1);
2322 /*! \brief Free a dummy channel structure */
2323 static void ast_dummy_channel_destructor(void *obj)
2325 struct ast_channel *chan = obj;
2326 struct ast_datastore *datastore;
2327 struct ast_var_t *vardata;
2328 struct varshead *headp;
2330 ast_pbx_hangup_handler_destroy(chan);
2332 /* Get rid of each of the data stores on the channel */
2333 while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
2334 /* Free the data store */
2335 ast_datastore_free(datastore);
2338 ast_party_dialed_free(ast_channel_dialed(chan));
2339 ast_party_caller_free(ast_channel_caller(chan));
2340 ast_party_connected_line_free(ast_channel_connected(chan));
2341 ast_party_redirecting_free(ast_channel_redirecting(chan));
2343 /* loop over the variables list, freeing all data and deleting list items */
2344 /* no need to lock the list, as the channel is already locked */
2345 headp = ast_channel_varshead(chan);
2346 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2347 ast_var_delete(vardata);
2349 if (ast_channel_cdr(chan)) {
2350 ast_cdr_discard(ast_channel_cdr(chan));
2351 ast_channel_cdr_set(chan, NULL);
2354 ast_channel_internal_cleanup(chan);
2357 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2359 return ast_datastore_alloc(info, uid);
2362 int ast_channel_datastore_free(struct ast_datastore *datastore)
2364 return ast_datastore_free(datastore);
2367 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2369 struct ast_datastore *datastore = NULL, *datastore2;
2371 AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2372 if (datastore->inheritance > 0) {
2373 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2375 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2376 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2377 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2384 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2388 AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2393 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2395 return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2398 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2400 struct ast_datastore *datastore = NULL;
2405 AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2406 if (datastore->info != info) {
2411 /* matched by type only */
2415 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2416 /* Matched by type AND uid */
2424 /*! Set the file descriptor on the channel */
2425 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2428 struct epoll_event ev;
2429 struct ast_epoll_data *aed = NULL;
2431 if (ast_channel_fd_isset(chan, which)) {
2432 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2433 aed = ast_channel_internal_epfd_data(chan, which);
2436 /* If this new fd is valid, add it to the epoll */
2438 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2441 ast_channel_internal_epfd_data_set(chan, which, aed);
2445 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2447 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2449 /* We don't have to keep around this epoll data structure now */
2451 ast_channel_epfd_data_set(chan, which, NULL);
2454 ast_channel_internal_fd_set(chan, which, fd);
2458 /*! Add a channel to an optimized waitfor */
2459 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2462 struct epoll_event ev;
2465 if (ast_channel_epfd(chan0) == -1)
2468 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2469 for (i = 0; i < AST_MAX_FDS; i++) {
2470 if (!ast_channel_fd_isset(chan1, i)) {
2473 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2474 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2475 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2482 /*! Delete a channel from an optimized waitfor */
2483 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2486 struct epoll_event ev;
2489 if (ast_channel_epfd(chan0) == -1)
2492 for (i = 0; i < AST_MAX_FDS; i++) {
2493 if (!ast_channel_fd_isset(chan1, i)) {
2496 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2503 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2505 ast_channel_lock(chan);
2507 ast_channel_softhangup_internal_flag_clear(chan, flag);
2509 if (!ast_channel_softhangup_internal_flag(chan)) {
2510 struct ast_frame *fr;
2512 /* If we have completely cleared the softhangup flag,
2513 * then we need to fully abort the hangup process. This requires
2514 * pulling the END_OF_Q frame out of the channel frame queue if it
2515 * still happens to be there. */
2517 fr = AST_LIST_LAST(ast_channel_readq(chan));
2518 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2519 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2520 AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2525 ast_channel_unlock(chan);
2528 /*! \brief Softly hangup a channel, don't lock */
2529 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2531 ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2532 /* Inform channel driver that we need to be hung up, if it cares */
2533 ast_channel_softhangup_internal_flag_add(chan, cause);
2534 ast_queue_frame(chan, &ast_null_frame);
2535 /* Interrupt any poll call or such */
2536 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2537 pthread_kill(ast_channel_blocker(chan), SIGURG);
2541 /*! \brief Softly hangup a channel, lock */
2542 int ast_softhangup(struct ast_channel *chan, int cause)
2546 ast_channel_lock(chan);
2547 res = ast_softhangup_nolock(chan, cause);
2548 manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2552 ast_channel_name(chan),
2553 ast_channel_uniqueid(chan),
2555 ast_channel_unlock(chan);
2560 static void free_translation(struct ast_channel *clonechan)
2562 if (ast_channel_writetrans(clonechan))
2563 ast_translator_free_path(ast_channel_writetrans(clonechan));
2564 if (ast_channel_readtrans(clonechan))
2565 ast_translator_free_path(ast_channel_readtrans(clonechan));
2566 ast_channel_writetrans_set(clonechan, NULL);
2567 ast_channel_readtrans_set(clonechan, NULL);
2568 if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2569 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2570 ast_format_clear(ast_channel_rawreadformat(clonechan));
2572 struct ast_format tmpfmt;
2573 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2574 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2575 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2579 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2581 struct ast_channel *bridge;
2583 ast_channel_lock(chan);
2584 if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2585 ast_channel_hangupsource_set(chan, source);
2587 bridge = ast_bridged_channel(chan);
2589 ast_channel_ref(bridge);
2591 ast_channel_unlock(chan);
2594 ast_channel_lock(bridge);
2595 if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
2596 ast_channel_hangupsource_set(bridge, source);
2598 ast_channel_unlock(bridge);
2599 ast_channel_unref(bridge);
2603 static void destroy_hooks(struct ast_channel *chan)
2605 if (ast_channel_audiohooks(chan)) {
2606 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2607 ast_channel_audiohooks_set(chan, NULL);
2610 ast_framehook_list_destroy(chan);
2613 /*! \brief Hangup a channel */
2614 int ast_hangup(struct ast_channel *chan)
2616 char extra_str[64]; /* used for cel logging below */
2618 ast_autoservice_stop(chan);
2620 ast_channel_lock(chan);
2623 * Do the masquerade if someone is setup to masquerade into us.
2625 * NOTE: We must hold the channel lock after testing for a
2626 * pending masquerade and setting the channel as a zombie to
2627 * prevent __ast_channel_masquerade() from setting up a
2628 * masquerade with a dead channel.
2630 while (ast_channel_masq(chan)) {
2631 ast_channel_unlock(chan);
2632 ast_do_masquerade(chan);
2633 ast_channel_lock(chan);
2636 if (ast_channel_masqr(chan)) {
2638 * This channel is one which will be masqueraded into something.
2639 * Mark it as a zombie already so ast_do_masquerade() will know
2642 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2643 destroy_hooks(chan);
2644 ast_channel_unlock(chan);
2648 /* Mark as a zombie so a masquerade cannot be setup on this channel. */
2649 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2651 ast_channel_unlock(chan);
2654 * XXX if running the hangup handlers here causes problems
2655 * because the handlers take too long to execute, we could move
2656 * the meat of this function into another thread. A thread
2657 * where channels go to die.
2659 * If this is done, ast_autoservice_chan_hangup_peer() will no
2662 ast_pbx_hangup_handler_run(chan);
2663 ao2_unlink(channels, chan);
2664 ast_channel_lock(chan);
2666 destroy_hooks(chan);
2668 free_translation(chan);
2669 /* Close audio stream */
2670 if (ast_channel_stream(chan)) {
2671 ast_closestream(ast_channel_stream(chan));
2672 ast_channel_stream_set(chan, NULL);
2674 /* Close video stream */
2675 if (ast_channel_vstream(chan)) {
2676 ast_closestream(ast_channel_vstream(chan));
2677 ast_channel_vstream_set(chan, NULL);
2679 if (ast_channel_sched(chan)) {
2680 ast_sched_context_destroy(ast_channel_sched(chan));
2681 ast_channel_sched_set(chan, NULL);
2684 if (ast_channel_generatordata(chan)) { /* Clear any tone stuff remaining */
2685 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2686 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2689 ast_channel_generatordata_set(chan, NULL);
2690 ast_channel_generator_set(chan, NULL);
2692 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"), ""));
2693 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2695 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2696 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2697 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2698 (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2699 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2702 ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2703 if (ast_channel_tech(chan)->hangup) {
2704 ast_channel_tech(chan)->hangup(chan);
2707 ast_channel_unlock(chan);
2710 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2713 "CallerIDNum: %s\r\n"
2714 "CallerIDName: %s\r\n"
2715 "ConnectedLineNum: %s\r\n"
2716 "ConnectedLineName: %s\r\n"
2718 "Cause-txt: %s\r\n",
2719 ast_channel_name(chan),
2720 ast_channel_uniqueid(chan),
2721 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
2722 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
2723 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
2724 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
2725 ast_channel_hangupcause(chan),
2726 ast_cause2str(ast_channel_hangupcause(chan))
2729 if (ast_channel_cdr(chan) && !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_BRIDGED) &&
2730 !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_POST_DISABLED) &&
2731 (ast_channel_cdr(chan)->disposition != AST_CDR_NULL || ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_DIALED))) {
2732 ast_channel_lock(chan);
2733 ast_cdr_end(ast_channel_cdr(chan));
2734 ast_cdr_detach(ast_channel_cdr(chan));
2735 ast_channel_cdr_set(chan, NULL);
2736 ast_channel_unlock(chan);
2739 ast_channel_unref(chan);
2744 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2748 ast_channel_lock(chan);
2750 /* You can't answer an outbound call */
2751 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2752 ast_channel_unlock(chan);
2756 /* Stop if we're a zombie or need a soft hangup */
2757 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2758 ast_channel_unlock(chan);
2762 ast_channel_unlock(chan);
2764 switch (ast_channel_state(chan)) {
2765 case AST_STATE_RINGING:
2766 case AST_STATE_RING:
2767 ast_channel_lock(chan);
2768 if (ast_channel_tech(chan)->answer) {
2769 res = ast_channel_tech(chan)->answer(chan);
2771 ast_setstate(chan, AST_STATE_UP);
2773 ast_cdr_answer(ast_channel_cdr(chan));
2775 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2776 ast_channel_unlock(chan);
2779 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2780 /* Calling ast_cdr_answer when it it has previously been called
2781 * is essentially a no-op, so it is safe.
2784 ast_cdr_answer(ast_channel_cdr(chan));
2791 ast_indicate(chan, -1);
2796 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2799 enum ast_channel_state old_state;
2801 old_state = ast_channel_state(chan);
2802 if ((res = ast_raw_answer(chan, cdr_answer))) {
2806 switch (old_state) {
2807 case AST_STATE_RINGING:
2808 case AST_STATE_RING:
2809 /* wait for media to start flowing, but don't wait any longer
2810 * than 'delay' or 500 milliseconds, whichever is longer
2813 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2814 struct ast_frame *cur, *new;
2815 int ms = MAX(delay, 500);
2816 unsigned int done = 0;
2818 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2821 ms = ast_waitfor(chan, ms);
2823 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2828 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));
2831 cur = ast_read(chan);
2832 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2833 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2838 ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2842 if ((new = ast_frisolate(cur)) != cur) {
2846 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2848 /* if a specific delay period was requested, continue
2849 * until that delay has passed. don't stop just because
2850 * incoming media has arrived.
2856 switch (new->frametype) {
2857 /* all of these frametypes qualify as 'media' */
2858 case AST_FRAME_VOICE:
2859 case AST_FRAME_VIDEO:
2860 case AST_FRAME_TEXT:
2861 case AST_FRAME_DTMF_BEGIN:
2862 case AST_FRAME_DTMF_END:
2863 case AST_FRAME_IMAGE:
2864 case AST_FRAME_HTML:
2865 case AST_FRAME_MODEM:
2868 case AST_FRAME_CONTROL:
2870 case AST_FRAME_NULL:
2881 ast_channel_lock(chan);
2882 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2883 ast_queue_frame_head(chan, cur);
2886 ast_channel_unlock(chan);
2897 int ast_answer(struct ast_channel *chan)
2899 return __ast_answer(chan, 0, 1);
2902 void ast_deactivate_generator(struct ast_channel *chan)
2904 ast_channel_lock(chan);
2905 if (ast_channel_generatordata(chan)) {
2906 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2907 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2909 ast_channel_generatordata_set(chan, NULL);
2910 ast_channel_generator_set(chan, NULL);
2911 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2912 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
2913 ast_settimeout(chan, 0, NULL, NULL);
2915 ast_channel_unlock(chan);
2918 static void generator_write_format_change(struct ast_channel *chan)
2920 ast_channel_lock(chan);
2921 if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
2922 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
2924 ast_channel_unlock(chan);
2927 static int generator_force(const void *data)
2929 /* Called if generator doesn't have data */
2932 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2933 struct ast_channel *chan = (struct ast_channel *)data;
2935 ast_channel_lock(chan);
2936 tmp = ast_channel_generatordata(chan);
2937 ast_channel_generatordata_set(chan, NULL);
2938 if (ast_channel_generator(chan))
2939 generate = ast_channel_generator(chan)->generate;
2940 ast_channel_unlock(chan);
2942 if (!tmp || !generate)
2945 res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
2947 ast_channel_generatordata_set(chan, tmp);
2950 ast_debug(1, "Auto-deactivating generator\n");
2951 ast_deactivate_generator(chan);
2957 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2960 void *generatordata = NULL;
2962 ast_channel_lock(chan);
2963 if (ast_channel_generatordata(chan)) {
2964 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2965 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2968 if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
2971 ast_channel_generatordata_set(chan, generatordata);
2973 ast_settimeout(chan, 50, generator_force, chan);
2974 ast_channel_generator_set(chan, gen);
2976 ast_channel_unlock(chan);
2983 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2984 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2987 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2991 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2993 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2994 int *exception, int *outfd, int *ms)
2996 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2997 int *exception, int *outfd, int *ms)
3000 struct timeval start = { 0 , 0 };
3001 struct pollfd *pfds = NULL;
3006 struct timeval now = { 0, 0 };
3007 struct timeval whentohangup = { 0, 0 }, diff;
3008 struct ast_channel *winner = NULL;
3021 if ((sz = n * AST_MAX_FDS + nfds)) {
3022 pfds = alloca(sizeof(*pfds) * sz);
3023 fdmap = alloca(sizeof(*fdmap) * sz);
3025 /* nothing to allocate and no FDs to check */
3029 /* Perform any pending masquerades */
3030 for (x = 0; x < n; x++) {
3031 while (ast_channel_masq(c[x])) {
3032 ast_do_masquerade(c[x]);
3035 ast_channel_lock(c[x]);
3036 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
3037 if (ast_tvzero(whentohangup))
3039 diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
3040 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3041 /* Should already be hungup */
3042 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3043 ast_channel_unlock(c[x]);
3046 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3047 whentohangup = diff;
3049 ast_channel_unlock(c[x]);
3051 /* Wait full interval */
3053 /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3054 if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3055 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
3056 if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
3059 } else if (!ast_tvzero(whentohangup) && rms < 0) {
3060 /* Tiny corner case... call would need to last >24 days */
3064 * Build the pollfd array, putting the channels' fds first,
3065 * followed by individual fds. Order is important because
3066 * individual fd's must have priority over channel fds.
3069 for (x = 0; x < n; x++) {
3070 for (y = 0; y < AST_MAX_FDS; y++) {
3071 fdmap[max].fdno = y; /* fd y is linked to this pfds */
3072 fdmap[max].chan = x; /* channel x is linked to this pfds */
3073 max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3075 CHECK_BLOCKING(c[x]);
3077 /* Add the individual fds */
3078 for (x = 0; x < nfds; x++) {
3079 fdmap[max].chan = -1;
3080 max += ast_add_fd(&pfds[max], fds[x]);
3084 start = ast_tvnow();
3087 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3090 if (kbrms > 600000) {
3093 res = ast_poll(pfds, max, kbrms);
3097 } while (!res && (rms > 0));
3099 res = ast_poll(pfds, max, rms);
3101 for (x = 0; x < n; x++) {
3102 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3104 if (res < 0) { /* Simulate a timeout if we were interrupted */
3105 if (errno != EINTR) {
3110 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
3112 for (x = 0; x < n; x++) {
3113 if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3114 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3115 if (winner == NULL) {
3121 if (res == 0) { /* no fd ready, reset timeout and done */
3122 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
3126 * Then check if any channel or fd has a pending event.
3127 * Remember to check channels first and fds last, as they
3128 * must have priority on setting 'winner'
3130 for (x = 0; x < max; x++) {
3131 res = pfds[x].revents;
3135 if (fdmap[x].chan >= 0) { /* this is a channel */
3136 winner = c[fdmap[x].chan]; /* override previous winners */
3137 if (res & POLLPRI) {
3138 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3140 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3142 ast_channel_fdno_set(winner, fdmap[x].fdno);
3143 } else { /* this is an fd */
3145 *outfd = pfds[x].fd;
3148 *exception = (res & POLLPRI) ? -1 : 0;
3154 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3163 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3165 struct timeval start = { 0 , 0 };
3167 struct epoll_event ev[1];
3168 long diff, rms = *ms;
3169 struct ast_channel *winner = NULL;
3170 struct ast_epoll_data *aed = NULL;
3173 /* See if this channel needs to be masqueraded */
3174 while (ast_channel_masq(chan)) {
3175 ast_do_masquerade(chan);
3178 ast_channel_lock(chan);
3179 /* Figure out their timeout */
3180 if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3181 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow())) < 0) {
3182 /* They should already be hungup! */
3183 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3184 ast_channel_unlock(chan);
3187 /* If this value is smaller then the current one... make it priority */
3193 ast_channel_unlock(chan);
3195 /* Time to make this channel block... */
3196 CHECK_BLOCKING(chan);
3199 start = ast_tvnow();
3202 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3203 res = epoll_wait(ast_channel_epfd(chan), ev, 1, rms);
3206 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
3208 /* Simulate a timeout if we were interrupted */
3210 if (errno != EINTR) {
3216 /* If this channel has a timeout see if it expired */
3217 if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3218 if (ast_tvdiff_ms(ast_tvnow(), *ast_channel_whentohangup(chan)) >= 0) {
3219 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3224 /* No fd ready, reset timeout and be done for now */
3230 /* See what events are pending */
3231 aed = ev[0].data.ptr;
3232 ast_channel_fdno_set(chan, aed->which);
3233 if (ev[0].events & EPOLLPRI) {
3234 ast_set_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3236 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3240 *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 while (ast_channel_masq(c[i])) {
3260 ast_do_masquerade(c[i]);
3263 ast_channel_lock(c[i]);
3264 if (!ast_tvzero(*ast_channel_whentohangup(c[i]))) {
3265 if (whentohangup == 0) {
3268 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(c[i]), now)) < 0) {
3269 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3270 ast_channel_unlock(c[i]);
3273 if (!whentohangup || whentohangup > diff) {
3274 whentohangup = diff;
3277 ast_channel_unlock(c[i]);
3278 CHECK_BLOCKING(c[i]);
3284 if (*ms >= 0 && *ms < rms) {
3290 start = ast_tvnow();
3293 res = epoll_wait(ast_channel_epfd(c[0]), ev, 25, rms);
3295 for (i = 0; i < n; i++) {
3296 ast_clear_flag(ast_channel_flags(c[i]), AST_FLAG_BLOCKING);
3300 if (errno != EINTR) {
3308 for (i = 0; i < n; i++) {
3309 if (!ast_tvzero(*ast_channel_whentohangup(c[i])) && ast_tvdiff_ms(now, *ast_channel_whentohangup(c[i])) >= 0) {
3310 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3323 for (i = 0; i < res; i++) {
3324 struct ast_epoll_data *aed = ev[i].data.ptr;
3326 if (!ev[i].events || !aed) {
3331 if (ev[i].events & EPOLLPRI) {
3332 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3334 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3336 ast_channel_fdno_set(winner, aed->which);
3340 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3349 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3350 int *exception, int *outfd, int *ms)
3352 /* Clear all provided values in one place. */
3360 /* If no epoll file descriptor is available&