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;
98 unsigned long global_fin, global_fout;
100 AST_THREADSTORAGE(state2str_threadbuf);
101 #define STATE2STR_BUFSIZE 32
103 /*! Default amount of time to use when emulating a digit as a begin and end
105 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
107 /*! Minimum allowed digit length - 80ms */
108 #define AST_MIN_DTMF_DURATION 80
110 /*! Minimum amount of time between the end of the last digit and the beginning
111 * of a new one - 45ms */
112 #define AST_MIN_DTMF_GAP 45
114 /*! \brief List of channel drivers */
116 const struct ast_channel_tech *tech;
117 AST_LIST_ENTRY(chanlist) list;
121 /*! \brief Structure to hold channel context backtrace data */
122 struct ast_chan_trace_data {
124 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
127 /*! \brief Structure to save contexts where an ast_chan has been into */
128 struct ast_chan_trace {
129 char context[AST_MAX_CONTEXT];
130 char exten[AST_MAX_EXTENSION];
132 AST_LIST_ENTRY(ast_chan_trace) entry;
136 /*! \brief the list of registered channel types */
137 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
140 #define NUM_CHANNEL_BUCKETS 61
142 #define NUM_CHANNEL_BUCKETS 1567
145 /*! \brief All active channels on the system */
146 static struct ao2_container *channels;
148 /*! \brief map AST_CAUSE's to readable string representations
152 static const struct {
157 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
158 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
159 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
160 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
161 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
162 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
163 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
164 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
165 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
166 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
167 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
168 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
169 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
170 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
171 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
172 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
173 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
174 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
175 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
176 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
177 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
178 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
179 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
180 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
181 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
182 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
183 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
184 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
185 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
186 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
187 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
188 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
189 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
190 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
191 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
192 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
193 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
194 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
195 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
196 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
197 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
198 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
199 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
200 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
203 struct ast_variable *ast_channeltype_list(void)
206 struct ast_variable *var = NULL, *prev = NULL;
208 AST_RWLIST_RDLOCK(&backends);
209 AST_RWLIST_TRAVERSE(&backends, cl, list) {
211 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
214 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
218 AST_RWLIST_UNLOCK(&backends);
223 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
224 static const char *party_number_ton2str(int ton)
226 #if defined(HAVE_PRI)
227 switch ((ton >> 4) & 0x07) {
228 case PRI_TON_INTERNATIONAL:
229 return "International";
230 case PRI_TON_NATIONAL:
232 case PRI_TON_NET_SPECIFIC:
233 return "Network Specific";
234 case PRI_TON_SUBSCRIBER:
236 case PRI_TON_ABBREVIATED:
237 return "Abbreviated";
238 case PRI_TON_RESERVED:
240 case PRI_TON_UNKNOWN:
244 #endif /* defined(HAVE_PRI) */
247 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
249 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
250 static const char *party_number_plan2str(int plan)
252 #if defined(HAVE_PRI)
253 switch (plan & 0x0F) {
255 case PRI_NPI_UNKNOWN:
257 case PRI_NPI_E163_E164:
258 return "Public (E.163/E.164)";
260 return "Data (X.121)";
262 return "Telex (F.69)";
263 case PRI_NPI_NATIONAL:
264 return "National Standard";
265 case PRI_NPI_PRIVATE:
267 case PRI_NPI_RESERVED:
270 #endif /* defined(HAVE_PRI) */
273 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
275 /*! \brief Show channel types - CLI command */
276 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
278 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
284 e->command = "core show channeltypes";
286 "Usage: core show channeltypes\n"
287 " Lists available channel types registered in your\n"
288 " Asterisk server.\n";
295 return CLI_SHOWUSAGE;
297 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
298 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
300 AST_RWLIST_RDLOCK(&backends);
301 AST_RWLIST_TRAVERSE(&backends, cl, list) {
302 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
303 (cl->tech->devicestate) ? "yes" : "no",
304 (cl->tech->indicate) ? "yes" : "no",
305 (cl->tech->transfer) ? "yes" : "no");
308 AST_RWLIST_UNLOCK(&backends);
310 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
317 static char *complete_channeltypes(struct ast_cli_args *a)
327 wordlen = strlen(a->word);
329 AST_RWLIST_RDLOCK(&backends);
330 AST_RWLIST_TRAVERSE(&backends, cl, list) {
331 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
332 ret = ast_strdup(cl->tech->type);
336 AST_RWLIST_UNLOCK(&backends);
341 /*! \brief Show details about a channel driver - CLI command */
342 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
344 struct chanlist *cl = NULL;
349 e->command = "core show channeltype";
351 "Usage: core show channeltype <name>\n"
352 " Show details about the specified channel type, <name>.\n";
355 return complete_channeltypes(a);
359 return CLI_SHOWUSAGE;
361 AST_RWLIST_RDLOCK(&backends);
363 AST_RWLIST_TRAVERSE(&backends, cl, list) {
364 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
370 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
371 AST_RWLIST_UNLOCK(&backends);
376 "-- Info about channel driver: %s --\n"
377 " Device State: %s\n"
380 " Capabilities: %s\n"
384 " Image Support: %s\n"
385 " Text Support: %s\n",
387 (cl->tech->devicestate) ? "yes" : "no",
388 (cl->tech->indicate) ? "yes" : "no",
389 (cl->tech->transfer) ? "yes" : "no",
390 ast_getformatname_multiple(buf, sizeof(buf), cl->tech->capabilities),
391 (cl->tech->send_digit_begin) ? "yes" : "no",
392 (cl->tech->send_digit_end) ? "yes" : "no",
393 (cl->tech->send_html) ? "yes" : "no",
394 (cl->tech->send_image) ? "yes" : "no",
395 (cl->tech->send_text) ? "yes" : "no"
399 AST_RWLIST_UNLOCK(&backends);
404 static struct ast_cli_entry cli_channel[] = {
405 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
406 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
409 static struct ast_frame *kill_read(struct ast_channel *chan)
411 /* Hangup channel. */
415 static struct ast_frame *kill_exception(struct ast_channel *chan)
417 /* Hangup channel. */
421 static int kill_write(struct ast_channel *chan, struct ast_frame *frame)
423 /* Hangup channel. */
427 static int kill_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
429 /* No problem fixing up the channel. */
433 static int kill_hangup(struct ast_channel *chan)
435 ast_channel_tech_pvt_set(chan, NULL);
440 * \brief Kill the channel channel driver technology descriptor.
443 * The purpose of this channel technology is to encourage the
444 * channel to hangup as quickly as possible.
446 * \note Used by DTMF atxfer and zombie channels.
448 const struct ast_channel_tech ast_kill_tech = {
450 .description = "Kill channel (should not see this)",
452 .exception = kill_exception,
455 .hangup = kill_hangup,
459 /*! \brief Destructor for the channel trace datastore */
460 static void ast_chan_trace_destroy_cb(void *data)
462 struct ast_chan_trace *trace;
463 struct ast_chan_trace_data *traced = data;
464 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
470 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
471 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
473 .destroy = ast_chan_trace_destroy_cb
476 /*! \brief Put the channel backtrace in a string */
477 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
480 struct ast_chan_trace *trace;
481 struct ast_chan_trace_data *traced;
482 struct ast_datastore *store;
484 ast_channel_lock(chan);
485 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
487 ast_channel_unlock(chan);
490 traced = store->data;
492 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
493 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
494 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
500 ast_channel_unlock(chan);
504 /* !\brief Whether or not context tracing is enabled */
505 int ast_channel_trace_is_enabled(struct ast_channel *chan)
507 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
510 return ((struct ast_chan_trace_data *)store->data)->enabled;
513 /*! \brief Update the context backtrace data if tracing is enabled */
514 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
516 struct ast_chan_trace *trace;
517 if (!traced->enabled)
519 /* If the last saved context does not match the current one
520 OR we have not saved any context so far, then save the current context */
521 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan))) ||
522 (AST_LIST_EMPTY(&traced->trace))) {
523 /* Just do some debug logging */
524 if (AST_LIST_EMPTY(&traced->trace))
525 ast_debug(1, "Setting initial trace context to %s\n", ast_channel_context(chan));
527 ast_debug(1, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan));
528 /* alloc or bail out */
529 trace = ast_malloc(sizeof(*trace));
532 /* save the current location and store it in the trace list */
533 ast_copy_string(trace->context, ast_channel_context(chan), sizeof(trace->context));
534 ast_copy_string(trace->exten, ast_channel_exten(chan), sizeof(trace->exten));
535 trace->priority = ast_channel_priority(chan);
536 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
541 /*! \brief Update the context backtrace if tracing is enabled */
542 int ast_channel_trace_update(struct ast_channel *chan)
544 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
547 return ast_channel_trace_data_update(chan, store->data);
550 /*! \brief Enable context tracing in the channel */
551 int ast_channel_trace_enable(struct ast_channel *chan)
553 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
554 struct ast_chan_trace_data *traced;
556 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
559 traced = ast_calloc(1, sizeof(*traced));
561 ast_datastore_free(store);
564 store->data = traced;
565 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
566 ast_channel_datastore_add(chan, store);
568 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
569 ast_channel_trace_data_update(chan, store->data);
573 /*! \brief Disable context tracing in the channel */
574 int ast_channel_trace_disable(struct ast_channel *chan)
576 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
579 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
582 #endif /* CHANNEL_TRACE */
584 /*! \brief Checks to see if a channel is needing hang up */
585 int ast_check_hangup(struct ast_channel *chan)
587 if (ast_channel_softhangup_internal_flag(chan)) /* yes if soft hangup flag set */
589 if (ast_tvzero(*ast_channel_whentohangup(chan))) /* no if no hangup scheduled */
591 if (ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()) > 0) /* no if hangup time has not come yet. */
593 ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()));
594 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT); /* record event */
598 int ast_check_hangup_locked(struct ast_channel *chan)
601 ast_channel_lock(chan);
602 res = ast_check_hangup(chan);
603 ast_channel_unlock(chan);
607 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
609 struct ast_channel *chan = obj;
611 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
616 void ast_begin_shutdown(int hangup)
621 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
625 /*! \brief returns number of active/allocated channels */
626 int ast_active_channels(void)
628 return channels ? ao2_container_count(channels) : 0;
631 /*! \brief Cancel a shutdown in progress */
632 void ast_cancel_shutdown(void)
637 /*! \brief Returns non-zero if Asterisk is being shut down */
638 int ast_shutting_down(void)
640 return shutting_down;
643 /*! \brief Set when to hangup channel */
644 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
646 if (ast_tvzero(offset)) {
647 ast_channel_whentohangup_set(chan, &offset);
649 struct timeval tv = ast_tvadd(offset, ast_tvnow());
650 ast_channel_whentohangup_set(chan, &tv);
652 ast_queue_frame(chan, &ast_null_frame);
656 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
658 struct timeval when = { offset, };
659 ast_channel_setwhentohangup_tv(chan, when);
662 /*! \brief Compare a offset with when to hangup channel */
663 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
665 struct timeval whentohangup;
667 if (ast_tvzero(*ast_channel_whentohangup(chan)))
668 return ast_tvzero(offset) ? 0 : -1;
670 if (ast_tvzero(offset))
673 whentohangup = ast_tvadd(offset, ast_tvnow());
675 return ast_tvdiff_ms(whentohangup, *ast_channel_whentohangup(chan));
678 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
680 struct timeval when = { offset, };
681 return ast_channel_cmpwhentohangup_tv(chan, when);
684 /*! \brief Register a new telephony channel in Asterisk */
685 int ast_channel_register(const struct ast_channel_tech *tech)
687 struct chanlist *chan;
689 AST_RWLIST_WRLOCK(&backends);
691 AST_RWLIST_TRAVERSE(&backends, chan, list) {
692 if (!strcasecmp(tech->type, chan->tech->type)) {
693 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
694 AST_RWLIST_UNLOCK(&backends);
699 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
700 AST_RWLIST_UNLOCK(&backends);
704 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
706 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
708 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
710 AST_RWLIST_UNLOCK(&backends);
715 /*! \brief Unregister channel driver */
716 void ast_channel_unregister(const struct ast_channel_tech *tech)
718 struct chanlist *chan;
720 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
722 AST_RWLIST_WRLOCK(&backends);
724 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
725 if (chan->tech == tech) {
726 AST_LIST_REMOVE_CURRENT(list);
728 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
732 AST_LIST_TRAVERSE_SAFE_END;
734 AST_RWLIST_UNLOCK(&backends);
737 /*! \brief Get handle to channel driver based on name */
738 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
740 struct chanlist *chanls;
741 const struct ast_channel_tech *ret = NULL;
743 AST_RWLIST_RDLOCK(&backends);
745 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
746 if (!strcasecmp(name, chanls->tech->type)) {
752 AST_RWLIST_UNLOCK(&backends);
757 /*! \brief Gives the string form of a given hangup cause */
758 const char *ast_cause2str(int cause)
762 for (x = 0; x < ARRAY_LEN(causes); x++) {
763 if (causes[x].cause == cause)
764 return causes[x].desc;
770 /*! \brief Convert a symbolic hangup cause to number */
771 int ast_str2cause(const char *name)
775 for (x = 0; x < ARRAY_LEN(causes); x++)
776 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
777 return causes[x].cause;
782 /*! \brief Gives the string form of a given channel state.
783 \note This function is not reentrant.
785 const char *ast_state2str(enum ast_channel_state state)
792 case AST_STATE_RESERVED:
794 case AST_STATE_OFFHOOK:
796 case AST_STATE_DIALING:
800 case AST_STATE_RINGING:
806 case AST_STATE_DIALING_OFFHOOK:
807 return "Dialing Offhook";
808 case AST_STATE_PRERING:
811 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
813 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
818 /*! \brief Gives the string form of a given transfer capability */
819 char *ast_transfercapability2str(int transfercapability)
821 switch (transfercapability) {
822 case AST_TRANS_CAP_SPEECH:
824 case AST_TRANS_CAP_DIGITAL:
826 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
827 return "RESTRICTED_DIGITAL";
828 case AST_TRANS_CAP_3_1K_AUDIO:
830 case AST_TRANS_CAP_DIGITAL_W_TONES:
831 return "DIGITAL_W_TONES";
832 case AST_TRANS_CAP_VIDEO:
839 /*! \brief Pick the best audio codec */
840 struct ast_format *ast_best_codec(struct ast_format_cap *cap, struct ast_format *result)
842 /* This just our opinion, expressed in code. We are asked to choose
843 the best codec to use, given no information */
844 static const enum ast_format_id prefs[] =
846 /*! Okay, ulaw is used by all telephony equipment, so start with it */
848 /*! Unless of course, you're a silly European, so then prefer ALAW */
854 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
856 /*! Okay, well, signed linear is easy to translate into other stuff */
857 AST_FORMAT_SLINEAR192,
858 AST_FORMAT_SLINEAR96,
859 AST_FORMAT_SLINEAR48,
860 AST_FORMAT_SLINEAR44,
861 AST_FORMAT_SLINEAR32,
862 AST_FORMAT_SLINEAR24,
863 AST_FORMAT_SLINEAR16,
864 AST_FORMAT_SLINEAR12,
866 /*! G.726 is standard ADPCM, in RFC3551 packing order */
868 /*! G.726 is standard ADPCM, in AAL2 packing order */
869 AST_FORMAT_G726_AAL2,
870 /*! ADPCM has great sound quality and is still pretty easy to translate */
872 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
873 translate and sounds pretty good */
875 /*! iLBC is not too bad */
877 /*! Speex is free, but computationally more expensive than GSM */
881 /*! SILK is pretty awesome. */
883 /*! CELT supports crazy high sample rates */
885 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
888 /*! G.729a is faster than 723 and slightly less expensive */
890 /*! Down to G.723.1 which is proprietary but at least designed for voice */
896 /* Find the first preferred codec in the format given */
897 for (x = 0; x < ARRAY_LEN(prefs); x++) {
898 if (ast_format_cap_best_byid(cap, prefs[x], result)) {
903 ast_format_clear(result);
904 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
909 static const struct ast_channel_tech null_tech = {
911 .description = "Null channel (should not see this)",
914 static void ast_channel_destructor(void *obj);
915 static void ast_dummy_channel_destructor(void *obj);
917 /*! \brief Create a new channel structure */
918 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
919 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
920 const char *acctcode, const char *exten, const char *context,
921 const char *linkedid, const int amaflag, const char *file, int line,
922 const char *function, const char *name_fmt, va_list ap)
924 struct ast_channel *tmp;
925 struct varshead *headp;
926 char *tech = "", *tech2 = NULL;
927 struct ast_format_cap *nativeformats;
928 struct ast_sched_context *schedctx;
929 struct ast_timer *timer;
931 /* If shutting down, don't allocate any new channels */
932 if (ast_shutting_down()) {
933 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
937 if (!(tmp = ast_channel_internal_alloc(ast_channel_destructor))) {
938 /* Channel structure allocation failure. */
941 if (!(nativeformats = ast_format_cap_alloc())) {
943 /* format capabilities structure allocation failure */
946 ast_channel_nativeformats_set(tmp, nativeformats);
949 * Init file descriptors to unopened state so
950 * the destructor can know not to close them.
952 ast_channel_timingfd_set(tmp, -1);
953 ast_channel_internal_alertpipe_clear(tmp);
954 ast_channel_internal_fd_clear_all(tmp);
957 ast_channel_epfd(tmp) = epoll_create(25);
960 if (!(schedctx = ast_sched_context_create())) {
961 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
962 return ast_channel_unref(tmp);
964 ast_channel_sched_set(tmp, schedctx);
966 ast_party_dialed_init(ast_channel_dialed(tmp));
967 ast_party_caller_init(ast_channel_caller(tmp));
968 ast_party_connected_line_init(ast_channel_connected(tmp));
969 ast_party_redirecting_init(ast_channel_redirecting(tmp));
972 ast_channel_caller(tmp)->id.name.valid = 1;
973 ast_channel_caller(tmp)->id.name.str = ast_strdup(cid_name);
974 if (!ast_channel_caller(tmp)->id.name.str) {
975 return ast_channel_unref(tmp);
979 ast_channel_caller(tmp)->id.number.valid = 1;
980 ast_channel_caller(tmp)->id.number.str = ast_strdup(cid_num);
981 if (!ast_channel_caller(tmp)->id.number.str) {
982 return ast_channel_unref(tmp);
986 if ((timer = ast_timer_open())) {
987 ast_channel_timer_set(tmp, timer);
988 if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
991 ast_channel_timingfd_set(tmp, ast_timer_fd(ast_channel_timer(tmp)));
995 * This is the last place the channel constructor can fail.
997 * The destructor takes advantage of this fact to ensure that the
998 * AST_CEL_CHANNEL_END is not posted if we have not posted the
999 * AST_CEL_CHANNEL_START yet.
1002 if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
1003 return ast_channel_unref(tmp);
1006 /* Always watch the alertpipe */
1007 ast_channel_set_fd(tmp, AST_ALERT_FD, ast_channel_internal_alert_readfd(tmp));
1008 /* And timing pipe */
1009 ast_channel_set_fd(tmp, AST_TIMING_FD, ast_channel_timingfd(tmp));
1012 ast_channel_state_set(tmp, state);
1014 ast_channel_streamid_set(tmp, -1);
1016 ast_channel_fin_set(tmp, global_fin);
1017 ast_channel_fout_set(tmp, global_fout);
1019 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1020 ast_channel_uniqueid_build(tmp, "%li.%d", (long) time(NULL),
1021 ast_atomic_fetchadd_int(&uniqueint, 1));
1023 ast_channel_uniqueid_build(tmp, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
1024 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1027 if (!ast_strlen_zero(linkedid)) {
1028 ast_channel_linkedid_set(tmp, linkedid);
1030 ast_channel_linkedid_set(tmp, ast_channel_uniqueid(tmp));
1033 if (!ast_strlen_zero(name_fmt)) {
1034 char *slash, *slash2;
1035 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1036 * And they all use slightly different formats for their name string.
1037 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1038 * This means, that the stringfields must have a routine that takes the va_lists directly, and
1039 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1040 * This new function was written so this can be accomplished.
1042 ast_channel_name_build_va(tmp, name_fmt, ap);
1043 tech = ast_strdupa(ast_channel_name(tmp));
1044 if ((slash = strchr(tech, '/'))) {
1045 if ((slash2 = strchr(slash + 1, '/'))) {
1053 * Start the string with '-' so it becomes an empty string
1054 * in the destructor.
1056 ast_channel_name_set(tmp, "-**Unknown**");
1059 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1061 /* These 4 variables need to be set up for the cdr_init() to work right */
1063 ast_channel_amaflags_set(tmp, amaflag);
1065 ast_channel_amaflags_set(tmp, ast_default_amaflags);
1068 if (!ast_strlen_zero(acctcode))
1069 ast_channel_accountcode_set(tmp, acctcode);
1071 ast_channel_accountcode_set(tmp, ast_default_accountcode);
1073 ast_channel_context_set(tmp, S_OR(context, "default"));
1074 ast_channel_exten_set(tmp, S_OR(exten, "s"));
1075 ast_channel_priority_set(tmp, 1);
1077 ast_channel_cdr_set(tmp, ast_cdr_alloc());
1078 ast_cdr_init(ast_channel_cdr(tmp), tmp);
1079 ast_cdr_start(ast_channel_cdr(tmp));
1081 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1083 headp = ast_channel_varshead(tmp);
1084 AST_LIST_HEAD_INIT_NOLOCK(headp);
1086 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1088 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_autochans(tmp));
1090 ast_channel_language_set(tmp, defaultlanguage);
1092 ast_channel_tech_set(tmp, &null_tech);
1094 ao2_link(channels, tmp);
1097 * And now, since the channel structure is built, and has its name, let's
1098 * call the manager event generator with this Newchannel event. This is the
1099 * proper and correct place to make this call, but you sure do have to pass
1100 * a lot of data into this func to do it here!
1102 if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1103 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1105 "ChannelState: %d\r\n"
1106 "ChannelStateDesc: %s\r\n"
1107 "CallerIDNum: %s\r\n"
1108 "CallerIDName: %s\r\n"
1109 "AccountCode: %s\r\n"
1113 ast_channel_name(tmp),
1115 ast_state2str(state),
1118 ast_channel_accountcode(tmp),
1121 ast_channel_uniqueid(tmp));
1124 ast_channel_internal_finalize(tmp);
1128 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1129 const char *cid_name, const char *acctcode,
1130 const char *exten, const char *context,
1131 const char *linkedid, const int amaflag,
1132 const char *file, int line, const char *function,
1133 const char *name_fmt, ...)
1136 struct ast_channel *result;
1138 va_start(ap, name_fmt);
1139 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1140 linkedid, amaflag, file, line, function, name_fmt, ap);
1146 /* only do the minimum amount of work needed here to make a channel
1147 * structure that can be used to expand channel vars */
1148 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1149 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1151 struct ast_channel *ast_dummy_channel_alloc(void)
1154 struct ast_channel *tmp;
1155 struct varshead *headp;
1157 if (!(tmp = ast_channel_internal_alloc(ast_dummy_channel_destructor))) {
1158 /* Dummy channel structure allocation failure. */
1162 headp = ast_channel_varshead(tmp);
1163 AST_LIST_HEAD_INIT_NOLOCK(headp);
1168 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1170 struct ast_frame *f;
1171 struct ast_frame *cur;
1172 unsigned int new_frames = 0;
1173 unsigned int new_voice_frames = 0;
1174 unsigned int queued_frames = 0;
1175 unsigned int queued_voice_frames = 0;
1176 AST_LIST_HEAD_NOLOCK(,ast_frame) frames;
1178 ast_channel_lock(chan);
1181 * Check the last frame on the queue if we are queuing the new
1184 cur = AST_LIST_LAST(ast_channel_readq(chan));
1185 if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1186 switch (cur->subclass.integer) {
1187 case AST_CONTROL_END_OF_Q:
1188 if (fin->frametype == AST_FRAME_CONTROL
1189 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1191 * Destroy the end-of-Q marker frame so we can queue the hangup
1192 * frame in its place.
1194 AST_LIST_REMOVE(ast_channel_readq(chan), cur, frame_list);
1198 * This has degenerated to a normal queue append anyway. Since
1199 * we just destroyed the last frame in the queue we must make
1200 * sure that "after" is NULL or bad things will happen.
1206 case AST_CONTROL_HANGUP:
1207 /* Don't queue anything. */
1208 ast_channel_unlock(chan);
1215 /* Build copies of all the new frames and count them */
1216 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1217 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1218 if (!(f = ast_frdup(cur))) {
1219 if (AST_LIST_FIRST(&frames)) {
1220 ast_frfree(AST_LIST_FIRST(&frames));
1222 ast_channel_unlock(chan);
1226 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1228 if (f->frametype == AST_FRAME_VOICE) {
1233 /* Count how many frames exist on the queue */
1234 AST_LIST_TRAVERSE(ast_channel_readq(chan), cur, frame_list) {
1236 if (cur->frametype == AST_FRAME_VOICE) {
1237 queued_voice_frames++;
1241 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1243 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1244 AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), cur, frame_list) {
1245 /* Save the most recent frame */
1246 if (!AST_LIST_NEXT(cur, frame_list)) {
1248 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1252 AST_LIST_REMOVE_CURRENT(frame_list);
1256 AST_LIST_TRAVERSE_SAFE_END;
1260 AST_LIST_INSERT_LIST_AFTER(ast_channel_readq(chan), &frames, after, frame_list);
1263 AST_LIST_APPEND_LIST(&frames, ast_channel_readq(chan), frame_list);
1264 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_readq(chan));
1266 AST_LIST_APPEND_LIST(ast_channel_readq(chan), &frames, frame_list);
1269 if (ast_channel_alert_writable(chan)) {
1270 if (ast_channel_alert_write(chan)) {
1271 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1272 ast_channel_name(chan), queued_frames, strerror(errno));
1274 } else if (ast_channel_timingfd(chan) > -1) {
1275 ast_timer_enable_continuous(ast_channel_timer(chan));
1276 } else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
1277 pthread_kill(ast_channel_blocker(chan), SIGURG);
1280 ast_channel_unlock(chan);
1285 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1287 return __ast_queue_frame(chan, fin, 0, NULL);
1290 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1292 return __ast_queue_frame(chan, fin, 1, NULL);
1295 /*! \brief Queue a hangup frame for channel */
1296 int ast_queue_hangup(struct ast_channel *chan)
1298 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1299 /* Yeah, let's not change a lock-critical value without locking */
1300 if (!ast_channel_trylock(chan)) {
1301 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1302 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1305 ast_channel_name(chan),
1306 ast_channel_uniqueid(chan));
1307 ast_channel_unlock(chan);
1309 return ast_queue_frame(chan, &f);
1312 /*! \brief Queue a hangup frame for channel */
1313 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1315 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1318 f.data.uint32 = cause;
1320 /* Yeah, let's not change a lock-critical value without locking */
1321 if (!ast_channel_trylock(chan)) {
1322 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1324 f.data.uint32 = ast_channel_hangupcause(chan);
1326 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1330 ast_channel_name(chan),
1331 ast_channel_uniqueid(chan),
1333 ast_channel_unlock(chan);
1336 return ast_queue_frame(chan, &f);
1339 /*! \brief Queue a control frame */
1340 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1342 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1343 return ast_queue_frame(chan, &f);
1346 /*! \brief Queue a control frame with payload */
1347 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1348 const void *data, size_t datalen)
1350 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1351 return ast_queue_frame(chan, &f);
1354 /*! \brief Set defer DTMF flag on channel */
1355 int ast_channel_defer_dtmf(struct ast_channel *chan)
1360 pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1361 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1366 /*! \brief Unset defer DTMF flag on channel */
1367 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1370 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1373 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1374 void *data, int ao2_flags)
1376 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1379 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1381 struct ast_channel *chan = obj;
1382 const char *name = arg;
1383 size_t name_len = *(size_t *) data;
1384 int ret = CMP_MATCH;
1386 if (ast_strlen_zero(name)) {
1387 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1391 ast_channel_lock(chan);
1392 if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1393 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1394 ret = 0; /* name match failed, keep looking */
1396 ast_channel_unlock(chan);
1401 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1403 struct ast_channel *chan = obj;
1404 char *context = arg;
1406 int ret = CMP_MATCH;
1408 if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1409 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1413 ast_channel_lock(chan);
1414 if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1415 ret = 0; /* Context match failed, continue */
1416 } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1417 ret = 0; /* Extension match failed, continue */
1419 ast_channel_unlock(chan);
1424 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1426 struct ast_channel *chan = obj;
1427 char *uniqueid = arg;
1428 size_t id_len = *(size_t *) data;
1429 int ret = CMP_MATCH;
1431 if (ast_strlen_zero(uniqueid)) {
1432 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1436 ast_channel_lock(chan);
1437 if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1438 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1439 ret = 0; /* uniqueid match failed, keep looking */
1441 ast_channel_unlock(chan);
1446 struct ast_channel_iterator {
1447 /* storage for non-dynamically allocated iterator */
1448 struct ao2_iterator simple_iterator;
1449 /* pointer to the actual iterator (simple_iterator or a dynamically
1450 * allocated iterator)
1452 struct ao2_iterator *active_iterator;
1455 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1457 ao2_iterator_destroy(i->active_iterator);
1463 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1465 struct ast_channel_iterator *i;
1466 char *l_exten = (char *) exten;
1467 char *l_context = (char *) context;
1469 if (!(i = ast_calloc(1, sizeof(*i)))) {
1473 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1474 l_context, l_exten, OBJ_MULTIPLE);
1475 if (!i->active_iterator) {
1483 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1485 struct ast_channel_iterator *i;
1486 char *l_name = (char *) name;
1488 if (!(i = ast_calloc(1, sizeof(*i)))) {
1492 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1494 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1495 if (!i->active_iterator) {
1503 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1505 struct ast_channel_iterator *i;
1507 if (!(i = ast_calloc(1, sizeof(*i)))) {
1511 i->simple_iterator = ao2_iterator_init(channels, 0);
1512 i->active_iterator = &i->simple_iterator;
1517 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1519 return ao2_iterator_next(i->active_iterator);
1522 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1523 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1525 ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1529 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1531 struct ast_channel *chan;
1532 char *l_name = (char *) name;
1534 chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1535 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1540 if (ast_strlen_zero(l_name)) {
1541 /* We didn't have a name to search for so quit. */
1545 /* Now try a search for uniqueid. */
1546 return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1549 struct ast_channel *ast_channel_get_by_name(const char *name)
1551 return ast_channel_get_by_name_prefix(name, 0);
1554 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1556 char *l_exten = (char *) exten;
1557 char *l_context = (char *) context;
1559 return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1562 int ast_is_deferrable_frame(const struct ast_frame *frame)
1564 /* Do not add a default entry in this switch statement. Each new
1565 * frame type should be addressed directly as to whether it should
1566 * be queued up or not.
1568 switch (frame->frametype) {
1569 case AST_FRAME_CONTROL:
1570 case AST_FRAME_TEXT:
1571 case AST_FRAME_IMAGE:
1572 case AST_FRAME_HTML:
1575 case AST_FRAME_DTMF_END:
1576 case AST_FRAME_DTMF_BEGIN:
1577 case AST_FRAME_VOICE:
1578 case AST_FRAME_VIDEO:
1579 case AST_FRAME_NULL:
1582 case AST_FRAME_MODEM:
1588 /*! \brief Wait, look for hangups and condition arg */
1589 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1591 struct ast_frame *f;
1592 struct ast_silence_generator *silgen = NULL;
1594 AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1596 AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1598 /* If no other generator is present, start silencegen while waiting */
1599 if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1600 silgen = ast_channel_start_silence_generator(chan);
1604 struct ast_frame *dup_f = NULL;
1605 if (cond && ((*cond)(data) == 0)) {
1608 ms = ast_waitfor(chan, ms);
1620 if (!ast_is_deferrable_frame(f)) {
1625 if ((dup_f = ast_frisolate(f))) {
1629 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1634 /* stop silgen if present */
1636 ast_channel_stop_silence_generator(chan, silgen);
1639 /* We need to free all the deferred frames, but we only need to
1640 * queue the deferred frames if there was no error and no
1641 * hangup was received
1643 ast_channel_lock(chan);
1644 while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1646 ast_queue_frame_head(chan, f);
1650 ast_channel_unlock(chan);
1655 /*! \brief Wait, look for hangups */
1656 int ast_safe_sleep(struct ast_channel *chan, int ms)
1658 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1661 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1663 /* Safe, even if already unlinked. */
1664 ao2_unlink(channels, chan);
1665 return ast_channel_unref(chan);
1668 void ast_party_name_init(struct ast_party_name *init)
1671 init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1672 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1676 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1679 /* Don't copy to self */
1683 ast_free(dest->str);
1684 dest->str = ast_strdup(src->str);
1685 dest->char_set = src->char_set;
1686 dest->presentation = src->presentation;
1687 dest->valid = src->valid;
1690 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1693 init->char_set = guide->char_set;
1694 init->presentation = guide->presentation;
1695 init->valid = guide->valid;
1698 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1701 /* Don't set to self */
1705 if (src->str && src->str != dest->str) {
1706 ast_free(dest->str);
1707 dest->str = ast_strdup(src->str);
1710 dest->char_set = src->char_set;
1711 dest->presentation = src->presentation;
1712 dest->valid = src->valid;
1715 void ast_party_name_free(struct ast_party_name *doomed)
1717 ast_free(doomed->str);
1721 void ast_party_number_init(struct ast_party_number *init)
1724 init->plan = 0;/* Unknown */
1725 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1729 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1732 /* Don't copy to self */
1736 ast_free(dest->str);
1737 dest->str = ast_strdup(src->str);
1738 dest->plan = src->plan;
1739 dest->presentation = src->presentation;
1740 dest->valid = src->valid;
1743 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1746 init->plan = guide->plan;
1747 init->presentation = guide->presentation;
1748 init->valid = guide->valid;
1751 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1754 /* Don't set to self */
1758 if (src->str && src->str != dest->str) {
1759 ast_free(dest->str);
1760 dest->str = ast_strdup(src->str);
1763 dest->plan = src->plan;
1764 dest->presentation = src->presentation;
1765 dest->valid = src->valid;
1768 void ast_party_number_free(struct ast_party_number *doomed)
1770 ast_free(doomed->str);
1774 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1778 init->odd_even_indicator = 0;
1782 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1785 /* Don't copy to self */
1789 ast_free(dest->str);
1790 dest->str = ast_strdup(src->str);
1791 dest->type = src->type;
1792 dest->odd_even_indicator = src->odd_even_indicator;
1793 dest->valid = src->valid;
1796 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1799 init->type = guide->type;
1800 init->odd_even_indicator = guide->odd_even_indicator;
1801 init->valid = guide->valid;
1804 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1807 /* Don't set to self */
1811 if (src->str && src->str != dest->str) {
1812 ast_free(dest->str);
1813 dest->str = ast_strdup(src->str);
1816 dest->type = src->type;
1817 dest->odd_even_indicator = src->odd_even_indicator;
1818 dest->valid = src->valid;
1821 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1823 ast_free(doomed->str);
1827 void ast_party_id_init(struct ast_party_id *init)
1829 ast_party_name_init(&init->name);
1830 ast_party_number_init(&init->number);
1831 ast_party_subaddress_init(&init->subaddress);
1835 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1838 /* Don't copy to self */
1842 ast_party_name_copy(&dest->name, &src->name);
1843 ast_party_number_copy(&dest->number, &src->number);
1844 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1846 ast_free(dest->tag);
1847 dest->tag = ast_strdup(src->tag);
1850 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1852 ast_party_name_set_init(&init->name, &guide->name);
1853 ast_party_number_set_init(&init->number, &guide->number);
1854 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1858 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1861 /* Don't set to self */
1865 if (!update || update->name) {
1866 ast_party_name_set(&dest->name, &src->name);
1868 if (!update || update->number) {
1869 ast_party_number_set(&dest->number, &src->number);
1871 if (!update || update->subaddress) {
1872 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1875 if (src->tag && src->tag != dest->tag) {
1876 ast_free(dest->tag);
1877 dest->tag = ast_strdup(src->tag);
1881 void ast_party_id_free(struct ast_party_id *doomed)
1883 ast_party_name_free(&doomed->name);
1884 ast_party_number_free(&doomed->number);
1885 ast_party_subaddress_free(&doomed->subaddress);
1887 ast_free(doomed->tag);
1891 int ast_party_id_presentation(const struct ast_party_id *id)
1893 int number_priority;
1895 int number_screening;
1899 /* Determine name presentation priority. */
1900 if (!id->name.valid) {
1901 name_value = AST_PRES_UNAVAILABLE;
1904 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1905 switch (name_value) {
1906 case AST_PRES_RESTRICTED:
1909 case AST_PRES_ALLOWED:
1912 case AST_PRES_UNAVAILABLE:
1916 name_value = AST_PRES_UNAVAILABLE;
1922 /* Determine number presentation priority. */
1923 if (!id->number.valid) {
1924 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1925 number_value = AST_PRES_UNAVAILABLE;
1926 number_priority = 3;
1928 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1929 number_value = id->number.presentation & AST_PRES_RESTRICTION;
1930 switch (number_value) {
1931 case AST_PRES_RESTRICTED:
1932 number_priority = 0;
1934 case AST_PRES_ALLOWED:
1935 number_priority = 1;
1937 case AST_PRES_UNAVAILABLE:
1938 number_priority = 2;
1941 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1942 number_value = AST_PRES_UNAVAILABLE;
1943 number_priority = 3;
1948 /* Select the wining presentation value. */
1949 if (name_priority < number_priority) {
1950 number_value = name_value;
1952 if (number_value == AST_PRES_UNAVAILABLE) {
1953 return AST_PRES_NUMBER_NOT_AVAILABLE;
1956 return number_value | number_screening;
1959 void ast_party_dialed_init(struct ast_party_dialed *init)
1961 init->number.str = NULL;
1962 init->number.plan = 0;/* Unknown */
1963 ast_party_subaddress_init(&init->subaddress);
1964 init->transit_network_select = 0;
1967 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1970 /* Don't copy to self */
1974 ast_free(dest->number.str);
1975 dest->number.str = ast_strdup(src->number.str);
1976 dest->number.plan = src->number.plan;
1977 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1978 dest->transit_network_select = src->transit_network_select;
1981 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
1983 init->number.str = NULL;
1984 init->number.plan = guide->number.plan;
1985 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1986 init->transit_network_select = guide->transit_network_select;
1989 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1991 if (src->number.str && src->number.str != dest->number.str) {
1992 ast_free(dest->number.str);
1993 dest->number.str = ast_strdup(src->number.str);
1995 dest->number.plan = src->number.plan;
1997 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1999 dest->transit_network_select = src->transit_network_select;
2002 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2004 ast_free(doomed->number.str);
2005 doomed->number.str = NULL;
2006 ast_party_subaddress_free(&doomed->subaddress);
2009 void ast_party_caller_init(struct ast_party_caller *init)
2011 ast_party_id_init(&init->id);
2012 ast_party_id_init(&init->ani);
2016 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2019 /* Don't copy to self */
2023 ast_party_id_copy(&dest->id, &src->id);
2024 ast_party_id_copy(&dest->ani, &src->ani);
2025 dest->ani2 = src->ani2;
2028 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2030 ast_party_id_set_init(&init->id, &guide->id);
2031 ast_party_id_set_init(&init->ani, &guide->ani);
2032 init->ani2 = guide->ani2;
2035 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2037 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2038 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2039 dest->ani2 = src->ani2;
2042 void ast_party_caller_free(struct ast_party_caller *doomed)
2044 ast_party_id_free(&doomed->id);
2045 ast_party_id_free(&doomed->ani);
2048 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2050 ast_party_id_init(&init->id);
2051 ast_party_id_init(&init->ani);
2053 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2056 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2059 /* Don't copy to self */
2063 ast_party_id_copy(&dest->id, &src->id);
2064 ast_party_id_copy(&dest->ani, &src->ani);
2065 dest->ani2 = src->ani2;
2066 dest->source = src->source;
2069 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2071 ast_party_id_set_init(&init->id, &guide->id);
2072 ast_party_id_set_init(&init->ani, &guide->ani);
2073 init->ani2 = guide->ani2;
2074 init->source = guide->source;
2077 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)
2079 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2080 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2081 dest->ani2 = src->ani2;
2082 dest->source = src->source;
2085 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2087 connected->id = caller->id;
2088 connected->ani = caller->ani;
2089 connected->ani2 = caller->ani2;
2090 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2093 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2095 ast_party_id_free(&doomed->id);
2096 ast_party_id_free(&doomed->ani);
2099 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2101 ast_party_id_init(&init->from);
2102 ast_party_id_init(&init->to);
2104 init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2107 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2110 /* Don't copy to self */
2114 ast_party_id_copy(&dest->from, &src->from);
2115 ast_party_id_copy(&dest->to, &src->to);
2116 dest->count = src->count;
2117 dest->reason = src->reason;
2120 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2122 ast_party_id_set_init(&init->from, &guide->from);
2123 ast_party_id_set_init(&init->to, &guide->to);
2124 init->count = guide->count;
2125 init->reason = guide->reason;
2128 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2130 ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2131 ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2132 dest->reason = src->reason;
2133 dest->count = src->count;
2136 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2138 ast_party_id_free(&doomed->from);
2139 ast_party_id_free(&doomed->to);
2142 /*! \brief Free a channel structure */
2143 static void ast_channel_destructor(void *obj)
2145 struct ast_channel *chan = obj;
2149 struct ast_var_t *vardata;
2150 struct ast_frame *f;
2151 struct varshead *headp;
2152 struct ast_datastore *datastore;
2153 char device_name[AST_CHANNEL_NAME];
2155 if (ast_channel_internal_is_finalized(chan)) {
2156 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2157 ast_cel_check_retire_linkedid(chan);
2160 /* Get rid of each of the data stores on the channel */
2161 ast_channel_lock(chan);
2162 while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2163 /* Free the data store */
2164 ast_datastore_free(datastore);
2165 ast_channel_unlock(chan);
2167 /* Lock and unlock the channel just to be sure nobody has it locked still
2168 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2169 ast_channel_lock(chan);
2170 ast_channel_unlock(chan);
2172 if (ast_channel_tech_pvt(chan)) {
2173 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2174 ast_free(ast_channel_tech_pvt(chan));
2177 if (ast_channel_sched(chan)) {
2178 ast_sched_context_destroy(ast_channel_sched(chan));
2181 if (ast_channel_internal_is_finalized(chan)) {
2184 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2185 if ((dashptr = strrchr(device_name, '-'))) {
2189 device_name[0] = '\0';
2192 /* Stop monitoring */
2193 if (ast_channel_monitor(chan))
2194 ast_channel_monitor(chan)->stop( chan, 0 );
2196 /* If there is native format music-on-hold state, free it */
2197 if (ast_channel_music_state(chan))
2198 ast_moh_cleanup(chan);
2200 /* Free translators */
2201 if (ast_channel_readtrans(chan))
2202 ast_translator_free_path(ast_channel_readtrans(chan));
2203 if (ast_channel_writetrans(chan))
2204 ast_translator_free_path(ast_channel_writetrans(chan));
2205 if (ast_channel_pbx(chan))
2206 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2208 ast_party_dialed_free(ast_channel_dialed(chan));
2209 ast_party_caller_free(ast_channel_caller(chan));
2210 ast_party_connected_line_free(ast_channel_connected(chan));
2211 ast_party_redirecting_free(ast_channel_redirecting(chan));
2213 /* Close pipes if appropriate */
2214 ast_channel_internal_alertpipe_close(chan);
2215 if (ast_channel_timer(chan)) {
2216 ast_timer_close(ast_channel_timer(chan));
2219 for (i = 0; i < AST_MAX_FDS; i++) {
2220 if (ast_channel_internal_epfd_data(chan, i)) {
2221 ast_free(ast_channel_internal_epfd_data(chan, i));
2224 close(ast_channel_epfd(chan));
2226 while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2229 /* loop over the variables list, freeing all data and deleting list items */
2230 /* no need to lock the list, as the channel is already locked */
2231 headp = ast_channel_varshead(chan);
2232 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2233 ast_var_delete(vardata);
2235 ast_app_group_discard(chan);
2237 /* Destroy the jitterbuffer */
2238 ast_jb_destroy(chan);
2240 if (ast_channel_cdr(chan)) {
2241 ast_cdr_discard(ast_channel_cdr(chan));
2242 ast_channel_cdr_set(chan, NULL);
2245 if (ast_channel_zone(chan)) {
2246 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2249 ast_channel_internal_cleanup(chan);
2251 if (device_name[0]) {
2253 * We have a device name to notify of a new state.
2255 * Queue an unknown state, because, while we know that this particular
2256 * instance is dead, we don't know the state of all other possible
2259 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2262 ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2265 /*! \brief Free a dummy channel structure */
2266 static void ast_dummy_channel_destructor(void *obj)
2268 struct ast_channel *chan = obj;
2269 struct ast_var_t *vardata;
2270 struct varshead *headp;
2272 headp = ast_channel_varshead(chan);
2274 ast_party_dialed_free(ast_channel_dialed(chan));
2275 ast_party_caller_free(ast_channel_caller(chan));
2276 ast_party_connected_line_free(ast_channel_connected(chan));
2277 ast_party_redirecting_free(ast_channel_redirecting(chan));
2279 /* loop over the variables list, freeing all data and deleting list items */
2280 /* no need to lock the list, as the channel is already locked */
2281 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2282 ast_var_delete(vardata);
2284 if (ast_channel_cdr(chan)) {
2285 ast_cdr_discard(ast_channel_cdr(chan));
2286 ast_channel_cdr_set(chan, NULL);
2289 ast_channel_internal_cleanup(chan);
2292 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2294 return ast_datastore_alloc(info, uid);
2297 int ast_channel_datastore_free(struct ast_datastore *datastore)
2299 return ast_datastore_free(datastore);
2302 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2304 struct ast_datastore *datastore = NULL, *datastore2;
2306 AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2307 if (datastore->inheritance > 0) {
2308 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2310 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2311 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2312 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2319 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2323 AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2328 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2330 return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2333 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2335 struct ast_datastore *datastore = NULL;
2340 AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2341 if (datastore->info != info) {
2346 /* matched by type only */
2350 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2351 /* Matched by type AND uid */
2359 /*! Set the file descriptor on the channel */
2360 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2363 struct epoll_event ev;
2364 struct ast_epoll_data *aed = NULL;
2366 if (ast_channel_fd_isset(chan, which)) {
2367 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2368 aed = ast_channel_internal_epfd_data(chan, which);
2371 /* If this new fd is valid, add it to the epoll */
2373 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2376 ast_channel_internal_epfd_data_set(chan, which, aed);
2380 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2382 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2384 /* We don't have to keep around this epoll data structure now */
2386 ast_channel_epfd_data_set(chan, which, NULL);
2389 ast_channel_internal_fd_set(chan, which, fd);
2393 /*! Add a channel to an optimized waitfor */
2394 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2397 struct epoll_event ev;
2400 if (ast_channel_epfd(chan0) == -1)
2403 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2404 for (i = 0; i < AST_MAX_FDS; i++) {
2405 if (!ast_channel_fd_isset(chan1, i)) {
2408 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2409 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2410 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2417 /*! Delete a channel from an optimized waitfor */
2418 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2421 struct epoll_event ev;
2424 if (ast_channel_epfd(chan0) == -1)
2427 for (i = 0; i < AST_MAX_FDS; i++) {
2428 if (!ast_channel_fd_isset(chan1, i)) {
2431 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2438 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2440 ast_channel_lock(chan);
2442 ast_channel_softhangup_internal_flag_clear(chan, flag);
2444 if (!ast_channel_softhangup_internal_flag(chan)) {
2445 struct ast_frame *fr;
2447 /* If we have completely cleared the softhangup flag,
2448 * then we need to fully abort the hangup process. This requires
2449 * pulling the END_OF_Q frame out of the channel frame queue if it
2450 * still happens to be there. */
2452 fr = AST_LIST_LAST(ast_channel_readq(chan));
2453 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2454 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2455 AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2460 ast_channel_unlock(chan);
2463 /*! \brief Softly hangup a channel, don't lock */
2464 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2466 ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2467 /* Inform channel driver that we need to be hung up, if it cares */
2468 ast_channel_softhangup_internal_flag_add(chan, cause);
2469 ast_queue_frame(chan, &ast_null_frame);
2470 /* Interrupt any poll call or such */
2471 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2472 pthread_kill(ast_channel_blocker(chan), SIGURG);
2476 /*! \brief Softly hangup a channel, lock */
2477 int ast_softhangup(struct ast_channel *chan, int cause)
2481 ast_channel_lock(chan);
2482 res = ast_softhangup_nolock(chan, cause);
2483 manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2487 ast_channel_name(chan),
2488 ast_channel_uniqueid(chan),
2490 ast_channel_unlock(chan);
2495 static void free_translation(struct ast_channel *clonechan)
2497 if (ast_channel_writetrans(clonechan))
2498 ast_translator_free_path(ast_channel_writetrans(clonechan));
2499 if (ast_channel_readtrans(clonechan))
2500 ast_translator_free_path(ast_channel_readtrans(clonechan));
2501 ast_channel_writetrans_set(clonechan, NULL);
2502 ast_channel_readtrans_set(clonechan, NULL);
2503 if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2504 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2505 ast_format_clear(ast_channel_rawreadformat(clonechan));
2507 struct ast_format tmpfmt;
2508 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2509 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2510 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2514 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2516 struct ast_channel *bridge;
2518 ast_channel_lock(chan);
2519 if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2520 ast_channel_hangupsource_set(chan, source);
2522 bridge = ast_bridged_channel(chan);
2523 ast_channel_unlock(chan);
2525 if (bridge && (force || ast_strlen_zero(ast_channel_hangupsource(bridge)))) {
2526 ast_channel_lock(bridge);
2527 ast_channel_hangupsource_set(chan, source);
2528 ast_channel_unlock(bridge);
2532 static void destroy_hooks(struct ast_channel *chan)
2534 if (ast_channel_audiohooks(chan)) {
2535 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2536 ast_channel_audiohooks_set(chan, NULL);
2539 ast_framehook_list_destroy(chan);
2542 /*! \brief Hangup a channel */
2543 int ast_hangup(struct ast_channel *chan)
2545 char extra_str[64]; /* used for cel logging below */
2548 ast_autoservice_stop(chan);
2550 ast_channel_lock(chan);
2553 * Do the masquerade if someone is setup to masquerade into us.
2555 * NOTE: We must hold the channel lock after testing for a
2556 * pending masquerade and setting the channel as a zombie to
2557 * prevent __ast_channel_masquerade() from setting up a
2558 * masquerade with a dead channel.
2560 while (ast_channel_masq(chan)) {
2561 ast_channel_unlock(chan);
2562 if (ast_do_masquerade(chan)) {
2563 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2565 /* Abort the loop or we might never leave. */
2566 ast_channel_lock(chan);
2569 ast_channel_lock(chan);
2572 if (ast_channel_masqr(chan)) {
2574 * This channel is one which will be masqueraded into something.
2575 * Mark it as a zombie already so ast_do_masquerade() will know
2578 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2579 destroy_hooks(chan);
2580 ast_channel_unlock(chan);
2584 if (!(was_zombie = ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE))) {
2585 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2588 ast_channel_unlock(chan);
2589 ao2_unlink(channels, chan);
2590 ast_channel_lock(chan);
2592 destroy_hooks(chan);
2594 free_translation(chan);
2595 /* Close audio stream */
2596 if (ast_channel_stream(chan)) {
2597 ast_closestream(ast_channel_stream(chan));
2598 ast_channel_stream_set(chan, NULL);
2600 /* Close video stream */
2601 if (ast_channel_vstream(chan)) {
2602 ast_closestream(ast_channel_vstream(chan));
2603 ast_channel_vstream_set(chan, NULL);
2605 if (ast_channel_sched(chan)) {
2606 ast_sched_context_destroy(ast_channel_sched(chan));
2607 ast_channel_sched_set(chan, NULL);
2610 if (ast_channel_generatordata(chan)) { /* Clear any tone stuff remaining */
2611 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2612 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2615 ast_channel_generatordata_set(chan, NULL);
2616 ast_channel_generator_set(chan, NULL);
2618 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"), ""));
2619 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2621 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2622 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2623 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2624 (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2625 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2628 ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2630 if (ast_channel_tech(chan)->hangup) {
2631 ast_channel_tech(chan)->hangup(chan);
2634 ast_debug(1, "Hanging up zombie '%s'\n", ast_channel_name(chan));
2637 ast_channel_unlock(chan);
2640 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2643 "CallerIDNum: %s\r\n"
2644 "CallerIDName: %s\r\n"
2645 "ConnectedLineNum: %s\r\n"
2646 "ConnectedLineName: %s\r\n"
2648 "Cause-txt: %s\r\n",
2649 ast_channel_name(chan),
2650 ast_channel_uniqueid(chan),
2651 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
2652 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
2653 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
2654 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
2655 ast_channel_hangupcause(chan),
2656 ast_cause2str(ast_channel_hangupcause(chan))
2659 if (ast_channel_cdr(chan) && !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_BRIDGED) &&
2660 !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_POST_DISABLED) &&
2661 (ast_channel_cdr(chan)->disposition != AST_CDR_NULL || ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_DIALED))) {
2662 ast_channel_lock(chan);
2663 ast_cdr_end(ast_channel_cdr(chan));
2664 ast_cdr_detach(ast_channel_cdr(chan));
2665 ast_channel_cdr_set(chan, NULL);
2666 ast_channel_unlock(chan);
2669 ast_channel_unref(chan);
2674 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2678 ast_channel_lock(chan);
2680 /* You can't answer an outbound call */
2681 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2682 ast_channel_unlock(chan);
2686 /* Stop if we're a zombie or need a soft hangup */
2687 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2688 ast_channel_unlock(chan);
2692 ast_channel_unlock(chan);
2694 switch (ast_channel_state(chan)) {
2695 case AST_STATE_RINGING:
2696 case AST_STATE_RING:
2697 ast_channel_lock(chan);
2698 if (ast_channel_tech(chan)->answer) {
2699 res = ast_channel_tech(chan)->answer(chan);
2701 ast_setstate(chan, AST_STATE_UP);
2703 ast_cdr_answer(ast_channel_cdr(chan));
2705 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2706 ast_channel_unlock(chan);
2709 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2710 /* Calling ast_cdr_answer when it it has previously been called
2711 * is essentially a no-op, so it is safe.
2714 ast_cdr_answer(ast_channel_cdr(chan));
2721 ast_indicate(chan, -1);
2726 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2729 enum ast_channel_state old_state;
2731 old_state = ast_channel_state(chan);
2732 if ((res = ast_raw_answer(chan, cdr_answer))) {
2736 switch (old_state) {
2737 case AST_STATE_RINGING:
2738 case AST_STATE_RING:
2739 /* wait for media to start flowing, but don't wait any longer
2740 * than 'delay' or 500 milliseconds, whichever is longer
2743 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2744 struct ast_frame *cur, *new;
2745 int ms = MAX(delay, 500);
2746 unsigned int done = 0;
2748 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2751 ms = ast_waitfor(chan, ms);
2753 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2758 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));
2761 cur = ast_read(chan);
2762 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2763 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2768 ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2772 if ((new = ast_frisolate(cur)) != cur) {
2776 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2778 /* if a specific delay period was requested, continue
2779 * until that delay has passed. don't stop just because
2780 * incoming media has arrived.
2786 switch (new->frametype) {
2787 /* all of these frametypes qualify as 'media' */
2788 case AST_FRAME_VOICE:
2789 case AST_FRAME_VIDEO:
2790 case AST_FRAME_TEXT:
2791 case AST_FRAME_DTMF_BEGIN:
2792 case AST_FRAME_DTMF_END:
2793 case AST_FRAME_IMAGE:
2794 case AST_FRAME_HTML:
2795 case AST_FRAME_MODEM:
2798 case AST_FRAME_CONTROL:
2800 case AST_FRAME_NULL:
2811 ast_channel_lock(chan);
2812 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2813 ast_queue_frame_head(chan, cur);
2816 ast_channel_unlock(chan);
2827 int ast_answer(struct ast_channel *chan)
2829 return __ast_answer(chan, 0, 1);
2832 void ast_deactivate_generator(struct ast_channel *chan)
2834 ast_channel_lock(chan);
2835 if (ast_channel_generatordata(chan)) {
2836 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release)
2837 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2838 ast_channel_generatordata_set(chan, NULL);
2839 ast_channel_generator_set(chan, NULL);
2840 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2841 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
2842 ast_settimeout(chan, 0, NULL, NULL);
2844 ast_channel_unlock(chan);
2847 static void generator_write_format_change(struct ast_channel *chan)
2849 ast_channel_lock(chan);
2850 if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
2851 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
2853 ast_channel_unlock(chan);
2856 static int generator_force(const void *data)
2858 /* Called if generator doesn't have data */
2861 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2862 struct ast_channel *chan = (struct ast_channel *)data;
2864 ast_channel_lock(chan);
2865 tmp = ast_channel_generatordata(chan);
2866 ast_channel_generatordata_set(chan, NULL);
2867 if (ast_channel_generator(chan))
2868 generate = ast_channel_generator(chan)->generate;
2869 ast_channel_unlock(chan);
2871 if (!tmp || !generate)
2874 res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
2876 ast_channel_generatordata_set(chan, tmp);
2879 ast_debug(1, "Auto-deactivating generator\n");
2880 ast_deactivate_generator(chan);
2886 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2889 void *generatordata = NULL;
2891 ast_channel_lock(chan);
2892 if (ast_channel_generatordata(chan)) {
2893 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2894 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2897 if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
2900 ast_channel_generatordata_set(chan, generatordata);
2902 ast_settimeout(chan, 50, generator_force, chan);
2903 ast_channel_generator_set(chan, gen);
2905 ast_channel_unlock(chan);
2912 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2913 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2916 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2920 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2922 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2923 int *exception, int *outfd, int *ms)
2925 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2926 int *exception, int *outfd, int *ms)
2929 struct timeval start = { 0 , 0 };
2930 struct pollfd *pfds = NULL;
2935 struct timeval now = { 0, 0 };
2936 struct timeval whentohangup = { 0, 0 }, diff;
2937 struct ast_channel *winner = NULL;
2943 if ((sz = n * AST_MAX_FDS + nfds)) {
2944 pfds = alloca(sizeof(*pfds) * sz);
2945 fdmap = alloca(sizeof(*fdmap) * sz);
2953 /* Perform any pending masquerades */
2954 for (x = 0; x < n; x++) {
2955 if (ast_channel_masq(c[x]) && ast_do_masquerade(c[x])) {
2956 ast_log(LOG_WARNING, "Masquerade failed\n");
2961 ast_channel_lock(c[x]);
2962 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
2963 if (ast_tvzero(whentohangup))
2965 diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
2966 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
2967 /* Should already be hungup */
2968 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
2969 ast_channel_unlock(c[x]);
2972 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
2973 whentohangup = diff;
2975 ast_channel_unlock(c[x]);
2977 /* Wait full interval */
2979 /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
2980 if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
2981 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
2982 if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
2985 } else if (!ast_tvzero(whentohangup) && rms < 0) {
2986 /* Tiny corner case... call would need to last >24 days */
2990 * Build the pollfd array, putting the channels' fds first,
2991 * followed by individual fds. Order is important because
2992 * individual fd's must have priority over channel fds.
2995 for (x = 0; x < n; x++) {
2996 for (y = 0; y < AST_MAX_FDS; y++) {
2997 fdmap[max].fdno = y; /* fd y is linked to this pfds */
2998 fdmap[max].chan = x; /* channel x is linked to this pfds */
2999 max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3001 CHECK_BLOCKING(c[x]);
3003 /* Add the individual fds */
3004 for (x = 0; x < nfds; x++) {
3005 fdmap[max].chan = -1;
3006 max += ast_add_fd(&pfds[max], fds[x]);
3010 start = ast_tvnow();
3012 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3017 res = ast_poll(pfds, max, kbrms);
3020 } while (!res && (rms > 0));
3022 res = ast_poll(pfds, max, rms);
3024 for (x = 0; x < n; x++)
3025 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3026 if (res < 0) { /* Simulate a timeout if we were interrupted */
3031 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
3033 for (x = 0; x < n; x++) {
3034 if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3035 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3041 if (res == 0) { /* no fd ready, reset timeout and done */
3042 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
3046 * Then check if any channel or fd has a pending event.
3047 * Remember to check channels first and fds last, as they
3048 * must have priority on setting 'winner'
3050 for (x = 0; x < max; x++) {
3051 res = pfds[x].revents;
3054 if (fdmap[x].chan >= 0) { /* this is a channel */
3055 winner = c[fdmap[x].chan]; /* override previous winners */
3057 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3059 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3060 ast_channel_fdno_set(winner, fdmap[x].fdno);
3061 } else { /* this is an fd */
3063 *outfd = pfds[x].fd;
3065 *exception = (res & POLLPRI) ? -1 : 0;
3070 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3078 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3080 struct timeval start = { 0 , 0 };
3082 struct epoll_event ev[1];
3083 long diff, rms = *ms;
3084 struct ast_channel *winner = NULL;
3085 struct ast_epoll_data *aed = NULL;
3088 /* See if this channel needs to be masqueraded */
3089 if (ast_channel_masq(chan) && ast_do_masquerade(chan)) {
3090 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", ast_channel_name(chan));
3095 ast_channel_lock(chan);
3096 /* Figure out their timeout */
3097 if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3098 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow())) < 0) {
3099 /* They should already be hungup! */
3100 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3101 ast_channel_unlock(chan);
3104 /* If this value is smaller then the current one... make it priority */
3109 ast_channel_unlock(chan);
3111 /* Time to make this channel block... */
3112 CHECK_BLOCKING(chan);
3115 start = ast_tvnow();
3117 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3118 res = epoll_wait(ast_channel_epfd(chan), ev, 1, rms);
3121 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
3123 /* Simulate a timeout if we were interrupted */
3130 /* If this channel has a timeout see if it expired */
3131 if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3132 if (ast_tvdiff_ms(ast_tvnow(), *ast_channel_whentohangup(chan)) >= 0) {
3133 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3138 /* No fd ready, reset timeout and be done for now */
3144 /* See what events are pending */
3145 aed = ev[0].data.ptr;
3146 ast_channel_fdno_set(chan, aed->which);
3147 if (ev[0].events & EPOLLPRI)
3148 ast_set_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3150 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3153 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3161 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3163 struct timeval start = { 0 , 0 };
3165 struct epoll_event ev[25] = { { 0, } };
3166 struct timeval now = { 0, 0 };
3167 long whentohangup = 0, diff = 0, rms = *ms;
3168 struct ast_channel *winner = NULL;
3170 for (i = 0; i < n; i++) {
3171 if (ast_channel_masq(c[i]) && ast_do_masquerade(c[i])) {
3172 ast_log(LOG_WARNING, "Masquerade failed\n");
3177 ast_channel_lock(c[i]);
3178 if (!ast_tvzero(*ast_channel_whentohangup(c[i]))) {
3179 if (whentohangup == 0)
3181 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(c[i]), now)) < 0) {
3182 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3183 ast_channel_unlock(c[i]);
3186 if (!whentohangup || whentohangup > diff)
3187 whentohangup = diff;
3189 ast_channel_unlock(c[i]);
3190 CHECK_BLOCKING(c[i]);
3196 if (*ms >= 0 && *ms < rms)
3201 start = ast_tvnow();
3203 res = epoll_wait(ast_channel_epfd(c[0]), ev, 25, rms);
3205 for (i = 0; i < n; i++)
3206 ast_clear_flag(ast_channel_flags(c[i]), AST_FLAG_BLOCKING);
3216 for (i = 0; i < n; i++) {
3217 if (!ast_tvzero(*ast_channel_whentohangup(c[i])) && ast_tvdiff_ms(now, *ast_channel_whentohangup(c[i])) >= 0) {
3218 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3230 for (i = 0; i < res; i++) {
3231 struct ast_epoll_data *aed = ev[i].data.ptr;
3233 if (!ev[i].events || !aed)
3237 if (ev[i].events & EPOLLPRI)
3238 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3240 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3241 ast_channel_fdno_set(winner, aed->which);
3245 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3253 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3254 int *exception, int *outfd, int *ms)
3256 /* Clear all provided values in one place. */
3262 /* If no epoll file descriptor is available resort to classic nandfds */
3263 if (!n || nfds || ast_channel_epfd(c[0]) == -1)
3264 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3265 else if (!nfds && n == 1)
3266 return ast_waitfor_nandfds_simple(c[0], ms);
3268 return ast_waitfor_nandfds_complex(c, n, ms);
3272 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3274 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3277 int ast_waitfor(struct ast_channel *c, int ms)
3279 int oldms = ms; /* -1 if no timeout */
3281 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3282 if ((ms < 0) && (oldms < 0))
3287 /* XXX never to be called with ms = -1 */
3288 int ast_waitfordigit(struct ast_channel *c, int ms)
3290 return ast_waitfordigit_full(c, ms, -1, -1);
3293 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3296 unsigned int real_rate = rate, max_rate;
3298 ast_channel_lock(c);
3300 if (ast_channel_timingfd(c) == -1) {
3301 ast_channel_unlock(c);
3310 if (rate && rate > (max_rate = ast_timer_get_max_rate(ast_channel_timer(c)))) {
3311 real_rate = max_rate;
3314 ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3316 res = ast_timer_set_rate(ast_channel_timer(c), real_rate);
3318 ast_channel_timingfunc_set(c, func);
3319 ast_channel_timingdata_set(c, data);
3321 if (func == NULL && rate == 0 && ast_channel_fdno(c) == AST_TIMING_FD) {
3322 /* Clearing the timing func and setting the rate to 0
3323 * means that we don't want to be reading from the timingfd
3324 * any more. Setting c->fdno to -1 means we won't have any
3325 * errant reads from the timingfd, meaning we won't potentially
3326 * miss any important frames.
3328 ast_channel_fdno_set(c, -1);
3331 ast_channel_unlock(c);
3336 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
3338 /* Stop if we're a zombie or need a soft hangup */
3339 if (ast_test_flag(ast_channel_flags(c), AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3342 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3343 ast_set_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3345 /* Wait for a digit, no more than ms milliseconds total. */
3348 struct ast_channel *rchan;
3352 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3354 if (!rchan && outfd < 0 && ms) {