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"
75 #include "asterisk/features.h"
76 #include "asterisk/bridging.h"
77 #include "asterisk/test.h"
78 #include "asterisk/stasis_channels.h"
84 #include <sys/epoll.h>
87 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
90 #endif /* defined(HAVE_PRI) */
91 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
93 struct ast_epoll_data {
94 struct ast_channel *chan;
98 /* uncomment if you have problems with 'monitoring' synchronized files */
100 #define MONITOR_CONSTANT_DELAY
101 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
104 /*! \brief Prevent new channel allocation if shutting down. */
105 static int shutting_down;
107 static int uniqueint;
108 static int chancount;
110 unsigned long global_fin, global_fout;
112 AST_THREADSTORAGE(state2str_threadbuf);
113 #define STATE2STR_BUFSIZE 32
115 /*! Default amount of time to use when emulating a digit as a begin and end
117 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
119 /*! Minimum amount of time between the end of the last digit and the beginning
120 * of a new one - 45ms */
121 #define AST_MIN_DTMF_GAP 45
123 /*! \brief List of channel drivers */
125 const struct ast_channel_tech *tech;
126 AST_LIST_ENTRY(chanlist) list;
130 /*! \brief Structure to hold channel context backtrace data */
131 struct ast_chan_trace_data {
133 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
136 /*! \brief Structure to save contexts where an ast_chan has been into */
137 struct ast_chan_trace {
138 char context[AST_MAX_CONTEXT];
139 char exten[AST_MAX_EXTENSION];
141 AST_LIST_ENTRY(ast_chan_trace) entry;
145 /*! \brief the list of registered channel types */
146 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
149 #define NUM_CHANNEL_BUCKETS 61
151 #define NUM_CHANNEL_BUCKETS 1567
154 /*! \brief All active channels on the system */
155 static struct ao2_container *channels;
157 /*! \brief map AST_CAUSE's to readable string representations
167 static const struct causes_map causes[] = {
168 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
169 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
170 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
171 { AST_CAUSE_MISDIALLED_TRUNK_PREFIX, "MISDIALLED_TRUNK_PREFIX", "Misdialed trunk prefix" },
172 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
173 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
174 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
175 { AST_CAUSE_NUMBER_PORTED_NOT_HERE, "NUMBER_PORTED_NOT_HERE", "Number ported elsewhere" },
176 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
177 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
178 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
179 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
180 { AST_CAUSE_SUBSCRIBER_ABSENT, "SUBSCRIBER_ABSENT", "Subscriber absent" },
181 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
182 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
183 { AST_CAUSE_REDIRECTED_TO_NEW_DESTINATION, "REDIRECTED_TO_NEW_DESTINATION", "Redirected to new destination" },
184 { AST_CAUSE_ANSWERED_ELSEWHERE, "ANSWERED_ELSEWHERE", "Answered elsewhere" },
185 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
186 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
187 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
188 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
189 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
190 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
191 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
192 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
193 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
194 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
195 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
196 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
197 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
198 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
199 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
200 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
201 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
202 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
203 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
204 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
205 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
206 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
207 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
208 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
209 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
210 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
211 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
212 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
213 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
214 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
215 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
216 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
219 struct ast_variable *ast_channeltype_list(void)
222 struct ast_variable *var = NULL, *prev = NULL;
224 AST_RWLIST_RDLOCK(&backends);
225 AST_RWLIST_TRAVERSE(&backends, cl, list) {
227 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
230 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
234 AST_RWLIST_UNLOCK(&backends);
239 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
240 static const char *party_number_ton2str(int ton)
242 #if defined(HAVE_PRI)
243 switch ((ton >> 4) & 0x07) {
244 case PRI_TON_INTERNATIONAL:
245 return "International";
246 case PRI_TON_NATIONAL:
248 case PRI_TON_NET_SPECIFIC:
249 return "Network Specific";
250 case PRI_TON_SUBSCRIBER:
252 case PRI_TON_ABBREVIATED:
253 return "Abbreviated";
254 case PRI_TON_RESERVED:
256 case PRI_TON_UNKNOWN:
260 #endif /* defined(HAVE_PRI) */
263 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
265 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
266 static const char *party_number_plan2str(int plan)
268 #if defined(HAVE_PRI)
269 switch (plan & 0x0F) {
271 case PRI_NPI_UNKNOWN:
273 case PRI_NPI_E163_E164:
274 return "Public (E.163/E.164)";
276 return "Data (X.121)";
278 return "Telex (F.69)";
279 case PRI_NPI_NATIONAL:
280 return "National Standard";
281 case PRI_NPI_PRIVATE:
283 case PRI_NPI_RESERVED:
286 #endif /* defined(HAVE_PRI) */
289 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
291 /*! \brief Show channel types - CLI command */
292 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
294 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
300 e->command = "core show channeltypes";
302 "Usage: core show channeltypes\n"
303 " Lists available channel types registered in your\n"
304 " Asterisk server.\n";
311 return CLI_SHOWUSAGE;
313 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
314 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
316 AST_RWLIST_RDLOCK(&backends);
317 AST_RWLIST_TRAVERSE(&backends, cl, list) {
318 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
319 (cl->tech->devicestate) ? "yes" : "no",
320 (cl->tech->indicate) ? "yes" : "no",
321 (cl->tech->transfer) ? "yes" : "no");
324 AST_RWLIST_UNLOCK(&backends);
326 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
333 static char *complete_channeltypes(struct ast_cli_args *a)
343 wordlen = strlen(a->word);
345 AST_RWLIST_RDLOCK(&backends);
346 AST_RWLIST_TRAVERSE(&backends, cl, list) {
347 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
348 ret = ast_strdup(cl->tech->type);
352 AST_RWLIST_UNLOCK(&backends);
357 /*! \brief Show details about a channel driver - CLI command */
358 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
360 struct chanlist *cl = NULL;
365 e->command = "core show channeltype";
367 "Usage: core show channeltype <name>\n"
368 " Show details about the specified channel type, <name>.\n";
371 return complete_channeltypes(a);
375 return CLI_SHOWUSAGE;
377 AST_RWLIST_RDLOCK(&backends);
379 AST_RWLIST_TRAVERSE(&backends, cl, list) {
380 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
386 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
387 AST_RWLIST_UNLOCK(&backends);
392 "-- Info about channel driver: %s --\n"
393 " Device State: %s\n"
396 " Capabilities: %s\n"
400 " Image Support: %s\n"
401 " Text Support: %s\n",
403 (cl->tech->devicestate) ? "yes" : "no",
404 (cl->tech->indicate) ? "yes" : "no",
405 (cl->tech->transfer) ? "yes" : "no",
406 ast_getformatname_multiple(buf, sizeof(buf), cl->tech->capabilities),
407 (cl->tech->send_digit_begin) ? "yes" : "no",
408 (cl->tech->send_digit_end) ? "yes" : "no",
409 (cl->tech->send_html) ? "yes" : "no",
410 (cl->tech->send_image) ? "yes" : "no",
411 (cl->tech->send_text) ? "yes" : "no"
415 AST_RWLIST_UNLOCK(&backends);
420 static struct ast_cli_entry cli_channel[] = {
421 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
422 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
425 static struct ast_frame *kill_read(struct ast_channel *chan)
427 /* Hangup channel. */
431 static struct ast_frame *kill_exception(struct ast_channel *chan)
433 /* Hangup channel. */
437 static int kill_write(struct ast_channel *chan, struct ast_frame *frame)
439 /* Hangup channel. */
443 static int kill_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
445 /* No problem fixing up the channel. */
449 static int kill_hangup(struct ast_channel *chan)
451 ast_channel_tech_pvt_set(chan, NULL);
456 * \brief Kill the channel channel driver technology descriptor.
459 * The purpose of this channel technology is to encourage the
460 * channel to hangup as quickly as possible.
462 * \note Used by DTMF atxfer and zombie channels.
464 const struct ast_channel_tech ast_kill_tech = {
466 .description = "Kill channel (should not see this)",
468 .exception = kill_exception,
471 .hangup = kill_hangup,
475 /*! \brief Destructor for the channel trace datastore */
476 static void ast_chan_trace_destroy_cb(void *data)
478 struct ast_chan_trace *trace;
479 struct ast_chan_trace_data *traced = data;
480 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
486 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
487 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
489 .destroy = ast_chan_trace_destroy_cb
492 /*! \brief Put the channel backtrace in a string */
493 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
496 struct ast_chan_trace *trace;
497 struct ast_chan_trace_data *traced;
498 struct ast_datastore *store;
500 ast_channel_lock(chan);
501 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
503 ast_channel_unlock(chan);
506 traced = store->data;
508 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
509 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
510 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
516 ast_channel_unlock(chan);
520 /* !\brief Whether or not context tracing is enabled */
521 int ast_channel_trace_is_enabled(struct ast_channel *chan)
523 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
526 return ((struct ast_chan_trace_data *)store->data)->enabled;
529 /*! \brief Update the context backtrace data if tracing is enabled */
530 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
532 struct ast_chan_trace *trace;
533 if (!traced->enabled)
535 /* If the last saved context does not match the current one
536 OR we have not saved any context so far, then save the current context */
537 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan))) ||
538 (AST_LIST_EMPTY(&traced->trace))) {
539 /* Just do some debug logging */
540 if (AST_LIST_EMPTY(&traced->trace))
541 ast_debug(1, "Setting initial trace context to %s\n", ast_channel_context(chan));
543 ast_debug(1, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan));
544 /* alloc or bail out */
545 trace = ast_malloc(sizeof(*trace));
548 /* save the current location and store it in the trace list */
549 ast_copy_string(trace->context, ast_channel_context(chan), sizeof(trace->context));
550 ast_copy_string(trace->exten, ast_channel_exten(chan), sizeof(trace->exten));
551 trace->priority = ast_channel_priority(chan);
552 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
557 /*! \brief Update the context backtrace if tracing is enabled */
558 int ast_channel_trace_update(struct ast_channel *chan)
560 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
563 return ast_channel_trace_data_update(chan, store->data);
566 /*! \brief Enable context tracing in the channel */
567 int ast_channel_trace_enable(struct ast_channel *chan)
569 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
570 struct ast_chan_trace_data *traced;
572 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
575 traced = ast_calloc(1, sizeof(*traced));
577 ast_datastore_free(store);
580 store->data = traced;
581 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
582 ast_channel_datastore_add(chan, store);
584 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
585 ast_channel_trace_data_update(chan, store->data);
589 /*! \brief Disable context tracing in the channel */
590 int ast_channel_trace_disable(struct ast_channel *chan)
592 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
595 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
598 #endif /* CHANNEL_TRACE */
600 /*! \brief Checks to see if a channel is needing hang up */
601 int ast_check_hangup(struct ast_channel *chan)
603 if (ast_channel_softhangup_internal_flag(chan)) /* yes if soft hangup flag set */
605 if (ast_tvzero(*ast_channel_whentohangup(chan))) /* no if no hangup scheduled */
607 if (ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()) > 0) /* no if hangup time has not come yet. */
609 ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()));
610 ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(chan));
611 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT); /* record event */
615 int ast_check_hangup_locked(struct ast_channel *chan)
618 ast_channel_lock(chan);
619 res = ast_check_hangup(chan);
620 ast_channel_unlock(chan);
624 void ast_channel_softhangup_withcause_locked(struct ast_channel *chan, int causecode)
626 ast_channel_lock(chan);
629 ast_debug(1, "Setting hangupcause of channel %s to %d (is %d now)\n",
630 ast_channel_name(chan), causecode, ast_channel_hangupcause(chan));
632 ast_channel_hangupcause_set(chan, causecode);
635 ast_softhangup_nolock(chan, AST_SOFTHANGUP_EXPLICIT);
637 ast_channel_unlock(chan);
640 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
642 struct ast_channel *chan = obj;
644 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
649 void ast_begin_shutdown(int hangup)
654 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
658 /*! \brief returns number of active/allocated channels */
659 int ast_active_channels(void)
661 return channels ? ao2_container_count(channels) : 0;
664 int ast_undestroyed_channels(void)
666 return ast_atomic_fetchadd_int(&chancount, 0);
669 /*! \brief Cancel a shutdown in progress */
670 void ast_cancel_shutdown(void)
675 /*! \brief Returns non-zero if Asterisk is being shut down */
676 int ast_shutting_down(void)
678 return shutting_down;
681 /*! \brief Set when to hangup channel */
682 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
684 if (ast_tvzero(offset)) {
685 ast_channel_whentohangup_set(chan, &offset);
687 struct timeval tv = ast_tvadd(offset, ast_tvnow());
688 ast_channel_whentohangup_set(chan, &tv);
690 ast_queue_frame(chan, &ast_null_frame);
694 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
696 struct timeval when = { offset, };
697 ast_channel_setwhentohangup_tv(chan, when);
700 /*! \brief Compare a offset with when to hangup channel */
701 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
703 struct timeval whentohangup;
705 if (ast_tvzero(*ast_channel_whentohangup(chan)))
706 return ast_tvzero(offset) ? 0 : -1;
708 if (ast_tvzero(offset))
711 whentohangup = ast_tvadd(offset, ast_tvnow());
713 return ast_tvdiff_ms(whentohangup, *ast_channel_whentohangup(chan));
716 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
718 struct timeval when = { offset, };
719 return ast_channel_cmpwhentohangup_tv(chan, when);
722 /*! \brief Register a new telephony channel in Asterisk */
723 int ast_channel_register(const struct ast_channel_tech *tech)
725 struct chanlist *chan;
727 AST_RWLIST_WRLOCK(&backends);
729 AST_RWLIST_TRAVERSE(&backends, chan, list) {
730 if (!strcasecmp(tech->type, chan->tech->type)) {
731 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
732 AST_RWLIST_UNLOCK(&backends);
737 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
738 AST_RWLIST_UNLOCK(&backends);
742 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
744 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
746 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
748 AST_RWLIST_UNLOCK(&backends);
753 /*! \brief Unregister channel driver */
754 void ast_channel_unregister(const struct ast_channel_tech *tech)
756 struct chanlist *chan;
758 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
760 AST_RWLIST_WRLOCK(&backends);
762 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
763 if (chan->tech == tech) {
764 AST_LIST_REMOVE_CURRENT(list);
766 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
770 AST_LIST_TRAVERSE_SAFE_END;
772 AST_RWLIST_UNLOCK(&backends);
775 /*! \brief Get handle to channel driver based on name */
776 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
778 struct chanlist *chanls;
779 const struct ast_channel_tech *ret = NULL;
781 AST_RWLIST_RDLOCK(&backends);
783 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
784 if (!strcasecmp(name, chanls->tech->type)) {
790 AST_RWLIST_UNLOCK(&backends);
795 /*! \brief Gives the string form of a given hangup cause */
796 const char *ast_cause2str(int cause)
800 for (x = 0; x < ARRAY_LEN(causes); x++) {
801 if (causes[x].cause == cause)
802 return causes[x].desc;
808 /*! \brief Convert a symbolic hangup cause to number */
809 int ast_str2cause(const char *name)
813 for (x = 0; x < ARRAY_LEN(causes); x++)
814 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
815 return causes[x].cause;
820 static void publish_cache_clear(struct ast_channel *chan)
822 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
824 message = stasis_cache_clear_create(ast_channel_snapshot_type(), ast_channel_uniqueid(chan));
825 stasis_publish(ast_channel_topic(chan), message);
828 /*! \brief Gives the string form of a given channel state.
830 * \note This function is not reentrant.
834 const char *ast_state2str(enum ast_channel_state state)
841 case AST_STATE_RESERVED:
843 case AST_STATE_OFFHOOK:
845 case AST_STATE_DIALING:
849 case AST_STATE_RINGING:
855 case AST_STATE_DIALING_OFFHOOK:
856 return "Dialing Offhook";
857 case AST_STATE_PRERING:
860 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
862 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
867 /*! \brief Gives the string form of a given transfer capability */
868 char *ast_transfercapability2str(int transfercapability)
870 switch (transfercapability) {
871 case AST_TRANS_CAP_SPEECH:
873 case AST_TRANS_CAP_DIGITAL:
875 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
876 return "RESTRICTED_DIGITAL";
877 case AST_TRANS_CAP_3_1K_AUDIO:
879 case AST_TRANS_CAP_DIGITAL_W_TONES:
880 return "DIGITAL_W_TONES";
881 case AST_TRANS_CAP_VIDEO:
888 /*! \brief Pick the best audio codec */
889 struct ast_format *ast_best_codec(struct ast_format_cap *cap, struct ast_format *result)
891 /* This just our opinion, expressed in code. We are asked to choose
892 the best codec to use, given no information */
893 static const enum ast_format_id prefs[] =
895 /*! Okay, ulaw is used by all telephony equipment, so start with it */
897 /*! Unless of course, you're a silly European, so then prefer ALAW */
903 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
905 /*! Okay, well, signed linear is easy to translate into other stuff */
906 AST_FORMAT_SLINEAR192,
907 AST_FORMAT_SLINEAR96,
908 AST_FORMAT_SLINEAR48,
909 AST_FORMAT_SLINEAR44,
910 AST_FORMAT_SLINEAR32,
911 AST_FORMAT_SLINEAR24,
912 AST_FORMAT_SLINEAR16,
913 AST_FORMAT_SLINEAR12,
915 /*! G.726 is standard ADPCM, in RFC3551 packing order */
917 /*! G.726 is standard ADPCM, in AAL2 packing order */
918 AST_FORMAT_G726_AAL2,
919 /*! ADPCM has great sound quality and is still pretty easy to translate */
921 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
922 translate and sounds pretty good */
924 /*! iLBC is not too bad */
926 /*! Speex is free, but computationally more expensive than GSM */
930 /*! SILK is pretty awesome. */
932 /*! CELT supports crazy high sample rates */
934 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
937 /*! G.729a is faster than 723 and slightly less expensive */
939 /*! Down to G.723.1 which is proprietary but at least designed for voice */
945 /* Find the first preferred codec in the format given */
946 for (x = 0; x < ARRAY_LEN(prefs); x++) {
947 if (ast_format_cap_best_byid(cap, prefs[x], result)) {
952 ast_format_clear(result);
953 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
958 static const struct ast_channel_tech null_tech = {
960 .description = "Null channel (should not see this)",
963 static void ast_channel_destructor(void *obj);
964 static void ast_dummy_channel_destructor(void *obj);
966 /*! \brief Create a new channel structure */
967 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
968 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
969 const char *acctcode, const char *exten, const char *context,
970 const char *linkedid, const int amaflag, const char *file, int line,
971 const char *function, const char *name_fmt, va_list ap)
973 struct ast_channel *tmp;
974 struct varshead *headp;
975 char *tech = "", *tech2 = NULL;
976 struct ast_format_cap *nativeformats;
977 struct ast_sched_context *schedctx;
978 struct ast_timer *timer;
981 /* If shutting down, don't allocate any new channels */
982 if (ast_shutting_down()) {
983 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
987 if (!(tmp = ast_channel_internal_alloc(ast_channel_destructor))) {
988 /* Channel structure allocation failure. */
991 if (!(nativeformats = ast_format_cap_alloc())) {
993 /* format capabilities structure allocation failure */
996 ast_channel_nativeformats_set(tmp, nativeformats);
999 * Init file descriptors to unopened state so
1000 * the destructor can know not to close them.
1002 ast_channel_timingfd_set(tmp, -1);
1003 ast_channel_internal_alertpipe_clear(tmp);
1004 ast_channel_internal_fd_clear_all(tmp);
1007 ast_channel_epfd_set(tmp, epoll_create(25));
1010 if (!(schedctx = ast_sched_context_create())) {
1011 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
1012 return ast_channel_unref(tmp);
1014 ast_channel_sched_set(tmp, schedctx);
1016 ast_party_dialed_init(ast_channel_dialed(tmp));
1017 ast_party_caller_init(ast_channel_caller(tmp));
1018 ast_party_connected_line_init(ast_channel_connected(tmp));
1019 ast_party_redirecting_init(ast_channel_redirecting(tmp));
1022 ast_channel_caller(tmp)->id.name.valid = 1;
1023 ast_channel_caller(tmp)->id.name.str = ast_strdup(cid_name);
1024 if (!ast_channel_caller(tmp)->id.name.str) {
1025 return ast_channel_unref(tmp);
1029 ast_channel_caller(tmp)->id.number.valid = 1;
1030 ast_channel_caller(tmp)->id.number.str = ast_strdup(cid_num);
1031 if (!ast_channel_caller(tmp)->id.number.str) {
1032 return ast_channel_unref(tmp);
1036 if ((timer = ast_timer_open())) {
1037 ast_channel_timer_set(tmp, timer);
1038 if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
1041 ast_channel_timingfd_set(tmp, ast_timer_fd(ast_channel_timer(tmp)));
1045 * This is the last place the channel constructor can fail.
1047 * The destructor takes advantage of this fact to ensure that the
1048 * AST_CEL_CHANNEL_END is not posted if we have not posted the
1049 * AST_CEL_CHANNEL_START yet.
1052 if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
1053 return ast_channel_unref(tmp);
1056 /* Always watch the alertpipe */
1057 ast_channel_set_fd(tmp, AST_ALERT_FD, ast_channel_internal_alert_readfd(tmp));
1058 /* And timing pipe */
1059 ast_channel_set_fd(tmp, AST_TIMING_FD, ast_channel_timingfd(tmp));
1062 ast_channel_state_set(tmp, state);
1064 ast_channel_streamid_set(tmp, -1);
1066 ast_channel_fin_set(tmp, global_fin);
1067 ast_channel_fout_set(tmp, global_fout);
1070 ast_channel_creationtime_set(tmp, &now);
1072 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1073 ast_channel_uniqueid_build(tmp, "%li.%d", (long) time(NULL),
1074 ast_atomic_fetchadd_int(&uniqueint, 1));
1076 ast_channel_uniqueid_build(tmp, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
1077 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1080 if (!ast_strlen_zero(linkedid)) {
1081 ast_channel_linkedid_set(tmp, linkedid);
1083 ast_channel_linkedid_set(tmp, ast_channel_uniqueid(tmp));
1086 ast_channel_internal_setup_topics(tmp);
1088 if (!ast_strlen_zero(name_fmt)) {
1089 char *slash, *slash2;
1090 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1091 * And they all use slightly different formats for their name string.
1092 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1093 * This means, that the stringfields must have a routine that takes the va_lists directly, and
1094 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1095 * This new function was written so this can be accomplished.
1097 ast_channel_name_build_va(tmp, name_fmt, ap);
1098 tech = ast_strdupa(ast_channel_name(tmp));
1099 if ((slash = strchr(tech, '/'))) {
1100 if ((slash2 = strchr(slash + 1, '/'))) {
1108 * Start the string with '-' so it becomes an empty string
1109 * in the destructor.
1111 ast_channel_name_set(tmp, "-**Unknown**");
1114 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1116 /* These 4 variables need to be set up for the cdr_init() to work right */
1118 ast_channel_amaflags_set(tmp, amaflag);
1120 ast_channel_amaflags_set(tmp, ast_default_amaflags);
1123 if (!ast_strlen_zero(acctcode))
1124 ast_channel_accountcode_set(tmp, acctcode);
1126 ast_channel_accountcode_set(tmp, ast_default_accountcode);
1128 ast_channel_context_set(tmp, S_OR(context, "default"));
1129 ast_channel_exten_set(tmp, S_OR(exten, "s"));
1130 ast_channel_priority_set(tmp, 1);
1132 ast_channel_cdr_set(tmp, ast_cdr_alloc());
1133 ast_cdr_init(ast_channel_cdr(tmp), tmp);
1134 ast_cdr_start(ast_channel_cdr(tmp));
1136 ast_atomic_fetchadd_int(&chancount, +1);
1137 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1139 headp = ast_channel_varshead(tmp);
1140 AST_LIST_HEAD_INIT_NOLOCK(headp);
1142 ast_pbx_hangup_handler_init(tmp);
1143 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1145 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_autochans(tmp));
1147 ast_channel_language_set(tmp, defaultlanguage);
1149 ast_channel_tech_set(tmp, &null_tech);
1151 ao2_link(channels, tmp);
1154 * And now, since the channel structure is built, and has its name, let's
1155 * call the manager event generator with this Newchannel event. This is the
1156 * proper and correct place to make this call, but you sure do have to pass
1157 * a lot of data into this func to do it here!
1159 if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1160 ast_publish_channel_state(tmp);
1163 ast_channel_internal_finalize(tmp);
1167 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1168 const char *cid_name, const char *acctcode,
1169 const char *exten, const char *context,
1170 const char *linkedid, const int amaflag,
1171 const char *file, int line, const char *function,
1172 const char *name_fmt, ...)
1175 struct ast_channel *result;
1177 va_start(ap, name_fmt);
1178 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1179 linkedid, amaflag, file, line, function, name_fmt, ap);
1185 /* only do the minimum amount of work needed here to make a channel
1186 * structure that can be used to expand channel vars */
1187 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1188 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1190 struct ast_channel *ast_dummy_channel_alloc(void)
1193 struct ast_channel *tmp;
1194 struct varshead *headp;
1196 if (!(tmp = ast_channel_internal_alloc(ast_dummy_channel_destructor))) {
1197 /* Dummy channel structure allocation failure. */
1201 ast_pbx_hangup_handler_init(tmp);
1202 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1205 * Init file descriptors to unopened state just in case
1206 * autoservice is called on the channel or something tries to
1207 * read a frame from it.
1209 ast_channel_timingfd_set(tmp, -1);
1210 ast_channel_internal_alertpipe_clear(tmp);
1211 ast_channel_internal_fd_clear_all(tmp);
1213 ast_channel_epfd_set(tmp, -1);
1216 ast_channel_internal_setup_topics(tmp);
1218 headp = ast_channel_varshead(tmp);
1219 AST_LIST_HEAD_INIT_NOLOCK(headp);
1224 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1226 struct ast_frame *f;
1227 struct ast_frame *cur;
1228 unsigned int new_frames = 0;
1229 unsigned int new_voice_frames = 0;
1230 unsigned int queued_frames = 0;
1231 unsigned int queued_voice_frames = 0;
1232 AST_LIST_HEAD_NOLOCK(,ast_frame) frames;
1234 ast_channel_lock(chan);
1237 * Check the last frame on the queue if we are queuing the new
1240 cur = AST_LIST_LAST(ast_channel_readq(chan));
1241 if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1242 switch (cur->subclass.integer) {
1243 case AST_CONTROL_END_OF_Q:
1244 if (fin->frametype == AST_FRAME_CONTROL
1245 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1247 * Destroy the end-of-Q marker frame so we can queue the hangup
1248 * frame in its place.
1250 AST_LIST_REMOVE(ast_channel_readq(chan), cur, frame_list);
1254 * This has degenerated to a normal queue append anyway. Since
1255 * we just destroyed the last frame in the queue we must make
1256 * sure that "after" is NULL or bad things will happen.
1262 case AST_CONTROL_HANGUP:
1263 /* Don't queue anything. */
1264 ast_channel_unlock(chan);
1271 /* Build copies of all the new frames and count them */
1272 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1273 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1274 if (!(f = ast_frdup(cur))) {
1275 if (AST_LIST_FIRST(&frames)) {
1276 ast_frfree(AST_LIST_FIRST(&frames));
1278 ast_channel_unlock(chan);
1282 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1284 if (f->frametype == AST_FRAME_VOICE) {
1289 /* Count how many frames exist on the queue */
1290 AST_LIST_TRAVERSE(ast_channel_readq(chan), cur, frame_list) {
1292 if (cur->frametype == AST_FRAME_VOICE) {
1293 queued_voice_frames++;
1297 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1299 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1300 AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), cur, frame_list) {
1301 /* Save the most recent frame */
1302 if (!AST_LIST_NEXT(cur, frame_list)) {
1304 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1308 AST_LIST_REMOVE_CURRENT(frame_list);
1312 AST_LIST_TRAVERSE_SAFE_END;
1316 AST_LIST_INSERT_LIST_AFTER(ast_channel_readq(chan), &frames, after, frame_list);
1319 AST_LIST_APPEND_LIST(&frames, ast_channel_readq(chan), frame_list);
1320 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_readq(chan));
1322 AST_LIST_APPEND_LIST(ast_channel_readq(chan), &frames, frame_list);
1325 if (ast_channel_alert_writable(chan)) {
1326 if (ast_channel_alert_write(chan)) {
1327 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1328 ast_channel_name(chan), queued_frames, strerror(errno));
1330 } else if (ast_channel_timingfd(chan) > -1) {
1331 ast_timer_enable_continuous(ast_channel_timer(chan));
1332 } else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
1333 pthread_kill(ast_channel_blocker(chan), SIGURG);
1336 ast_channel_unlock(chan);
1341 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1343 return __ast_queue_frame(chan, fin, 0, NULL);
1346 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1348 return __ast_queue_frame(chan, fin, 1, NULL);
1351 /*! \internal \brief Publish a channel blob message */
1352 static void publish_channel_blob(struct ast_channel *chan,
1353 struct stasis_message_type *type, struct ast_json *blob)
1355 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1357 blob = ast_json_null();
1360 message = ast_channel_blob_create(chan, type, blob);
1362 stasis_publish(ast_channel_topic(chan), message);
1366 /*! \brief Queue a hangup frame for channel */
1367 int ast_queue_hangup(struct ast_channel *chan)
1369 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1372 /* Yeah, let's not change a lock-critical value without locking */
1373 ast_channel_lock(chan);
1374 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1375 publish_channel_blob(chan, ast_channel_hangup_request_type(), NULL);
1377 res = ast_queue_frame(chan, &f);
1378 ast_channel_unlock(chan);
1382 /*! \brief Queue a hangup frame for channel */
1383 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1385 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
1386 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1390 f.data.uint32 = cause;
1393 /* Yeah, let's not change a lock-critical value without locking */
1394 ast_channel_lock(chan);
1395 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1397 f.data.uint32 = ast_channel_hangupcause(chan);
1399 blob = ast_json_pack("{s: i}",
1401 publish_channel_blob(chan, ast_channel_hangup_request_type(), blob);
1403 res = ast_queue_frame(chan, &f);
1404 ast_channel_unlock(chan);
1408 int ast_queue_hold(struct ast_channel *chan, const char *musicclass)
1410 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
1411 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HOLD };
1414 if (!ast_strlen_zero(musicclass)) {
1415 f.data.ptr = (void *) musicclass;
1416 f.datalen = strlen(musicclass) + 1;
1418 blob = ast_json_pack("{s: s}",
1419 "musicclass", musicclass);
1422 publish_channel_blob(chan, ast_channel_hold_type(), blob);
1424 res = ast_queue_frame(chan, &f);
1428 int ast_queue_unhold(struct ast_channel *chan)
1430 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_UNHOLD };
1433 publish_channel_blob(chan, ast_channel_unhold_type(), NULL);
1435 res = ast_queue_frame(chan, &f);
1439 /*! \brief Queue a control frame */
1440 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1442 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1443 return ast_queue_frame(chan, &f);
1446 /*! \brief Queue a control frame with payload */
1447 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1448 const void *data, size_t datalen)
1450 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1451 return ast_queue_frame(chan, &f);
1454 /*! \brief Set defer DTMF flag on channel */
1455 int ast_channel_defer_dtmf(struct ast_channel *chan)
1460 pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1461 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1466 /*! \brief Unset defer DTMF flag on channel */
1467 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1470 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1473 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1474 void *data, int ao2_flags)
1476 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1479 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1481 struct ast_channel *chan = obj;
1482 const char *name = arg;
1483 size_t name_len = *(size_t *) data;
1484 int ret = CMP_MATCH;
1486 if (ast_strlen_zero(name)) {
1487 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1491 ast_channel_lock(chan);
1492 if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1493 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1494 ret = 0; /* name match failed, keep looking */
1496 ast_channel_unlock(chan);
1501 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1503 struct ast_channel *chan = obj;
1504 char *context = arg;
1506 int ret = CMP_MATCH;
1508 if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1509 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1513 ast_channel_lock(chan);
1514 if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1515 ret = 0; /* Context match failed, continue */
1516 } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1517 ret = 0; /* Extension match failed, continue */
1519 ast_channel_unlock(chan);
1524 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1526 struct ast_channel *chan = obj;
1527 char *uniqueid = arg;
1528 size_t id_len = *(size_t *) data;
1529 int ret = CMP_MATCH;
1531 if (ast_strlen_zero(uniqueid)) {
1532 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1536 ast_channel_lock(chan);
1537 if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1538 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1539 ret = 0; /* uniqueid match failed, keep looking */
1541 ast_channel_unlock(chan);
1546 struct ast_channel_iterator {
1547 /* storage for non-dynamically allocated iterator */
1548 struct ao2_iterator simple_iterator;
1549 /* pointer to the actual iterator (simple_iterator or a dynamically
1550 * allocated iterator)
1552 struct ao2_iterator *active_iterator;
1555 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1557 ao2_iterator_destroy(i->active_iterator);
1563 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1565 struct ast_channel_iterator *i;
1566 char *l_exten = (char *) exten;
1567 char *l_context = (char *) context;
1569 if (!(i = ast_calloc(1, sizeof(*i)))) {
1573 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1574 l_context, l_exten, OBJ_MULTIPLE);
1575 if (!i->active_iterator) {
1583 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1585 struct ast_channel_iterator *i;
1586 char *l_name = (char *) name;
1588 if (!(i = ast_calloc(1, sizeof(*i)))) {
1592 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1594 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1595 if (!i->active_iterator) {
1603 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1605 struct ast_channel_iterator *i;
1607 if (!(i = ast_calloc(1, sizeof(*i)))) {
1611 i->simple_iterator = ao2_iterator_init(channels, 0);
1612 i->active_iterator = &i->simple_iterator;
1617 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1619 return ao2_iterator_next(i->active_iterator);
1622 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1623 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1625 ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1629 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1631 struct ast_channel *chan;
1632 char *l_name = (char *) name;
1634 chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1635 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1640 if (ast_strlen_zero(l_name)) {
1641 /* We didn't have a name to search for so quit. */
1645 /* Now try a search for uniqueid. */
1646 return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1649 struct ast_channel *ast_channel_get_by_name(const char *name)
1651 return ast_channel_get_by_name_prefix(name, 0);
1654 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1656 char *l_exten = (char *) exten;
1657 char *l_context = (char *) context;
1659 return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1662 int ast_is_deferrable_frame(const struct ast_frame *frame)
1664 /* Do not add a default entry in this switch statement. Each new
1665 * frame type should be addressed directly as to whether it should
1666 * be queued up or not.
1668 switch (frame->frametype) {
1669 case AST_FRAME_BRIDGE_ACTION:
1670 case AST_FRAME_CONTROL:
1671 case AST_FRAME_TEXT:
1672 case AST_FRAME_IMAGE:
1673 case AST_FRAME_HTML:
1676 case AST_FRAME_DTMF_END:
1677 case AST_FRAME_DTMF_BEGIN:
1678 case AST_FRAME_VOICE:
1679 case AST_FRAME_VIDEO:
1680 case AST_FRAME_NULL:
1683 case AST_FRAME_MODEM:
1689 /*! \brief Wait, look for hangups and condition arg */
1690 int ast_safe_sleep_conditional(struct ast_channel *chan, int timeout_ms, int (*cond)(void*), void *data)
1692 struct ast_frame *f;
1693 struct ast_silence_generator *silgen = NULL;
1695 struct timeval start;
1697 AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1699 AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1701 /* If no other generator is present, start silencegen while waiting */
1702 if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1703 silgen = ast_channel_start_silence_generator(chan);
1706 start = ast_tvnow();
1707 while ((ms = ast_remaining_ms(start, timeout_ms))) {
1708 struct ast_frame *dup_f = NULL;
1710 if (cond && ((*cond)(data) == 0)) {
1713 ms = ast_waitfor(chan, ms);
1725 if (!ast_is_deferrable_frame(f)) {
1730 if ((dup_f = ast_frisolate(f))) {
1734 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1739 /* stop silgen if present */
1741 ast_channel_stop_silence_generator(chan, silgen);
1744 /* We need to free all the deferred frames, but we only need to
1745 * queue the deferred frames if there was no error and no
1746 * hangup was received
1748 ast_channel_lock(chan);
1749 while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1751 ast_queue_frame_head(chan, f);
1755 ast_channel_unlock(chan);
1760 /*! \brief Wait, look for hangups */
1761 int ast_safe_sleep(struct ast_channel *chan, int ms)
1763 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1766 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1768 /* Safe, even if already unlinked. */
1769 ao2_unlink(channels, chan);
1770 return ast_channel_unref(chan);
1773 void ast_party_name_init(struct ast_party_name *init)
1776 init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1777 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1781 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1784 /* Don't copy to self */
1788 ast_free(dest->str);
1789 dest->str = ast_strdup(src->str);
1790 dest->char_set = src->char_set;
1791 dest->presentation = src->presentation;
1792 dest->valid = src->valid;
1795 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1798 init->char_set = guide->char_set;
1799 init->presentation = guide->presentation;
1800 init->valid = guide->valid;
1803 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1806 /* Don't set to self */
1810 if (src->str && src->str != dest->str) {
1811 ast_free(dest->str);
1812 dest->str = ast_strdup(src->str);
1815 dest->char_set = src->char_set;
1816 dest->presentation = src->presentation;
1817 dest->valid = src->valid;
1820 void ast_party_name_free(struct ast_party_name *doomed)
1822 ast_free(doomed->str);
1826 void ast_party_number_init(struct ast_party_number *init)
1829 init->plan = 0;/* Unknown */
1830 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1834 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1837 /* Don't copy to self */
1841 ast_free(dest->str);
1842 dest->str = ast_strdup(src->str);
1843 dest->plan = src->plan;
1844 dest->presentation = src->presentation;
1845 dest->valid = src->valid;
1848 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1851 init->plan = guide->plan;
1852 init->presentation = guide->presentation;
1853 init->valid = guide->valid;
1856 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1859 /* Don't set to self */
1863 if (src->str && src->str != dest->str) {
1864 ast_free(dest->str);
1865 dest->str = ast_strdup(src->str);
1868 dest->plan = src->plan;
1869 dest->presentation = src->presentation;
1870 dest->valid = src->valid;
1873 void ast_party_number_free(struct ast_party_number *doomed)
1875 ast_free(doomed->str);
1879 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1883 init->odd_even_indicator = 0;
1887 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1890 /* Don't copy to self */
1894 ast_free(dest->str);
1895 dest->str = ast_strdup(src->str);
1896 dest->type = src->type;
1897 dest->odd_even_indicator = src->odd_even_indicator;
1898 dest->valid = src->valid;
1901 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1904 init->type = guide->type;
1905 init->odd_even_indicator = guide->odd_even_indicator;
1906 init->valid = guide->valid;
1909 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1912 /* Don't set to self */
1916 if (src->str && src->str != dest->str) {
1917 ast_free(dest->str);
1918 dest->str = ast_strdup(src->str);
1921 dest->type = src->type;
1922 dest->odd_even_indicator = src->odd_even_indicator;
1923 dest->valid = src->valid;
1926 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1928 ast_free(doomed->str);
1932 void ast_set_party_id_all(struct ast_set_party_id *update_id)
1934 update_id->name = 1;
1935 update_id->number = 1;
1936 update_id->subaddress = 1;
1939 void ast_party_id_init(struct ast_party_id *init)
1941 ast_party_name_init(&init->name);
1942 ast_party_number_init(&init->number);
1943 ast_party_subaddress_init(&init->subaddress);
1947 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1950 /* Don't copy to self */
1954 ast_party_name_copy(&dest->name, &src->name);
1955 ast_party_number_copy(&dest->number, &src->number);
1956 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1958 ast_free(dest->tag);
1959 dest->tag = ast_strdup(src->tag);
1962 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1964 ast_party_name_set_init(&init->name, &guide->name);
1965 ast_party_number_set_init(&init->number, &guide->number);
1966 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1970 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1973 /* Don't set to self */
1977 if (!update || update->name) {
1978 ast_party_name_set(&dest->name, &src->name);
1980 if (!update || update->number) {
1981 ast_party_number_set(&dest->number, &src->number);
1983 if (!update || update->subaddress) {
1984 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1987 if (src->tag && src->tag != dest->tag) {
1988 ast_free(dest->tag);
1989 dest->tag = ast_strdup(src->tag);
1993 void ast_party_id_free(struct ast_party_id *doomed)
1995 ast_party_name_free(&doomed->name);
1996 ast_party_number_free(&doomed->number);
1997 ast_party_subaddress_free(&doomed->subaddress);
1999 ast_free(doomed->tag);
2003 int ast_party_id_presentation(const struct ast_party_id *id)
2005 int number_priority;
2007 int number_screening;
2011 /* Determine name presentation priority. */
2012 if (!id->name.valid) {
2013 name_value = AST_PRES_UNAVAILABLE;
2016 name_value = id->name.presentation & AST_PRES_RESTRICTION;
2017 switch (name_value) {
2018 case AST_PRES_RESTRICTED:
2021 case AST_PRES_ALLOWED:
2024 case AST_PRES_UNAVAILABLE:
2028 name_value = AST_PRES_UNAVAILABLE;
2034 /* Determine number presentation priority. */
2035 if (!id->number.valid) {
2036 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2037 number_value = AST_PRES_UNAVAILABLE;
2038 number_priority = 3;
2040 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
2041 number_value = id->number.presentation & AST_PRES_RESTRICTION;
2042 switch (number_value) {
2043 case AST_PRES_RESTRICTED:
2044 number_priority = 0;
2046 case AST_PRES_ALLOWED:
2047 number_priority = 1;
2049 case AST_PRES_UNAVAILABLE:
2050 number_priority = 2;
2053 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2054 number_value = AST_PRES_UNAVAILABLE;
2055 number_priority = 3;
2060 /* Select the wining presentation value. */
2061 if (name_priority < number_priority) {
2062 number_value = name_value;
2064 if (number_value == AST_PRES_UNAVAILABLE) {
2065 return AST_PRES_NUMBER_NOT_AVAILABLE;
2068 return number_value | number_screening;
2071 void ast_party_id_invalidate(struct ast_party_id *id)
2074 id->number.valid = 0;
2075 id->subaddress.valid = 0;
2078 void ast_party_id_reset(struct ast_party_id *id)
2080 ast_party_id_free(id);
2081 ast_party_id_init(id);
2084 struct ast_party_id ast_party_id_merge(struct ast_party_id *base, struct ast_party_id *overlay)
2086 struct ast_party_id merged;
2089 if (overlay->name.valid) {
2090 merged.name = overlay->name;
2092 if (overlay->number.valid) {
2093 merged.number = overlay->number;
2095 if (overlay->subaddress.valid) {
2096 merged.subaddress = overlay->subaddress;
2098 /* Note the actual structure is returned and not a pointer to it! */
2102 void ast_party_id_merge_copy(struct ast_party_id *dest, struct ast_party_id *base, struct ast_party_id *overlay)
2104 struct ast_party_id merged;
2106 merged = ast_party_id_merge(base, overlay);
2107 ast_party_id_copy(dest, &merged);
2110 void ast_party_dialed_init(struct ast_party_dialed *init)
2112 init->number.str = NULL;
2113 init->number.plan = 0;/* Unknown */
2114 ast_party_subaddress_init(&init->subaddress);
2115 init->transit_network_select = 0;
2118 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2121 /* Don't copy to self */
2125 ast_free(dest->number.str);
2126 dest->number.str = ast_strdup(src->number.str);
2127 dest->number.plan = src->number.plan;
2128 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2129 dest->transit_network_select = src->transit_network_select;
2132 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2134 init->number.str = NULL;
2135 init->number.plan = guide->number.plan;
2136 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2137 init->transit_network_select = guide->transit_network_select;
2140 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2142 if (src->number.str && src->number.str != dest->number.str) {
2143 ast_free(dest->number.str);
2144 dest->number.str = ast_strdup(src->number.str);
2146 dest->number.plan = src->number.plan;
2148 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2150 dest->transit_network_select = src->transit_network_select;
2153 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2155 ast_free(doomed->number.str);
2156 doomed->number.str = NULL;
2157 ast_party_subaddress_free(&doomed->subaddress);
2160 void ast_party_caller_init(struct ast_party_caller *init)
2162 ast_party_id_init(&init->id);
2163 ast_party_id_init(&init->ani);
2164 ast_party_id_init(&init->priv);
2168 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2171 /* Don't copy to self */
2175 ast_party_id_copy(&dest->id, &src->id);
2176 ast_party_id_copy(&dest->ani, &src->ani);
2177 ast_party_id_copy(&dest->priv, &src->priv);
2178 dest->ani2 = src->ani2;
2181 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2183 ast_party_id_set_init(&init->id, &guide->id);
2184 ast_party_id_set_init(&init->ani, &guide->ani);
2185 ast_party_id_set_init(&init->priv, &guide->priv);
2186 init->ani2 = guide->ani2;
2189 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2191 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2192 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2193 ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2194 dest->ani2 = src->ani2;
2197 void ast_party_caller_free(struct ast_party_caller *doomed)
2199 ast_party_id_free(&doomed->id);
2200 ast_party_id_free(&doomed->ani);
2201 ast_party_id_free(&doomed->priv);
2204 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2206 ast_party_id_init(&init->id);
2207 ast_party_id_init(&init->ani);
2208 ast_party_id_init(&init->priv);
2210 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2213 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2216 /* Don't copy to self */
2220 ast_party_id_copy(&dest->id, &src->id);
2221 ast_party_id_copy(&dest->ani, &src->ani);
2222 ast_party_id_copy(&dest->priv, &src->priv);
2223 dest->ani2 = src->ani2;
2224 dest->source = src->source;
2227 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2229 ast_party_id_set_init(&init->id, &guide->id);
2230 ast_party_id_set_init(&init->ani, &guide->ani);
2231 ast_party_id_set_init(&init->priv, &guide->priv);
2232 init->ani2 = guide->ani2;
2233 init->source = guide->source;
2236 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)
2238 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2239 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2240 ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2241 dest->ani2 = src->ani2;
2242 dest->source = src->source;
2245 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2247 connected->id = caller->id;
2248 connected->ani = caller->ani;
2249 connected->priv = caller->priv;
2250 connected->ani2 = caller->ani2;
2251 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2254 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2256 ast_party_id_free(&doomed->id);
2257 ast_party_id_free(&doomed->ani);
2258 ast_party_id_free(&doomed->priv);
2261 void ast_party_redirecting_reason_init(struct ast_party_redirecting_reason *init)
2264 init->code = AST_REDIRECTING_REASON_UNKNOWN;
2267 void ast_party_redirecting_reason_copy(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2273 ast_free(dest->str);
2274 dest->str = ast_strdup(src->str);
2275 dest->code = src->code;
2278 void ast_party_redirecting_reason_set_init(struct ast_party_redirecting_reason *init, const struct ast_party_redirecting_reason *guide)
2281 init->code = guide->code;
2284 void ast_party_redirecting_reason_set(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2290 if (src->str && src->str != dest->str) {
2291 ast_free(dest->str);
2292 dest->str = ast_strdup(src->str);
2295 dest->code = src->code;
2298 void ast_party_redirecting_reason_free(struct ast_party_redirecting_reason *doomed)
2300 ast_free(doomed->str);
2304 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2306 ast_party_id_init(&init->orig);
2307 ast_party_id_init(&init->from);
2308 ast_party_id_init(&init->to);
2309 ast_party_id_init(&init->priv_orig);
2310 ast_party_id_init(&init->priv_from);
2311 ast_party_id_init(&init->priv_to);
2312 ast_party_redirecting_reason_init(&init->reason);
2313 ast_party_redirecting_reason_init(&init->orig_reason);
2317 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2320 /* Don't copy to self */
2324 ast_party_id_copy(&dest->orig, &src->orig);
2325 ast_party_id_copy(&dest->from, &src->from);
2326 ast_party_id_copy(&dest->to, &src->to);
2327 ast_party_id_copy(&dest->priv_orig, &src->priv_orig);
2328 ast_party_id_copy(&dest->priv_from, &src->priv_from);
2329 ast_party_id_copy(&dest->priv_to, &src->priv_to);
2330 ast_party_redirecting_reason_copy(&dest->reason, &src->reason);
2331 ast_party_redirecting_reason_copy(&dest->orig_reason, &src->orig_reason);
2332 dest->count = src->count;
2335 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2337 ast_party_id_set_init(&init->orig, &guide->orig);
2338 ast_party_id_set_init(&init->from, &guide->from);
2339 ast_party_id_set_init(&init->to, &guide->to);
2340 ast_party_id_set_init(&init->priv_orig, &guide->priv_orig);
2341 ast_party_id_set_init(&init->priv_from, &guide->priv_from);
2342 ast_party_id_set_init(&init->priv_to, &guide->priv_to);
2343 ast_party_redirecting_reason_set_init(&init->reason, &guide->reason);
2344 ast_party_redirecting_reason_set_init(&init->orig_reason, &guide->orig_reason);
2345 init->count = guide->count;
2348 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2350 ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2351 ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2352 ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2353 ast_party_id_set(&dest->priv_orig, &src->priv_orig, update ? &update->priv_orig : NULL);
2354 ast_party_id_set(&dest->priv_from, &src->priv_from, update ? &update->priv_from : NULL);
2355 ast_party_id_set(&dest->priv_to, &src->priv_to, update ? &update->priv_to : NULL);
2356 ast_party_redirecting_reason_set(&dest->reason, &src->reason);
2357 ast_party_redirecting_reason_set(&dest->orig_reason, &src->orig_reason);
2358 dest->count = src->count;
2361 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2363 ast_party_id_free(&doomed->orig);
2364 ast_party_id_free(&doomed->from);
2365 ast_party_id_free(&doomed->to);
2366 ast_party_id_free(&doomed->priv_orig);
2367 ast_party_id_free(&doomed->priv_from);
2368 ast_party_id_free(&doomed->priv_to);
2369 ast_party_redirecting_reason_free(&doomed->reason);
2370 ast_party_redirecting_reason_free(&doomed->orig_reason);
2373 /*! \brief Free a channel structure */
2374 static void ast_channel_destructor(void *obj)
2376 struct ast_channel *chan = obj;
2380 struct ast_var_t *vardata;
2381 struct ast_frame *f;
2382 struct varshead *headp;
2383 struct ast_datastore *datastore;
2384 char device_name[AST_CHANNEL_NAME];
2385 struct ast_callid *callid;
2387 if (ast_channel_internal_is_finalized(chan)) {
2388 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2389 ast_cel_check_retire_linkedid(chan);
2392 ast_pbx_hangup_handler_destroy(chan);
2394 ast_channel_lock(chan);
2396 /* Get rid of each of the data stores on the channel */
2397 while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2398 /* Free the data store */
2399 ast_datastore_free(datastore);
2401 /* While the channel is locked, take the reference to its callid while we tear down the call. */
2402 callid = ast_channel_callid(chan);
2403 ast_channel_callid_cleanup(chan);
2405 ast_channel_unlock(chan);
2407 /* Lock and unlock the channel just to be sure nobody has it locked still
2408 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2409 ast_channel_lock(chan);
2410 ast_channel_unlock(chan);
2412 if (ast_channel_tech_pvt(chan)) {
2413 ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2414 ast_free(ast_channel_tech_pvt(chan));
2417 if (ast_channel_sched(chan)) {
2418 ast_sched_context_destroy(ast_channel_sched(chan));
2421 if (ast_channel_internal_is_finalized(chan)) {
2424 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2425 if ((dashptr = strrchr(device_name, '-'))) {
2429 device_name[0] = '\0';
2432 /* Stop monitoring */
2433 if (ast_channel_monitor(chan))
2434 ast_channel_monitor(chan)->stop( chan, 0 );
2436 /* If there is native format music-on-hold state, free it */
2437 if (ast_channel_music_state(chan))
2438 ast_moh_cleanup(chan);
2440 /* Free translators */
2441 if (ast_channel_readtrans(chan))
2442 ast_translator_free_path(ast_channel_readtrans(chan));
2443 if (ast_channel_writetrans(chan))
2444 ast_translator_free_path(ast_channel_writetrans(chan));
2445 if (ast_channel_pbx(chan))
2446 ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2448 ast_party_dialed_free(ast_channel_dialed(chan));
2449 ast_party_caller_free(ast_channel_caller(chan));
2450 ast_party_connected_line_free(ast_channel_connected(chan));
2451 ast_party_redirecting_free(ast_channel_redirecting(chan));
2453 /* Close pipes if appropriate */
2454 ast_channel_internal_alertpipe_close(chan);
2455 if (ast_channel_timer(chan)) {
2456 ast_timer_close(ast_channel_timer(chan));
2457 ast_channel_timer_set(chan, NULL);
2460 for (i = 0; i < AST_MAX_FDS; i++) {
2461 if (ast_channel_internal_epfd_data(chan, i)) {
2462 ast_free(ast_channel_internal_epfd_data(chan, i));
2465 close(ast_channel_epfd(chan));
2467 while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2470 /* loop over the variables list, freeing all data and deleting list items */
2471 /* no need to lock the list, as the channel is already locked */
2472 headp = ast_channel_varshead(chan);
2473 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2474 ast_var_delete(vardata);
2476 ast_app_group_discard(chan);
2478 /* Destroy the jitterbuffer */
2479 ast_jb_destroy(chan);
2481 if (ast_channel_cdr(chan)) {
2482 ast_cdr_discard(ast_channel_cdr(chan));
2483 ast_channel_cdr_set(chan, NULL);
2486 if (ast_channel_zone(chan)) {
2487 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2490 ast_channel_internal_cleanup(chan);
2492 if (device_name[0]) {
2494 * We have a device name to notify of a new state.
2496 * Queue an unknown state, because, while we know that this particular
2497 * instance is dead, we don't know the state of all other possible
2500 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_DEVSTATE_CACHE) ? AST_DEVSTATE_NOT_CACHABLE : AST_DEVSTATE_CACHABLE), device_name);
2503 ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2505 ast_callid_unref(callid);
2508 ast_channel_named_callgroups_set(chan, NULL);
2509 ast_channel_named_pickupgroups_set(chan, NULL);
2511 ast_atomic_fetchadd_int(&chancount, -1);
2514 /*! \brief Free a dummy channel structure */
2515 static void ast_dummy_channel_destructor(void *obj)
2517 struct ast_channel *chan = obj;
2518 struct ast_datastore *datastore;
2519 struct ast_var_t *vardata;
2520 struct varshead *headp;
2522 ast_pbx_hangup_handler_destroy(chan);
2524 /* Get rid of each of the data stores on the channel */
2525 while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
2526 /* Free the data store */
2527 ast_datastore_free(datastore);
2530 ast_party_dialed_free(ast_channel_dialed(chan));
2531 ast_party_caller_free(ast_channel_caller(chan));
2532 ast_party_connected_line_free(ast_channel_connected(chan));
2533 ast_party_redirecting_free(ast_channel_redirecting(chan));
2535 /* loop over the variables list, freeing all data and deleting list items */
2536 /* no need to lock the list, as the channel is already locked */
2537 headp = ast_channel_varshead(chan);
2538 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2539 ast_var_delete(vardata);
2541 if (ast_channel_cdr(chan)) {
2542 ast_cdr_discard(ast_channel_cdr(chan));
2543 ast_channel_cdr_set(chan, NULL);
2546 ast_channel_internal_cleanup(chan);
2549 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2551 return ast_datastore_alloc(info, uid);
2554 int ast_channel_datastore_free(struct ast_datastore *datastore)
2556 return ast_datastore_free(datastore);
2559 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2561 struct ast_datastore *datastore = NULL, *datastore2;
2563 AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2564 if (datastore->inheritance > 0) {
2565 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2567 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2568 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2569 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2576 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2580 AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2585 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2587 return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2590 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2592 struct ast_datastore *datastore = NULL;
2597 AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2598 if (datastore->info != info) {
2603 /* matched by type only */
2607 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2608 /* Matched by type AND uid */
2616 /*! Set the file descriptor on the channel */
2617 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2620 struct epoll_event ev;
2621 struct ast_epoll_data *aed = NULL;
2623 if (ast_channel_fd_isset(chan, which)) {
2624 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2625 aed = ast_channel_internal_epfd_data(chan, which);
2628 /* If this new fd is valid, add it to the epoll */
2630 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2633 ast_channel_internal_epfd_data_set(chan, which, aed);
2637 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2639 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2641 /* We don't have to keep around this epoll data structure now */
2643 ast_channel_epfd_data_set(chan, which, NULL);
2646 ast_channel_internal_fd_set(chan, which, fd);
2650 /*! Add a channel to an optimized waitfor */
2651 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2654 struct epoll_event ev;
2657 if (ast_channel_epfd(chan0) == -1)
2660 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2661 for (i = 0; i < AST_MAX_FDS; i++) {
2662 if (!ast_channel_fd_isset(chan1, i)) {
2665 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2666 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2667 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2674 /*! Delete a channel from an optimized waitfor */
2675 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2678 struct epoll_event ev;
2681 if (ast_channel_epfd(chan0) == -1)
2684 for (i = 0; i < AST_MAX_FDS; i++) {
2685 if (!ast_channel_fd_isset(chan1, i)) {
2688 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2695 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2697 ast_channel_lock(chan);
2699 ast_channel_softhangup_internal_flag_clear(chan, flag);
2701 if (!ast_channel_softhangup_internal_flag(chan)) {
2702 struct ast_frame *fr;
2704 /* If we have completely cleared the softhangup flag,
2705 * then we need to fully abort the hangup process. This requires
2706 * pulling the END_OF_Q frame out of the channel frame queue if it
2707 * still happens to be there. */
2709 fr = AST_LIST_LAST(ast_channel_readq(chan));
2710 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2711 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2712 AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2717 ast_channel_unlock(chan);
2720 /*! \brief Softly hangup a channel, don't lock */
2721 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2723 ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2724 /* Inform channel driver that we need to be hung up, if it cares */
2725 ast_channel_softhangup_internal_flag_add(chan, cause);
2726 ast_queue_frame(chan, &ast_null_frame);
2727 /* Interrupt any poll call or such */
2728 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2729 pthread_kill(ast_channel_blocker(chan), SIGURG);
2733 /*! \brief Softly hangup a channel, lock */
2734 int ast_softhangup(struct ast_channel *chan, int cause)
2736 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
2739 ast_channel_lock(chan);
2740 res = ast_softhangup_nolock(chan, cause);
2741 blob = ast_json_pack("{s: i, s: b}",
2744 publish_channel_blob(chan, ast_channel_hangup_request_type(), blob);
2745 ast_channel_unlock(chan);
2750 static void free_translation(struct ast_channel *clonechan)
2752 if (ast_channel_writetrans(clonechan))
2753 ast_translator_free_path(ast_channel_writetrans(clonechan));
2754 if (ast_channel_readtrans(clonechan))
2755 ast_translator_free_path(ast_channel_readtrans(clonechan));
2756 ast_channel_writetrans_set(clonechan, NULL);
2757 ast_channel_readtrans_set(clonechan, NULL);
2758 if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2759 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2760 ast_format_clear(ast_channel_rawreadformat(clonechan));
2762 struct ast_format tmpfmt;
2763 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2764 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2765 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2769 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2771 struct ast_channel *bridge;
2773 ast_channel_lock(chan);
2774 if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2775 ast_channel_hangupsource_set(chan, source);
2777 bridge = ast_bridged_channel(chan);
2779 ast_channel_ref(bridge);
2781 ast_channel_unlock(chan);
2784 ast_channel_lock(bridge);
2785 if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
2786 ast_channel_hangupsource_set(bridge, source);
2788 ast_channel_unlock(bridge);
2789 ast_channel_unref(bridge);
2793 static void destroy_hooks(struct ast_channel *chan)
2795 if (ast_channel_audiohooks(chan)) {
2796 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2797 ast_channel_audiohooks_set(chan, NULL);
2800 ast_framehook_list_destroy(chan);
2803 /*! \brief Hangup a channel */
2804 int ast_hangup(struct ast_channel *chan)
2806 char extra_str[64]; /* used for cel logging below */
2808 ast_autoservice_stop(chan);
2810 ast_channel_lock(chan);
2813 * Do the masquerade if someone is setup to masquerade into us.
2815 * NOTE: We must hold the channel lock after testing for a
2816 * pending masquerade and setting the channel as a zombie to
2817 * prevent __ast_channel_masquerade() from setting up a
2818 * masquerade with a dead channel.
2820 while (ast_channel_masq(chan)) {
2821 ast_channel_unlock(chan);
2822 ast_do_masquerade(chan);
2823 ast_channel_lock(chan);
2826 if (ast_channel_masqr(chan)) {
2828 * This channel is one which will be masqueraded into something.
2829 * Mark it as a zombie already so ast_do_masquerade() will know
2832 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2833 destroy_hooks(chan);
2834 ast_channel_unlock(chan);
2838 /* Mark as a zombie so a masquerade cannot be setup on this channel. */
2839 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2841 ast_channel_unlock(chan);
2844 * XXX if running the hangup handlers here causes problems
2845 * because the handlers take too long to execute, we could move
2846 * the meat of this function into another thread. A thread
2847 * where channels go to die.
2849 * If this is done, ast_autoservice_chan_hangup_peer() will no
2852 ast_pbx_hangup_handler_run(chan);
2853 ao2_unlink(channels, chan);
2854 ast_channel_lock(chan);
2856 destroy_hooks(chan);
2858 free_translation(chan);
2859 /* Close audio stream */
2860 if (ast_channel_stream(chan)) {
2861 ast_closestream(ast_channel_stream(chan));
2862 ast_channel_stream_set(chan, NULL);
2864 /* Close video stream */
2865 if (ast_channel_vstream(chan)) {
2866 ast_closestream(ast_channel_vstream(chan));
2867 ast_channel_vstream_set(chan, NULL);
2869 if (ast_channel_sched(chan)) {
2870 ast_sched_context_destroy(ast_channel_sched(chan));
2871 ast_channel_sched_set(chan, NULL);
2874 if (ast_channel_generatordata(chan)) { /* Clear any tone stuff remaining */
2875 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2876 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2879 ast_channel_generatordata_set(chan, NULL);
2880 ast_channel_generator_set(chan, NULL);
2882 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"), ""));
2883 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2885 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2886 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2887 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2888 (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2889 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2892 ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2893 if (ast_channel_tech(chan)->hangup) {
2894 ast_channel_tech(chan)->hangup(chan);
2897 ast_channel_unlock(chan);
2901 ast_publish_channel_state(chan);
2902 publish_cache_clear(chan);
2904 if (ast_channel_cdr(chan) && !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_BRIDGED) &&
2905 !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_POST_DISABLED) &&
2906 (ast_channel_cdr(chan)->disposition != AST_CDR_NULL || ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_DIALED))) {
2907 ast_channel_lock(chan);
2908 ast_cdr_end(ast_channel_cdr(chan));
2909 ast_cdr_detach(ast_channel_cdr(chan));
2910 ast_channel_cdr_set(chan, NULL);
2911 ast_channel_unlock(chan);
2914 ast_channel_unref(chan);
2919 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2923 ast_channel_lock(chan);
2925 /* You can't answer an outbound call */
2926 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2927 ast_channel_unlock(chan);
2931 /* Stop if we're a zombie or need a soft hangup */
2932 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2933 ast_channel_unlock(chan);
2937 ast_channel_unlock(chan);
2939 switch (ast_channel_state(chan)) {
2940 case AST_STATE_RINGING:
2941 case AST_STATE_RING:
2942 ast_channel_lock(chan);
2943 if (ast_channel_tech(chan)->answer) {
2944 res = ast_channel_tech(chan)->answer(chan);
2946 ast_setstate(chan, AST_STATE_UP);
2948 ast_cdr_answer(ast_channel_cdr(chan));
2950 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2951 ast_channel_unlock(chan);
2954 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2955 /* Calling ast_cdr_answer when it it has previously been called
2956 * is essentially a no-op, so it is safe.
2959 ast_cdr_answer(ast_channel_cdr(chan));
2966 ast_indicate(chan, -1);
2971 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2974 enum ast_channel_state old_state;
2976 old_state = ast_channel_state(chan);
2977 if ((res = ast_raw_answer(chan, cdr_answer))) {
2981 switch (old_state) {
2982 case AST_STATE_RINGING:
2983 case AST_STATE_RING:
2984 /* wait for media to start flowing, but don't wait any longer
2985 * than 'delay' or 500 milliseconds, whichever is longer
2988 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2989 struct ast_frame *cur;
2990 struct ast_frame *new_frame;
2991 int timeout_ms = MAX(delay, 500);
2992 unsigned int done = 0;
2993 struct timeval start;
2995 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2997 start = ast_tvnow();
2999 int ms = ast_remaining_ms(start, timeout_ms);
3000 ms = ast_waitfor(chan, ms);
3002 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
3007 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));
3010 cur = ast_read(chan);
3011 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
3012 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
3017 ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
3021 if ((new_frame = ast_frisolate(cur)) != cur) {
3025 AST_LIST_INSERT_HEAD(&frames, new_frame, frame_list);
3027 /* if a specific delay period was requested, continue
3028 * until that delay has passed. don't stop just because
3029 * incoming media has arrived.
3035 switch (new_frame->frametype) {
3036 /* all of these frametypes qualify as 'media' */
3037 case AST_FRAME_VOICE:
3038 case AST_FRAME_VIDEO:
3039 case AST_FRAME_TEXT:
3040 case AST_FRAME_DTMF_BEGIN:
3041 case AST_FRAME_DTMF_END:
3042 case AST_FRAME_IMAGE:
3043 case AST_FRAME_HTML:
3044 case AST_FRAME_MODEM:
3047 case AST_FRAME_CONTROL:
3049 case AST_FRAME_BRIDGE_ACTION:
3050 case AST_FRAME_NULL:
3061 ast_channel_lock(chan);
3062 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
3063 ast_queue_frame_head(chan, cur);
3066 ast_channel_unlock(chan);
3077 int ast_answer(struct ast_channel *chan)
3079 return __ast_answer(chan, 0, 1);
3082 void ast_deactivate_generator(struct ast_channel *chan)
3084 ast_channel_lock(chan);
3085 if (ast_channel_generatordata(chan)) {
3086 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3087 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3089 ast_channel_generatordata_set(chan, NULL);
3090 ast_channel_generator_set(chan, NULL);
3091 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
3092 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
3093 ast_settimeout(chan, 0, NULL, NULL);
3095 ast_channel_unlock(chan);
3098 static void generator_write_format_change(struct ast_channel *chan)
3100 ast_channel_lock(chan);
3101 if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
3102 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
3104 ast_channel_unlock(chan);
3107 static int generator_force(const void *data)
3109 /* Called if generator doesn't have data */
3112 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
3113 struct ast_channel *chan = (struct ast_channel *)data;
3115 ast_channel_lock(chan);
3116 tmp = ast_channel_generatordata(chan);
3117 ast_channel_generatordata_set(chan, NULL);
3118 if (ast_channel_generator(chan))
3119 generate = ast_channel_generator(chan)->generate;
3120 ast_channel_unlock(chan);
3122 if (!tmp || !generate)
3125 res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
3127 ast_channel_lock(chan);
3128 if (ast_channel_generator(chan) && generate == ast_channel_generator(chan)->generate) {
3129 ast_channel_generatordata_set(chan, tmp);
3131 ast_channel_unlock(chan);
3134 ast_debug(1, "Auto-deactivating generator\n");
3135 ast_deactivate_generator(chan);
3141 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
3144 void *generatordata = NULL;
3146 ast_channel_lock(chan);
3147 if (ast_channel_generatordata(chan)) {
3148 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3149 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3152 if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
3155 ast_channel_generatordata_set(chan, generatordata);
3157 ast_settimeout(chan, 50, generator_force, chan);
3158 ast_channel_generator_set(chan, gen);
3160 ast_channel_unlock(chan);
3167 /*! \brief Wait for x amount of time on a file descriptor to have input. */
3168 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
3171 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
3175 /*! \brief Wait for x amount of time on a file descriptor to have input. */
3177 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
3178 int *exception, int *outfd, int *ms)
3180 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3181 int *exception, int *outfd, int *ms)
3184 struct timeval start = { 0 , 0 };
3185 struct pollfd *pfds = NULL;
3190 struct timeval now = { 0, 0 };
3191 struct timeval whentohangup = { 0, 0 }, diff;
3192 struct ast_channel *winner = NULL;
3205 if ((sz = n * AST_MAX_FDS + nfds)) {
3206 pfds = ast_alloca(sizeof(*pfds) * sz);
3207 fdmap = ast_alloca(sizeof(*fdmap) * sz);
3209 /* nothing to allocate and no FDs to check */
3213 /* Perform any pending masquerades */
3214 for (x = 0; x < n; x++) {
3215 while (ast_channel_masq(c[x])) {
3216 ast_do_masquerade(c[x]);
3219 ast_channel_lock(c[x]);
3220 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
3221 if (ast_tvzero(whentohangup))
3223 diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
3224 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3225 ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3226 /* Should already be hungup */
3227 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3228 ast_channel_unlock(c[x]);
3231 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3232 whentohangup = diff;
3234 ast_channel_unlock(c[x]);
3236 /* Wait full interval */
3238 /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3239 if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3240 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
3241 if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
3244 } else if (!ast_tvzero(whentohangup) && rms < 0) {
3245 /* Tiny corner case... call would need to last >24 days */
3249 * Build the pollfd array, putting the channels' fds first,
3250 * followed by individual fds. Order is important because
3251 * individual fd's must have priority over channel fds.
3254 for (x = 0; x < n; x++) {
3255 for (y = 0; y < AST_MAX_FDS; y++) {
3256 fdmap[max].fdno = y; /* fd y is linked to this pfds */
3257 fdmap[max].chan = x; /* channel x is linked to this pfds */
3258 max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3260 CHECK_BLOCKING(c[x]);
3262 /* Add the individual fds */
3263 for (x = 0; x < nfds; x++) {
3264 fdmap[max].chan = -1;
3265 max += ast_add_fd(&pfds[max], fds[x]);
3269 start = ast_tvnow();
3272 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3275 if (kbrms > 600000) {
3278 res = ast_poll(pfds, max, kbrms);
3282 } while (!res && (rms > 0));
3284 res = ast_poll(pfds, max, rms);
3286 for (x = 0; x < n; x++) {
3287 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3289 if (res < 0) { /* Simulate a timeout if we were interrupted */
3290 if (errno != EINTR) {
3295 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
3297 for (x = 0; x < n; x++) {
3298 if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3299 ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3300 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3301 if (winner == NULL) {
3307 if (res == 0) { /* no fd ready, reset timeout and done */
3308 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
3312 * Then check if any channel or fd has a pending event.
3313 * Remember to check channels first and fds last, as they
3314 * must have priority on setting 'winner'
3316 for (x = 0; x < max; x++) {
3317 res = pfds[x].revents;
3321 if (fdmap[x].chan >= 0) { /* this is a channel */
3322 winner = c[fdmap[x].chan]; /* override previous winners */
3323 if (res & POLLPRI) {
3324 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3326 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3328 ast_channel_fdno_set(winner, fdmap[x].fdno);
3329 } else { /* this is an fd */
3331 *outfd = pfds[x].fd;
3334 *exception = (res & POLLPRI) ? -1 : 0;
3340 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3349 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3351 struct timeval start = { 0 , 0 };
3353 struct epoll_event ev[1];
3354 long diff, rms = *ms;
3355 struct ast_channel *winner = NULL;
3356 struct ast_epoll_data *aed = NULL;
3359 /* See if this channel needs to be masqueraded */
3360 while (ast_channel_masq(chan)) {
3361 ast_do_masquerade(chan);
3364 ast_channel_lock(chan);
3365 /* Figure out their timeout */
3366 if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3367 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow())) < 0) {
3368 /* They should already be hungup! */
3369 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3370 ast_channel_unlock(chan);
3373 /* If this value is smaller then the current one... make it priority */
3379 ast_channel_unlock(chan);
3381 /* Time to make this channel block... */
3382 CHECK_BLOCKING(chan);
3385 start = ast_tvnow();
3388 /* We don't have to add any file descriptors... they are already added, we just have to wait! */