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/test.h"
82 #include <sys/epoll.h>
85 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
88 #endif /* defined(HAVE_PRI) */
89 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
91 struct ast_epoll_data {
92 struct ast_channel *chan;
96 /* uncomment if you have problems with 'monitoring' synchronized files */
98 #define MONITOR_CONSTANT_DELAY
99 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
102 /*! \brief Prevent new channel allocation if shutting down. */
103 static int shutting_down;
105 static int uniqueint;
106 static int chancount;
108 unsigned long global_fin, global_fout;
110 AST_THREADSTORAGE(state2str_threadbuf);
111 #define STATE2STR_BUFSIZE 32
113 /*! Default amount of time to use when emulating a digit as a begin and end
115 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
117 /*! Minimum amount of time between the end of the last digit and the beginning
118 * of a new one - 45ms */
119 #define AST_MIN_DTMF_GAP 45
121 /*! \brief List of channel drivers */
123 const struct ast_channel_tech *tech;
124 AST_LIST_ENTRY(chanlist) list;
128 /*! \brief Structure to hold channel context backtrace data */
129 struct ast_chan_trace_data {
131 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
134 /*! \brief Structure to save contexts where an ast_chan has been into */
135 struct ast_chan_trace {
136 char context[AST_MAX_CONTEXT];
137 char exten[AST_MAX_EXTENSION];
139 AST_LIST_ENTRY(ast_chan_trace) entry;
143 /*! \brief the list of registered channel types */
144 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
147 #define NUM_CHANNEL_BUCKETS 61
149 #define NUM_CHANNEL_BUCKETS 1567
152 /*! \brief All active channels on the system */
153 static struct ao2_container *channels;
155 /*! \brief map AST_CAUSE's to readable string representations
165 static const struct causes_map causes[] = {
166 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
167 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
168 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
169 { AST_CAUSE_MISDIALLED_TRUNK_PREFIX, "MISDIALLED_TRUNK_PREFIX", "Misdialed trunk prefix" },
170 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
171 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
172 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
173 { AST_CAUSE_NUMBER_PORTED_NOT_HERE, "NUMBER_PORTED_NOT_HERE", "Number ported elsewhere" },
174 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
175 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
176 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
177 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
178 { AST_CAUSE_SUBSCRIBER_ABSENT, "SUBSCRIBER_ABSENT", "Subscriber absent" },
179 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
180 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
181 { AST_CAUSE_REDIRECTED_TO_NEW_DESTINATION, "REDIRECTED_TO_NEW_DESTINATION", "Redirected to new destination" },
182 { AST_CAUSE_ANSWERED_ELSEWHERE, "ANSWERED_ELSEWHERE", "Answered elsewhere" },
183 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
184 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
185 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
186 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
187 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
188 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
189 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
190 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
191 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
192 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
193 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
194 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
195 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
196 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
197 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
198 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
199 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
200 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
201 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
202 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
203 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
204 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
205 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
206 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
207 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
208 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
209 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
210 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
211 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
212 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
213 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
214 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
217 struct ast_variable *ast_channeltype_list(void)
220 struct ast_variable *var = NULL, *prev = NULL;
222 AST_RWLIST_RDLOCK(&backends);
223 AST_RWLIST_TRAVERSE(&backends, cl, list) {
225 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
228 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
232 AST_RWLIST_UNLOCK(&backends);
237 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
238 static const char *party_number_ton2str(int ton)
240 #if defined(HAVE_PRI)
241 switch ((ton >> 4) & 0x07) {
242 case PRI_TON_INTERNATIONAL:
243 return "International";
244 case PRI_TON_NATIONAL:
246 case PRI_TON_NET_SPECIFIC:
247 return "Network Specific";
248 case PRI_TON_SUBSCRIBER:
250 case PRI_TON_ABBREVIATED:
251 return "Abbreviated";
252 case PRI_TON_RESERVED:
254 case PRI_TON_UNKNOWN:
258 #endif /* defined(HAVE_PRI) */
261 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
263 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
264 static const char *party_number_plan2str(int plan)
266 #if defined(HAVE_PRI)
267 switch (plan & 0x0F) {
269 case PRI_NPI_UNKNOWN:
271 case PRI_NPI_E163_E164:
272 return "Public (E.163/E.164)";
274 return "Data (X.121)";
276 return "Telex (F.69)";
277 case PRI_NPI_NATIONAL:
278 return "National Standard";
279 case PRI_NPI_PRIVATE:
281 case PRI_NPI_RESERVED:
284 #endif /* defined(HAVE_PRI) */
287 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
289 /*! \brief Show channel types - CLI command */
290 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
292 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
298 e->command = "core show channeltypes";
300 "Usage: core show channeltypes\n"
301 " Lists available channel types registered in your\n"
302 " Asterisk server.\n";
309 return CLI_SHOWUSAGE;
311 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
312 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
314 AST_RWLIST_RDLOCK(&backends);
315 AST_RWLIST_TRAVERSE(&backends, cl, list) {
316 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
317 (cl->tech->devicestate) ? "yes" : "no",
318 (cl->tech->indicate) ? "yes" : "no",
319 (cl->tech->transfer) ? "yes" : "no");
322 AST_RWLIST_UNLOCK(&backends);
324 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
331 static char *complete_channeltypes(struct ast_cli_args *a)
341 wordlen = strlen(a->word);
343 AST_RWLIST_RDLOCK(&backends);
344 AST_RWLIST_TRAVERSE(&backends, cl, list) {
345 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
346 ret = ast_strdup(cl->tech->type);
350 AST_RWLIST_UNLOCK(&backends);
355 /*! \brief Show details about a channel driver - CLI command */
356 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
358 struct chanlist *cl = NULL;
363 e->command = "core show channeltype";
365 "Usage: core show channeltype <name>\n"
366 " Show details about the specified channel type, <name>.\n";
369 return complete_channeltypes(a);
373 return CLI_SHOWUSAGE;
375 AST_RWLIST_RDLOCK(&backends);
377 AST_RWLIST_TRAVERSE(&backends, cl, list) {
378 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
384 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
385 AST_RWLIST_UNLOCK(&backends);
390 "-- Info about channel driver: %s --\n"
391 " Device State: %s\n"
394 " Capabilities: %s\n"
398 " Image Support: %s\n"
399 " Text Support: %s\n",
401 (cl->tech->devicestate) ? "yes" : "no",
402 (cl->tech->indicate) ? "yes" : "no",
403 (cl->tech->transfer) ? "yes" : "no",
404 ast_getformatname_multiple(buf, sizeof(buf), cl->tech->capabilities),
405 (cl->tech->send_digit_begin) ? "yes" : "no",
406 (cl->tech->send_digit_end) ? "yes" : "no",
407 (cl->tech->send_html) ? "yes" : "no",
408 (cl->tech->send_image) ? "yes" : "no",
409 (cl->tech->send_text) ? "yes" : "no"
413 AST_RWLIST_UNLOCK(&backends);
418 static struct ast_cli_entry cli_channel[] = {
419 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
420 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
423 static struct ast_frame *kill_read(struct ast_channel *chan)
425 /* Hangup channel. */
429 static struct ast_frame *kill_exception(struct ast_channel *chan)
431 /* Hangup channel. */
435 static int kill_write(struct ast_channel *chan, struct ast_frame *frame)
437 /* Hangup channel. */
441 static int kill_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
443 /* No problem fixing up the channel. */
447 static int kill_hangup(struct ast_channel *chan)
449 ast_channel_tech_pvt_set(chan, NULL);
454 * \brief Kill the channel channel driver technology descriptor.
457 * The purpose of this channel technology is to encourage the
458 * channel to hangup as quickly as possible.
460 * \note Used by DTMF atxfer and zombie channels.
462 const struct ast_channel_tech ast_kill_tech = {
464 .description = "Kill channel (should not see this)",
466 .exception = kill_exception,
469 .hangup = kill_hangup,
473 /*! \brief Destructor for the channel trace datastore */
474 static void ast_chan_trace_destroy_cb(void *data)
476 struct ast_chan_trace *trace;
477 struct ast_chan_trace_data *traced = data;
478 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
484 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
485 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
487 .destroy = ast_chan_trace_destroy_cb
490 /*! \brief Put the channel backtrace in a string */
491 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
494 struct ast_chan_trace *trace;
495 struct ast_chan_trace_data *traced;
496 struct ast_datastore *store;
498 ast_channel_lock(chan);
499 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
501 ast_channel_unlock(chan);
504 traced = store->data;
506 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
507 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
508 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
514 ast_channel_unlock(chan);
518 /* !\brief Whether or not context tracing is enabled */
519 int ast_channel_trace_is_enabled(struct ast_channel *chan)
521 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
524 return ((struct ast_chan_trace_data *)store->data)->enabled;
527 /*! \brief Update the context backtrace data if tracing is enabled */
528 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
530 struct ast_chan_trace *trace;
531 if (!traced->enabled)
533 /* If the last saved context does not match the current one
534 OR we have not saved any context so far, then save the current context */
535 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan))) ||
536 (AST_LIST_EMPTY(&traced->trace))) {
537 /* Just do some debug logging */
538 if (AST_LIST_EMPTY(&traced->trace))
539 ast_debug(1, "Setting initial trace context to %s\n", ast_channel_context(chan));
541 ast_debug(1, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan));
542 /* alloc or bail out */
543 trace = ast_malloc(sizeof(*trace));
546 /* save the current location and store it in the trace list */
547 ast_copy_string(trace->context, ast_channel_context(chan), sizeof(trace->context));
548 ast_copy_string(trace->exten, ast_channel_exten(chan), sizeof(trace->exten));
549 trace->priority = ast_channel_priority(chan);
550 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
555 /*! \brief Update the context backtrace if tracing is enabled */
556 int ast_channel_trace_update(struct ast_channel *chan)
558 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
561 return ast_channel_trace_data_update(chan, store->data);
564 /*! \brief Enable context tracing in the channel */
565 int ast_channel_trace_enable(struct ast_channel *chan)
567 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
568 struct ast_chan_trace_data *traced;
570 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
573 traced = ast_calloc(1, sizeof(*traced));
575 ast_datastore_free(store);
578 store->data = traced;
579 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
580 ast_channel_datastore_add(chan, store);
582 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
583 ast_channel_trace_data_update(chan, store->data);
587 /*! \brief Disable context tracing in the channel */
588 int ast_channel_trace_disable(struct ast_channel *chan)
590 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
593 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
596 #endif /* CHANNEL_TRACE */
598 /*! \brief Checks to see if a channel is needing hang up */
599 int ast_check_hangup(struct ast_channel *chan)
601 if (ast_channel_softhangup_internal_flag(chan)) /* yes if soft hangup flag set */
603 if (ast_tvzero(*ast_channel_whentohangup(chan))) /* no if no hangup scheduled */
605 if (ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()) > 0) /* no if hangup time has not come yet. */
607 ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()));
608 ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(chan));
609 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT); /* record event */
613 int ast_check_hangup_locked(struct ast_channel *chan)
616 ast_channel_lock(chan);
617 res = ast_check_hangup(chan);
618 ast_channel_unlock(chan);
622 void ast_channel_softhangup_withcause_locked(struct ast_channel *chan, int causecode)
624 ast_channel_lock(chan);
627 ast_debug(1, "Setting hangupcause of channel %s to %d (is %d now)\n",
628 ast_channel_name(chan), causecode, ast_channel_hangupcause(chan));
630 ast_channel_hangupcause_set(chan, causecode);
633 ast_softhangup_nolock(chan, AST_SOFTHANGUP_EXPLICIT);
635 ast_channel_unlock(chan);
638 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
640 struct ast_channel *chan = obj;
642 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
647 void ast_begin_shutdown(int hangup)
652 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
656 /*! \brief returns number of active/allocated channels */
657 int ast_active_channels(void)
659 return channels ? ao2_container_count(channels) : 0;
662 int ast_undestroyed_channels(void)
664 return ast_atomic_fetchadd_int(&chancount, 0);
667 /*! \brief Cancel a shutdown in progress */
668 void ast_cancel_shutdown(void)
673 /*! \brief Returns non-zero if Asterisk is being shut down */
674 int ast_shutting_down(void)
676 return shutting_down;
679 /*! \brief Set when to hangup channel */
680 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
682 if (ast_tvzero(offset)) {
683 ast_channel_whentohangup_set(chan, &offset);
685 struct timeval tv = ast_tvadd(offset, ast_tvnow());
686 ast_channel_whentohangup_set(chan, &tv);
688 ast_queue_frame(chan, &ast_null_frame);
692 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
694 struct timeval when = { offset, };
695 ast_channel_setwhentohangup_tv(chan, when);
698 /*! \brief Compare a offset with when to hangup channel */
699 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
701 struct timeval whentohangup;
703 if (ast_tvzero(*ast_channel_whentohangup(chan)))
704 return ast_tvzero(offset) ? 0 : -1;
706 if (ast_tvzero(offset))
709 whentohangup = ast_tvadd(offset, ast_tvnow());
711 return ast_tvdiff_ms(whentohangup, *ast_channel_whentohangup(chan));
714 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
716 struct timeval when = { offset, };
717 return ast_channel_cmpwhentohangup_tv(chan, when);
720 /*! \brief Register a new telephony channel in Asterisk */
721 int ast_channel_register(const struct ast_channel_tech *tech)
723 struct chanlist *chan;
725 AST_RWLIST_WRLOCK(&backends);
727 AST_RWLIST_TRAVERSE(&backends, chan, list) {
728 if (!strcasecmp(tech->type, chan->tech->type)) {
729 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
730 AST_RWLIST_UNLOCK(&backends);
735 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
736 AST_RWLIST_UNLOCK(&backends);
740 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
742 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
744 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
746 AST_RWLIST_UNLOCK(&backends);
751 /*! \brief Unregister channel driver */
752 void ast_channel_unregister(const struct ast_channel_tech *tech)
754 struct chanlist *chan;
756 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
758 AST_RWLIST_WRLOCK(&backends);
760 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
761 if (chan->tech == tech) {
762 AST_LIST_REMOVE_CURRENT(list);
764 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
768 AST_LIST_TRAVERSE_SAFE_END;
770 AST_RWLIST_UNLOCK(&backends);
773 /*! \brief Get handle to channel driver based on name */
774 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
776 struct chanlist *chanls;
777 const struct ast_channel_tech *ret = NULL;
779 AST_RWLIST_RDLOCK(&backends);
781 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
782 if (!strcasecmp(name, chanls->tech->type)) {
788 AST_RWLIST_UNLOCK(&backends);
793 /*! \brief Gives the string form of a given hangup cause */
794 const char *ast_cause2str(int cause)
798 for (x = 0; x < ARRAY_LEN(causes); x++) {
799 if (causes[x].cause == cause)
800 return causes[x].desc;
806 /*! \brief Convert a symbolic hangup cause to number */
807 int ast_str2cause(const char *name)
811 for (x = 0; x < ARRAY_LEN(causes); x++)
812 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
813 return causes[x].cause;
818 /*! \brief Gives the string form of a given channel state.
820 * \note This function is not reentrant.
824 const char *ast_state2str(enum ast_channel_state state)
831 case AST_STATE_RESERVED:
833 case AST_STATE_OFFHOOK:
835 case AST_STATE_DIALING:
839 case AST_STATE_RINGING:
845 case AST_STATE_DIALING_OFFHOOK:
846 return "Dialing Offhook";
847 case AST_STATE_PRERING:
850 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
852 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
857 /*! \brief Gives the string form of a given transfer capability */
858 char *ast_transfercapability2str(int transfercapability)
860 switch (transfercapability) {
861 case AST_TRANS_CAP_SPEECH:
863 case AST_TRANS_CAP_DIGITAL:
865 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
866 return "RESTRICTED_DIGITAL";
867 case AST_TRANS_CAP_3_1K_AUDIO:
869 case AST_TRANS_CAP_DIGITAL_W_TONES:
870 return "DIGITAL_W_TONES";
871 case AST_TRANS_CAP_VIDEO:
878 /*! \brief Pick the best audio codec */
879 struct ast_format *ast_best_codec(struct ast_format_cap *cap, struct ast_format *result)
881 /* This just our opinion, expressed in code. We are asked to choose
882 the best codec to use, given no information */
883 static const enum ast_format_id prefs[] =
885 /*! Okay, ulaw is used by all telephony equipment, so start with it */
887 /*! Unless of course, you're a silly European, so then prefer ALAW */
893 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
895 /*! Okay, well, signed linear is easy to translate into other stuff */
896 AST_FORMAT_SLINEAR192,
897 AST_FORMAT_SLINEAR96,
898 AST_FORMAT_SLINEAR48,
899 AST_FORMAT_SLINEAR44,
900 AST_FORMAT_SLINEAR32,
901 AST_FORMAT_SLINEAR24,
902 AST_FORMAT_SLINEAR16,
903 AST_FORMAT_SLINEAR12,
905 /*! G.726 is standard ADPCM, in RFC3551 packing order */
907 /*! G.726 is standard ADPCM, in AAL2 packing order */
908 AST_FORMAT_G726_AAL2,
909 /*! ADPCM has great sound quality and is still pretty easy to translate */
911 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
912 translate and sounds pretty good */
914 /*! iLBC is not too bad */
916 /*! Speex is free, but computationally more expensive than GSM */
920 /*! SILK is pretty awesome. */
922 /*! CELT supports crazy high sample rates */
924 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
927 /*! G.729a is faster than 723 and slightly less expensive */
929 /*! Down to G.723.1 which is proprietary but at least designed for voice */
935 /* Find the first preferred codec in the format given */
936 for (x = 0; x < ARRAY_LEN(prefs); x++) {
937 if (ast_format_cap_best_byid(cap, prefs[x], result)) {
942 ast_format_clear(result);
943 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
948 static const struct ast_channel_tech null_tech = {
950 .description = "Null channel (should not see this)",
953 static void ast_channel_destructor(void *obj);
954 static void ast_dummy_channel_destructor(void *obj);
956 /*! \brief Create a new channel structure */
957 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
958 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
959 const char *acctcode, const char *exten, const char *context,
960 const char *linkedid, const int amaflag, const char *file, int line,
961 const char *function, const char *name_fmt, va_list ap)
963 struct ast_channel *tmp;
964 struct varshead *headp;
965 char *tech = "", *tech2 = NULL;
966 struct ast_format_cap *nativeformats;
967 struct ast_sched_context *schedctx;
968 struct ast_timer *timer;
971 /* If shutting down, don't allocate any new channels */
972 if (ast_shutting_down()) {
973 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
977 if (!(tmp = ast_channel_internal_alloc(ast_channel_destructor))) {
978 /* Channel structure allocation failure. */
981 if (!(nativeformats = ast_format_cap_alloc())) {
983 /* format capabilities structure allocation failure */
986 ast_channel_nativeformats_set(tmp, nativeformats);
989 * Init file descriptors to unopened state so
990 * the destructor can know not to close them.
992 ast_channel_timingfd_set(tmp, -1);
993 ast_channel_internal_alertpipe_clear(tmp);
994 ast_channel_internal_fd_clear_all(tmp);
997 ast_channel_epfd_set(tmp, epoll_create(25));
1000 if (!(schedctx = ast_sched_context_create())) {
1001 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
1002 return ast_channel_unref(tmp);
1004 ast_channel_sched_set(tmp, schedctx);
1006 ast_party_dialed_init(ast_channel_dialed(tmp));
1007 ast_party_caller_init(ast_channel_caller(tmp));
1008 ast_party_connected_line_init(ast_channel_connected(tmp));
1009 ast_party_redirecting_init(ast_channel_redirecting(tmp));
1012 ast_channel_caller(tmp)->id.name.valid = 1;
1013 ast_channel_caller(tmp)->id.name.str = ast_strdup(cid_name);
1014 if (!ast_channel_caller(tmp)->id.name.str) {
1015 return ast_channel_unref(tmp);
1019 ast_channel_caller(tmp)->id.number.valid = 1;
1020 ast_channel_caller(tmp)->id.number.str = ast_strdup(cid_num);
1021 if (!ast_channel_caller(tmp)->id.number.str) {
1022 return ast_channel_unref(tmp);
1026 if ((timer = ast_timer_open())) {
1027 ast_channel_timer_set(tmp, timer);
1028 if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
1031 ast_channel_timingfd_set(tmp, ast_timer_fd(ast_channel_timer(tmp)));
1035 * This is the last place the channel constructor can fail.
1037 * The destructor takes advantage of this fact to ensure that the
1038 * AST_CEL_CHANNEL_END is not posted if we have not posted the
1039 * AST_CEL_CHANNEL_START yet.
1042 if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
1043 return ast_channel_unref(tmp);
1046 /* Always watch the alertpipe */
1047 ast_channel_set_fd(tmp, AST_ALERT_FD, ast_channel_internal_alert_readfd(tmp));
1048 /* And timing pipe */
1049 ast_channel_set_fd(tmp, AST_TIMING_FD, ast_channel_timingfd(tmp));
1052 ast_channel_state_set(tmp, state);
1054 ast_channel_streamid_set(tmp, -1);
1056 ast_channel_fin_set(tmp, global_fin);
1057 ast_channel_fout_set(tmp, global_fout);
1060 ast_channel_creationtime_set(tmp, &now);
1062 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1063 ast_channel_uniqueid_build(tmp, "%li.%d", (long) time(NULL),
1064 ast_atomic_fetchadd_int(&uniqueint, 1));
1066 ast_channel_uniqueid_build(tmp, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
1067 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1070 if (!ast_strlen_zero(linkedid)) {
1071 ast_channel_linkedid_set(tmp, linkedid);
1073 ast_channel_linkedid_set(tmp, ast_channel_uniqueid(tmp));
1076 if (!ast_strlen_zero(name_fmt)) {
1077 char *slash, *slash2;
1078 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1079 * And they all use slightly different formats for their name string.
1080 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1081 * This means, that the stringfields must have a routine that takes the va_lists directly, and
1082 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1083 * This new function was written so this can be accomplished.
1085 ast_channel_name_build_va(tmp, name_fmt, ap);
1086 tech = ast_strdupa(ast_channel_name(tmp));
1087 if ((slash = strchr(tech, '/'))) {
1088 if ((slash2 = strchr(slash + 1, '/'))) {
1096 * Start the string with '-' so it becomes an empty string
1097 * in the destructor.
1099 ast_channel_name_set(tmp, "-**Unknown**");
1102 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1104 /* These 4 variables need to be set up for the cdr_init() to work right */
1106 ast_channel_amaflags_set(tmp, amaflag);
1108 ast_channel_amaflags_set(tmp, ast_default_amaflags);
1111 if (!ast_strlen_zero(acctcode))
1112 ast_channel_accountcode_set(tmp, acctcode);
1114 ast_channel_accountcode_set(tmp, ast_default_accountcode);
1116 ast_channel_context_set(tmp, S_OR(context, "default"));
1117 ast_channel_exten_set(tmp, S_OR(exten, "s"));
1118 ast_channel_priority_set(tmp, 1);
1120 ast_channel_cdr_set(tmp, ast_cdr_alloc());
1121 ast_cdr_init(ast_channel_cdr(tmp), tmp);
1122 ast_cdr_start(ast_channel_cdr(tmp));
1124 ast_atomic_fetchadd_int(&chancount, +1);
1125 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1127 headp = ast_channel_varshead(tmp);
1128 AST_LIST_HEAD_INIT_NOLOCK(headp);
1130 ast_pbx_hangup_handler_init(tmp);
1131 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1133 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_autochans(tmp));
1135 ast_channel_language_set(tmp, defaultlanguage);
1137 ast_channel_tech_set(tmp, &null_tech);
1139 ao2_link(channels, tmp);
1142 * And now, since the channel structure is built, and has its name, let's
1143 * call the manager event generator with this Newchannel event. This is the
1144 * proper and correct place to make this call, but you sure do have to pass
1145 * a lot of data into this func to do it here!
1147 if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1149 <managerEventInstance>
1150 <synopsis>Raised when a new channel is created.</synopsis>
1152 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Newstate']/managerEventInstance/syntax/parameter[@name='ChannelState'])" />
1153 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Newstate']/managerEventInstance/syntax/parameter[@name='ChannelStateDesc'])" />
1155 </managerEventInstance>
1157 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1159 "ChannelState: %d\r\n"
1160 "ChannelStateDesc: %s\r\n"
1161 "CallerIDNum: %s\r\n"
1162 "CallerIDName: %s\r\n"
1163 "AccountCode: %s\r\n"
1167 ast_channel_name(tmp),
1169 ast_state2str(state),
1172 ast_channel_accountcode(tmp),
1175 ast_channel_uniqueid(tmp));
1178 ast_channel_internal_finalize(tmp);
1182 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1183 const char *cid_name, const char *acctcode,
1184 const char *exten, const char *context,
1185 const char *linkedid, const int amaflag,
1186 const char *file, int line, const char *function,
1187 const char *name_fmt, ...)
1190 struct ast_channel *result;
1192 va_start(ap, name_fmt);
1193 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1194 linkedid, amaflag, file, line, function, name_fmt, ap);
1200 /* only do the minimum amount of work needed here to make a channel
1201 * structure that can be used to expand channel vars */
1202 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1203 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1205 struct ast_channel *ast_dummy_channel_alloc(void)
1208 struct ast_channel *tmp;
1209 struct varshead *headp;
1211 if (!(tmp = ast_channel_internal_alloc(ast_dummy_channel_destructor))) {
1212 /* Dummy channel structure allocation failure. */
1216 ast_pbx_hangup_handler_init(tmp);
1217 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1220 * Init file descriptors to unopened state just in case
1221 * autoservice is called on the channel or something tries to
1222 * read a frame from it.
1224 ast_channel_timingfd_set(tmp, -1);
1225 ast_channel_internal_alertpipe_clear(tmp);
1226 ast_channel_internal_fd_clear_all(tmp);
1228 ast_channel_epfd_set(tmp, -1);
1231 headp = ast_channel_varshead(tmp);
1232 AST_LIST_HEAD_INIT_NOLOCK(headp);
1237 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1239 struct ast_frame *f;
1240 struct ast_frame *cur;
1241 unsigned int new_frames = 0;
1242 unsigned int new_voice_frames = 0;
1243 unsigned int queued_frames = 0;
1244 unsigned int queued_voice_frames = 0;
1245 AST_LIST_HEAD_NOLOCK(,ast_frame) frames;
1247 ast_channel_lock(chan);
1250 * Check the last frame on the queue if we are queuing the new
1253 cur = AST_LIST_LAST(ast_channel_readq(chan));
1254 if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1255 switch (cur->subclass.integer) {
1256 case AST_CONTROL_END_OF_Q:
1257 if (fin->frametype == AST_FRAME_CONTROL
1258 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1260 * Destroy the end-of-Q marker frame so we can queue the hangup
1261 * frame in its place.
1263 AST_LIST_REMOVE(ast_channel_readq(chan), cur, frame_list);
1267 * This has degenerated to a normal queue append anyway. Since
1268 * we just destroyed the last frame in the queue we must make
1269 * sure that "after" is NULL or bad things will happen.
1275 case AST_CONTROL_HANGUP:
1276 /* Don't queue anything. */
1277 ast_channel_unlock(chan);
1284 /* Build copies of all the new frames and count them */
1285 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1286 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1287 if (!(f = ast_frdup(cur))) {
1288 if (AST_LIST_FIRST(&frames)) {
1289 ast_frfree(AST_LIST_FIRST(&frames));
1291 ast_channel_unlock(chan);
1295 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1297 if (f->frametype == AST_FRAME_VOICE) {
1302 /* Count how many frames exist on the queue */
1303 AST_LIST_TRAVERSE(ast_channel_readq(chan), cur, frame_list) {
1305 if (cur->frametype == AST_FRAME_VOICE) {
1306 queued_voice_frames++;
1310 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1312 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1313 AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), cur, frame_list) {
1314 /* Save the most recent frame */
1315 if (!AST_LIST_NEXT(cur, frame_list)) {
1317 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1321 AST_LIST_REMOVE_CURRENT(frame_list);
1325 AST_LIST_TRAVERSE_SAFE_END;
1329 AST_LIST_INSERT_LIST_AFTER(ast_channel_readq(chan), &frames, after, frame_list);
1332 AST_LIST_APPEND_LIST(&frames, ast_channel_readq(chan), frame_list);
1333 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_readq(chan));
1335 AST_LIST_APPEND_LIST(ast_channel_readq(chan), &frames, frame_list);
1338 if (ast_channel_alert_writable(chan)) {
1339 if (ast_channel_alert_write(chan)) {
1340 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1341 ast_channel_name(chan), queued_frames, strerror(errno));
1343 } else if (ast_channel_timingfd(chan) > -1) {
1344 ast_timer_enable_continuous(ast_channel_timer(chan));
1345 } else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
1346 pthread_kill(ast_channel_blocker(chan), SIGURG);
1349 ast_channel_unlock(chan);
1354 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1356 return __ast_queue_frame(chan, fin, 0, NULL);
1359 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1361 return __ast_queue_frame(chan, fin, 1, NULL);
1364 /*! \brief Queue a hangup frame for channel */
1365 int ast_queue_hangup(struct ast_channel *chan)
1367 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1370 /* Yeah, let's not change a lock-critical value without locking */
1371 ast_channel_lock(chan);
1372 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1374 <managerEventInstance>
1375 <synopsis>Raised when a hangup is requested with no set cause.</synopsis>
1376 </managerEventInstance>
1378 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1381 ast_channel_name(chan),
1382 ast_channel_uniqueid(chan));
1384 res = ast_queue_frame(chan, &f);
1385 ast_channel_unlock(chan);
1389 /*! \brief Queue a hangup frame for channel */
1390 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1392 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1396 f.data.uint32 = cause;
1399 /* Yeah, let's not change a lock-critical value without locking */
1400 ast_channel_lock(chan);
1401 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1403 f.data.uint32 = ast_channel_hangupcause(chan);
1406 <managerEventInstance>
1407 <synopsis>Raised when a hangup is requested with a specific cause code.</synopsis>
1409 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Hangup']/managerEventInstance/syntax/parameter[@name='Cause'])" />
1411 </managerEventInstance>
1413 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1417 ast_channel_name(chan),
1418 ast_channel_uniqueid(chan),
1421 res = ast_queue_frame(chan, &f);
1422 ast_channel_unlock(chan);
1426 /*! \brief Queue a control frame */
1427 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1429 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1430 return ast_queue_frame(chan, &f);
1433 /*! \brief Queue a control frame with payload */
1434 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1435 const void *data, size_t datalen)
1437 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1438 return ast_queue_frame(chan, &f);
1441 /*! \brief Set defer DTMF flag on channel */
1442 int ast_channel_defer_dtmf(struct ast_channel *chan)
1447 pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1448 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1453 /*! \brief Unset defer DTMF flag on channel */
1454 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1457 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1460 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1461 void *data, int ao2_flags)
1463 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1466 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1468 struct ast_channel *chan = obj;
1469 const char *name = arg;
1470 size_t name_len = *(size_t *) data;
1471 int ret = CMP_MATCH;
1473 if (ast_strlen_zero(name)) {
1474 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1478 ast_channel_lock(chan);
1479 if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1480 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1481 ret = 0; /* name match failed, keep looking */
1483 ast_channel_unlock(chan);
1488 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1490 struct ast_channel *chan = obj;
1491 char *context = arg;
1493 int ret = CMP_MATCH;
1495 if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1496 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1500 ast_channel_lock(chan);
1501 if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1502 ret = 0; /* Context match failed, continue */
1503 } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1504 ret = 0; /* Extension match failed, continue */
1506 ast_channel_unlock(chan);
1511 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1513 struct ast_channel *chan = obj;
1514 char *uniqueid = arg;
1515 size_t id_len = *(size_t *) data;
1516 int ret = CMP_MATCH;
1518 if (ast_strlen_zero(uniqueid)) {
1519 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1523 ast_channel_lock(chan);
1524 if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1525 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1526 ret = 0; /* uniqueid match failed, keep looking */
1528 ast_channel_unlock(chan);
1533 struct ast_channel_iterator {
1534 /* storage for non-dynamically allocated iterator */
1535 struct ao2_iterator simple_iterator;
1536 /* pointer to the actual iterator (simple_iterator or a dynamically
1537 * allocated iterator)
1539 struct ao2_iterator *active_iterator;
1542 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1544 ao2_iterator_destroy(i->active_iterator);
1550 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1552 struct ast_channel_iterator *i;
1553 char *l_exten = (char *) exten;
1554 char *l_context = (char *) context;
1556 if (!(i = ast_calloc(1, sizeof(*i)))) {
1560 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1561 l_context, l_exten, OBJ_MULTIPLE);
1562 if (!i->active_iterator) {
1570 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1572 struct ast_channel_iterator *i;
1573 char *l_name = (char *) name;
1575 if (!(i = ast_calloc(1, sizeof(*i)))) {
1579 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1581 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1582 if (!i->active_iterator) {
1590 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1592 struct ast_channel_iterator *i;
1594 if (!(i = ast_calloc(1, sizeof(*i)))) {
1598 i->simple_iterator = ao2_iterator_init(channels, 0);
1599 i->active_iterator = &i->simple_iterator;
1604 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1606 return ao2_iterator_next(i->active_iterator);
1609 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1610 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1612 ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1616 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1618 struct ast_channel *chan;
1619 char *l_name = (char *) name;
1621 chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1622 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1627 if (ast_strlen_zero(l_name)) {
1628 /* We didn't have a name to search for so quit. */
1632 /* Now try a search for uniqueid. */
1633 return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1636 struct ast_channel *ast_channel_get_by_name(const char *name)
1638 return ast_channel_get_by_name_prefix(name, 0);
1641 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1643 char *l_exten = (char *) exten;
1644 char *l_context = (char *) context;
1646 return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1649 int ast_is_deferrable_frame(const struct ast_frame *frame)
1651 /* Do not add a default entry in this switch statement. Each new
1652 * frame type should be addressed directly as to whether it should
1653 * be queued up or not.
1655 switch (frame->frametype) {
1656 case AST_FRAME_CONTROL:
1657 case AST_FRAME_TEXT:
1658 case AST_FRAME_IMAGE:
1659 case AST_FRAME_HTML:
1662 case AST_FRAME_DTMF_END:
1663 case AST_FRAME_DTMF_BEGIN:
1664 case AST_FRAME_VOICE:
1665 case AST_FRAME_VIDEO:
1666 case AST_FRAME_NULL:
1669 case AST_FRAME_MODEM:
1675 /*! \brief Wait, look for hangups and condition arg */
1676 int ast_safe_sleep_conditional(struct ast_channel *chan, int timeout_ms, int (*cond)(void*), void *data)
1678 struct ast_frame *f;
1679 struct ast_silence_generator *silgen = NULL;
1681 struct timeval start;
1683 AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1685 AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1687 /* If no other generator is present, start silencegen while waiting */
1688 if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1689 silgen = ast_channel_start_silence_generator(chan);
1692 start = ast_tvnow();
1693 while ((ms = ast_remaining_ms(start, timeout_ms))) {
1694 struct ast_frame *dup_f = NULL;
1696 if (cond && ((*cond)(data) == 0)) {
1699 ms = ast_waitfor(chan, ms);
1711 if (!ast_is_deferrable_frame(f)) {
1716 if ((dup_f = ast_frisolate(f))) {
1720 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1725 /* stop silgen if present */
1727 ast_channel_stop_silence_generator(chan, silgen);
1730 /* We need to free all the deferred frames, but we only need to
1731 * queue the deferred frames if there was no error and no
1732 * hangup was received
1734 ast_channel_lock(chan);
1735 while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1737 ast_queue_frame_head(chan, f);
1741 ast_channel_unlock(chan);
1746 /*! \brief Wait, look for hangups */
1747 int ast_safe_sleep(struct ast_channel *chan, int ms)
1749 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1752 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1754 /* Safe, even if already unlinked. */
1755 ao2_unlink(channels, chan);
1756 return ast_channel_unref(chan);
1759 void ast_party_name_init(struct ast_party_name *init)
1762 init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1763 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1767 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1770 /* Don't copy to self */
1774 ast_free(dest->str);
1775 dest->str = ast_strdup(src->str);
1776 dest->char_set = src->char_set;
1777 dest->presentation = src->presentation;
1778 dest->valid = src->valid;
1781 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1784 init->char_set = guide->char_set;
1785 init->presentation = guide->presentation;
1786 init->valid = guide->valid;
1789 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1792 /* Don't set to self */
1796 if (src->str && src->str != dest->str) {
1797 ast_free(dest->str);
1798 dest->str = ast_strdup(src->str);
1801 dest->char_set = src->char_set;
1802 dest->presentation = src->presentation;
1803 dest->valid = src->valid;
1806 void ast_party_name_free(struct ast_party_name *doomed)
1808 ast_free(doomed->str);
1812 void ast_party_number_init(struct ast_party_number *init)
1815 init->plan = 0;/* Unknown */
1816 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1820 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1823 /* Don't copy to self */
1827 ast_free(dest->str);
1828 dest->str = ast_strdup(src->str);
1829 dest->plan = src->plan;
1830 dest->presentation = src->presentation;
1831 dest->valid = src->valid;
1834 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1837 init->plan = guide->plan;
1838 init->presentation = guide->presentation;
1839 init->valid = guide->valid;
1842 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1845 /* Don't set to self */
1849 if (src->str && src->str != dest->str) {
1850 ast_free(dest->str);
1851 dest->str = ast_strdup(src->str);
1854 dest->plan = src->plan;
1855 dest->presentation = src->presentation;
1856 dest->valid = src->valid;
1859 void ast_party_number_free(struct ast_party_number *doomed)
1861 ast_free(doomed->str);
1865 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1869 init->odd_even_indicator = 0;
1873 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1876 /* Don't copy to self */
1880 ast_free(dest->str);
1881 dest->str = ast_strdup(src->str);
1882 dest->type = src->type;
1883 dest->odd_even_indicator = src->odd_even_indicator;
1884 dest->valid = src->valid;
1887 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1890 init->type = guide->type;
1891 init->odd_even_indicator = guide->odd_even_indicator;
1892 init->valid = guide->valid;
1895 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1898 /* Don't set to self */
1902 if (src->str && src->str != dest->str) {
1903 ast_free(dest->str);
1904 dest->str = ast_strdup(src->str);
1907 dest->type = src->type;
1908 dest->odd_even_indicator = src->odd_even_indicator;
1909 dest->valid = src->valid;
1912 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1914 ast_free(doomed->str);
1918 void ast_set_party_id_all(struct ast_set_party_id *update_id)
1920 update_id->name = 1;
1921 update_id->number = 1;
1922 update_id->subaddress = 1;
1925 void ast_party_id_init(struct ast_party_id *init)
1927 ast_party_name_init(&init->name);
1928 ast_party_number_init(&init->number);
1929 ast_party_subaddress_init(&init->subaddress);
1933 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1936 /* Don't copy to self */
1940 ast_party_name_copy(&dest->name, &src->name);
1941 ast_party_number_copy(&dest->number, &src->number);
1942 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1944 ast_free(dest->tag);
1945 dest->tag = ast_strdup(src->tag);
1948 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1950 ast_party_name_set_init(&init->name, &guide->name);
1951 ast_party_number_set_init(&init->number, &guide->number);
1952 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1956 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1959 /* Don't set to self */
1963 if (!update || update->name) {
1964 ast_party_name_set(&dest->name, &src->name);
1966 if (!update || update->number) {
1967 ast_party_number_set(&dest->number, &src->number);
1969 if (!update || update->subaddress) {
1970 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1973 if (src->tag && src->tag != dest->tag) {
1974 ast_free(dest->tag);
1975 dest->tag = ast_strdup(src->tag);
1979 void ast_party_id_free(struct ast_party_id *doomed)
1981 ast_party_name_free(&doomed->name);
1982 ast_party_number_free(&doomed->number);
1983 ast_party_subaddress_free(&doomed->subaddress);
1985 ast_free(doomed->tag);
1989 int ast_party_id_presentation(const struct ast_party_id *id)
1991 int number_priority;
1993 int number_screening;
1997 /* Determine name presentation priority. */
1998 if (!id->name.valid) {
1999 name_value = AST_PRES_UNAVAILABLE;
2002 name_value = id->name.presentation & AST_PRES_RESTRICTION;
2003 switch (name_value) {
2004 case AST_PRES_RESTRICTED:
2007 case AST_PRES_ALLOWED:
2010 case AST_PRES_UNAVAILABLE:
2014 name_value = AST_PRES_UNAVAILABLE;
2020 /* Determine number presentation priority. */
2021 if (!id->number.valid) {
2022 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2023 number_value = AST_PRES_UNAVAILABLE;
2024 number_priority = 3;
2026 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
2027 number_value = id->number.presentation & AST_PRES_RESTRICTION;
2028 switch (number_value) {
2029 case AST_PRES_RESTRICTED:
2030 number_priority = 0;
2032 case AST_PRES_ALLOWED:
2033 number_priority = 1;
2035 case AST_PRES_UNAVAILABLE:
2036 number_priority = 2;
2039 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2040 number_value = AST_PRES_UNAVAILABLE;
2041 number_priority = 3;
2046 /* Select the wining presentation value. */
2047 if (name_priority < number_priority) {
2048 number_value = name_value;
2050 if (number_value == AST_PRES_UNAVAILABLE) {
2051 return AST_PRES_NUMBER_NOT_AVAILABLE;
2054 return number_value | number_screening;
2057 void ast_party_id_invalidate(struct ast_party_id *id)
2060 id->number.valid = 0;
2061 id->subaddress.valid = 0;
2064 void ast_party_id_reset(struct ast_party_id *id)
2066 ast_party_id_free(id);
2067 ast_party_id_init(id);
2070 struct ast_party_id ast_party_id_merge(struct ast_party_id *base, struct ast_party_id *overlay)
2072 struct ast_party_id merged;
2075 if (overlay->name.valid) {
2076 merged.name = overlay->name;
2078 if (overlay->number.valid) {
2079 merged.number = overlay->number;
2081 if (overlay->subaddress.valid) {
2082 merged.subaddress = overlay->subaddress;
2084 /* Note the actual structure is returned and not a pointer to it! */
2088 void ast_party_id_merge_copy(struct ast_party_id *dest, struct ast_party_id *base, struct ast_party_id *overlay)
2090 struct ast_party_id merged;
2092 merged = ast_party_id_merge(base, overlay);
2093 ast_party_id_copy(dest, &merged);
2096 void ast_party_dialed_init(struct ast_party_dialed *init)
2098 init->number.str = NULL;
2099 init->number.plan = 0;/* Unknown */
2100 ast_party_subaddress_init(&init->subaddress);
2101 init->transit_network_select = 0;
2104 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2107 /* Don't copy to self */
2111 ast_free(dest->number.str);
2112 dest->number.str = ast_strdup(src->number.str);
2113 dest->number.plan = src->number.plan;
2114 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2115 dest->transit_network_select = src->transit_network_select;
2118 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2120 init->number.str = NULL;
2121 init->number.plan = guide->number.plan;
2122 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2123 init->transit_network_select = guide->transit_network_select;
2126 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2128 if (src->number.str && src->number.str != dest->number.str) {
2129 ast_free(dest->number.str);
2130 dest->number.str = ast_strdup(src->number.str);
2132 dest->number.plan = src->number.plan;
2134 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2136 dest->transit_network_select = src->transit_network_select;
2139 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2141 ast_free(doomed->number.str);
2142 doomed->number.str = NULL;
2143 ast_party_subaddress_free(&doomed->subaddress);
2146 void ast_party_caller_init(struct ast_party_caller *init)
2148 ast_party_id_init(&init->id);
2149 ast_party_id_init(&init->ani);
2150 ast_party_id_init(&init->priv);
2154 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2157 /* Don't copy to self */
2161 ast_party_id_copy(&dest->id, &src->id);
2162 ast_party_id_copy(&dest->ani, &src->ani);
2163 ast_party_id_copy(&dest->priv, &src->priv);
2164 dest->ani2 = src->ani2;
2167 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2169 ast_party_id_set_init(&init->id, &guide->id);
2170 ast_party_id_set_init(&init->ani, &guide->ani);
2171 ast_party_id_set_init(&init->priv, &guide->priv);
2172 init->ani2 = guide->ani2;
2175 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2177 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2178 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2179 ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2180 dest->ani2 = src->ani2;
2183 void ast_party_caller_free(struct ast_party_caller *doomed)
2185 ast_party_id_free(&doomed->id);
2186 ast_party_id_free(&doomed->ani);
2187 ast_party_id_free(&doomed->priv);
2190 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2192 ast_party_id_init(&init->id);
2193 ast_party_id_init(&init->ani);
2194 ast_party_id_init(&init->priv);
2196 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2199 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2202 /* Don't copy to self */
2206 ast_party_id_copy(&dest->id, &src->id);
2207 ast_party_id_copy(&dest->ani, &src->ani);
2208 ast_party_id_copy(&dest->priv, &src->priv);
2209 dest->ani2 = src->ani2;
2210 dest->source = src->source;
2213 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2215 ast_party_id_set_init(&init->id, &guide->id);
2216 ast_party_id_set_init(&init->ani, &guide->ani);
2217 ast_party_id_set_init(&init->priv, &guide->priv);
2218 init->ani2 = guide->ani2;
2219 init->source = guide->source;
2222 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)
2224 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2225 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2226 ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2227 dest->ani2 = src->ani2;
2228 dest->source = src->source;
2231 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2233 connected->id = caller->id;
2234 connected->ani = caller->ani;
2235 connected->priv = caller->priv;
2236 connected->ani2 = caller->ani2;
2237 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2240 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2242 ast_party_id_free(&doomed->id);
2243 ast_party_id_free(&doomed->ani);
2244 ast_party_id_free(&doomed->priv);
2247 void ast_party_redirecting_reason_init(struct ast_party_redirecting_reason *init)
2250 init->code = AST_REDIRECTING_REASON_UNKNOWN;
2253 void ast_party_redirecting_reason_copy(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2259 ast_free(dest->str);
2260 dest->str = ast_strdup(src->str);
2261 dest->code = src->code;
2264 void ast_party_redirecting_reason_set_init(struct ast_party_redirecting_reason *init, const struct ast_party_redirecting_reason *guide)
2267 init->code = guide->code;
2270 void ast_party_redirecting_reason_set(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2276 if (src->str && src->str != dest->str) {
2277 ast_free(dest->str);
2278 dest->str = ast_strdup(src->str);
2281 dest->code = src->code;
2284 void ast_party_redirecting_reason_free(struct ast_party_redirecting_reason *doomed)
2286 ast_free(doomed->str);
2290 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2292 ast_party_id_init(&init->orig);
2293 ast_party_id_init(&init->from);
2294 ast_party_id_init(&init->to);
2295 ast_party_id_init(&init->priv_orig);
2296 ast_party_id_init(&init->priv_from);
2297 ast_party_id_init(&init->priv_to);
2298 ast_party_redirecting_reason_init(&init->reason);
2299 ast_party_redirecting_reason_init(&init->orig_reason);
2303 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2306 /* Don't copy to self */
2310 ast_party_id_copy(&dest->orig, &src->orig);
2311 ast_party_id_copy(&dest->from, &src->from);
2312 ast_party_id_copy(&dest->to, &src->to);
2313 ast_party_id_copy(&dest->priv_orig, &src->priv_orig);
2314 ast_party_id_copy(&dest->priv_from, &src->priv_from);
2315 ast_party_id_copy(&dest->priv_to, &src->priv_to);
2316 ast_party_redirecting_reason_copy(&dest->reason, &src->reason);
2317 ast_party_redirecting_reason_copy(&dest->orig_reason, &src->orig_reason);
2318 dest->count = src->count;
2321 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2323 ast_party_id_set_init(&init->orig, &guide->orig);
2324 ast_party_id_set_init(&init->from, &guide->from);
2325 ast_party_id_set_init(&init->to, &guide->to);
2326 ast_party_id_set_init(&init->priv_orig, &guide->priv_orig);
2327 ast_party_id_set_init(&init->priv_from, &guide->priv_from);
2328 ast_party_id_set_init(&init->priv_to, &guide->priv_to);
2329 ast_party_redirecting_reason_set_init(&init->reason, &guide->reason);
2330 ast_party_redirecting_reason_set_init(&init->orig_reason, &guide->orig_reason);
2331 init->count = guide->count;
2334 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2336 ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2337 ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2338 ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2339 ast_party_id_set(&dest->priv_orig, &src->priv_orig, update ? &update->priv_orig : NULL);
2340 ast_party_id_set(&dest->priv_from, &src->priv_from, update ? &update->priv_from : NULL);
2341 ast_party_id_set(&dest->priv_to, &src->priv_to, update ? &update->priv_to : NULL);
2342 ast_party_redirecting_reason_set(&dest->reason, &src->reason);
2343 ast_party_redirecting_reason_set(&dest->orig_reason, &src->orig_reason);
2344 dest->count = src->count;
2347 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2349 ast_party_id_free(&doomed->orig);
2350 ast_party_id_free(&doomed->from);
2351 ast_party_id_free(&doomed->to);
2352 ast_party_id_free(&doomed->priv_orig);
2353 ast_party_id_free(&doomed->priv_from);
2354 ast_party_id_free(&doomed->priv_to);
2355 ast_party_redirecting_reason_free(&doomed->reason);
2356 ast_party_redirecting_reason_free(&doomed->orig_reason);
2359 /*! \brief Free a channel structure */
2360 static void ast_channel_destructor(void *obj)
2362 struct ast_channel *chan = obj;
2366 struct ast_var_t *vardata;
2367 struct ast_frame *f;
2368 struct varshead *headp;
2369 struct ast_datastore *datastore;
2370 char device_name[AST_CHANNEL_NAME];
2371 struct ast_callid *callid;
2373 if (ast_channel_internal_is_finalized(chan)) {
2374 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2375 ast_cel_check_retire_linkedid(chan);
2378 ast_pbx_hangup_handler_destroy(chan);
2380 ast_channel_lock(chan);
2382 /* Get rid of each of the data stores on the channel */
2383 while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2384 /* Free the data store */
2385 ast_datastore_free(datastore);
2387 /* While the channel is locked, take the reference to its callid while we tear down the call. */
2388 callid = ast_channel_callid(chan);
2389 ast_channel_callid_cleanup(chan);
2391 ast_channel_unlock(chan);
2393 /* Lock and unlock the channel just to be sure nobody has it locked still
2394 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2395 ast_channel_lock(chan);
2396 ast_channel_unlock(chan);
2398 if (ast_channel_tech_pvt(chan)) {
2399 ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2400 ast_free(ast_channel_tech_pvt(chan));
2403 if (ast_channel_sched(chan)) {
2404 ast_sched_context_destroy(ast_channel_sched(chan));
2407 if (ast_channel_internal_is_finalized(chan)) {
2410 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2411 if ((dashptr = strrchr(device_name, '-'))) {
2415 device_name[0] = '\0';
2418 /* Stop monitoring */
2419 if (ast_channel_monitor(chan))
2420 ast_channel_monitor(chan)->stop( chan, 0 );
2422 /* If there is native format music-on-hold state, free it */
2423 if (ast_channel_music_state(chan))
2424 ast_moh_cleanup(chan);
2426 /* Free translators */
2427 if (ast_channel_readtrans(chan))
2428 ast_translator_free_path(ast_channel_readtrans(chan));
2429 if (ast_channel_writetrans(chan))
2430 ast_translator_free_path(ast_channel_writetrans(chan));
2431 if (ast_channel_pbx(chan))
2432 ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2434 ast_party_dialed_free(ast_channel_dialed(chan));
2435 ast_party_caller_free(ast_channel_caller(chan));
2436 ast_party_connected_line_free(ast_channel_connected(chan));
2437 ast_party_redirecting_free(ast_channel_redirecting(chan));
2439 /* Close pipes if appropriate */
2440 ast_channel_internal_alertpipe_close(chan);
2441 if (ast_channel_timer(chan)) {
2442 ast_timer_close(ast_channel_timer(chan));
2443 ast_channel_timer_set(chan, NULL);
2446 for (i = 0; i < AST_MAX_FDS; i++) {
2447 if (ast_channel_internal_epfd_data(chan, i)) {
2448 ast_free(ast_channel_internal_epfd_data(chan, i));
2451 close(ast_channel_epfd(chan));
2453 while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2456 /* loop over the variables list, freeing all data and deleting list items */
2457 /* no need to lock the list, as the channel is already locked */
2458 headp = ast_channel_varshead(chan);
2459 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2460 ast_var_delete(vardata);
2462 ast_app_group_discard(chan);
2464 /* Destroy the jitterbuffer */
2465 ast_jb_destroy(chan);
2467 if (ast_channel_cdr(chan)) {
2468 ast_cdr_discard(ast_channel_cdr(chan));
2469 ast_channel_cdr_set(chan, NULL);
2472 if (ast_channel_zone(chan)) {
2473 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2476 ast_channel_internal_cleanup(chan);
2478 if (device_name[0]) {
2480 * We have a device name to notify of a new state.
2482 * Queue an unknown state, because, while we know that this particular
2483 * instance is dead, we don't know the state of all other possible
2486 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);
2489 ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2491 ast_callid_unref(callid);
2494 ast_channel_named_callgroups_set(chan, NULL);
2495 ast_channel_named_pickupgroups_set(chan, NULL);
2497 ast_atomic_fetchadd_int(&chancount, -1);
2500 /*! \brief Free a dummy channel structure */
2501 static void ast_dummy_channel_destructor(void *obj)
2503 struct ast_channel *chan = obj;
2504 struct ast_datastore *datastore;
2505 struct ast_var_t *vardata;
2506 struct varshead *headp;
2508 ast_pbx_hangup_handler_destroy(chan);
2510 /* Get rid of each of the data stores on the channel */
2511 while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
2512 /* Free the data store */
2513 ast_datastore_free(datastore);
2516 ast_party_dialed_free(ast_channel_dialed(chan));
2517 ast_party_caller_free(ast_channel_caller(chan));
2518 ast_party_connected_line_free(ast_channel_connected(chan));
2519 ast_party_redirecting_free(ast_channel_redirecting(chan));
2521 /* loop over the variables list, freeing all data and deleting list items */
2522 /* no need to lock the list, as the channel is already locked */
2523 headp = ast_channel_varshead(chan);
2524 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2525 ast_var_delete(vardata);
2527 if (ast_channel_cdr(chan)) {
2528 ast_cdr_discard(ast_channel_cdr(chan));
2529 ast_channel_cdr_set(chan, NULL);
2532 ast_channel_internal_cleanup(chan);
2535 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2537 return ast_datastore_alloc(info, uid);
2540 int ast_channel_datastore_free(struct ast_datastore *datastore)
2542 return ast_datastore_free(datastore);
2545 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2547 struct ast_datastore *datastore = NULL, *datastore2;
2549 AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2550 if (datastore->inheritance > 0) {
2551 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2553 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2554 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2555 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2562 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2566 AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2571 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2573 return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2576 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2578 struct ast_datastore *datastore = NULL;
2583 AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2584 if (datastore->info != info) {
2589 /* matched by type only */
2593 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2594 /* Matched by type AND uid */
2602 /*! Set the file descriptor on the channel */
2603 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2606 struct epoll_event ev;
2607 struct ast_epoll_data *aed = NULL;
2609 if (ast_channel_fd_isset(chan, which)) {
2610 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2611 aed = ast_channel_internal_epfd_data(chan, which);
2614 /* If this new fd is valid, add it to the epoll */
2616 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2619 ast_channel_internal_epfd_data_set(chan, which, aed);
2623 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2625 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2627 /* We don't have to keep around this epoll data structure now */
2629 ast_channel_epfd_data_set(chan, which, NULL);
2632 ast_channel_internal_fd_set(chan, which, fd);
2636 /*! Add a channel to an optimized waitfor */
2637 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2640 struct epoll_event ev;
2643 if (ast_channel_epfd(chan0) == -1)
2646 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2647 for (i = 0; i < AST_MAX_FDS; i++) {
2648 if (!ast_channel_fd_isset(chan1, i)) {
2651 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2652 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2653 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2660 /*! Delete a channel from an optimized waitfor */
2661 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2664 struct epoll_event ev;
2667 if (ast_channel_epfd(chan0) == -1)
2670 for (i = 0; i < AST_MAX_FDS; i++) {
2671 if (!ast_channel_fd_isset(chan1, i)) {
2674 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2681 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2683 ast_channel_lock(chan);
2685 ast_channel_softhangup_internal_flag_clear(chan, flag);
2687 if (!ast_channel_softhangup_internal_flag(chan)) {
2688 struct ast_frame *fr;
2690 /* If we have completely cleared the softhangup flag,
2691 * then we need to fully abort the hangup process. This requires
2692 * pulling the END_OF_Q frame out of the channel frame queue if it
2693 * still happens to be there. */
2695 fr = AST_LIST_LAST(ast_channel_readq(chan));
2696 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2697 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2698 AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2703 ast_channel_unlock(chan);
2706 /*! \brief Softly hangup a channel, don't lock */
2707 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2709 ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2710 /* Inform channel driver that we need to be hung up, if it cares */
2711 ast_channel_softhangup_internal_flag_add(chan, cause);
2712 ast_queue_frame(chan, &ast_null_frame);
2713 /* Interrupt any poll call or such */
2714 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2715 pthread_kill(ast_channel_blocker(chan), SIGURG);
2719 /*! \brief Softly hangup a channel, lock */
2720 int ast_softhangup(struct ast_channel *chan, int cause)
2724 ast_channel_lock(chan);
2725 res = ast_softhangup_nolock(chan, cause);
2727 <managerEventInstance>
2728 <synopsis>Raised when a soft hangup is requested with a specific cause code.</synopsis>
2730 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Hangup']/managerEventInstance/syntax/parameter[@name='Cause'])" />
2732 </managerEventInstance>
2734 manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2738 ast_channel_name(chan),
2739 ast_channel_uniqueid(chan),
2741 ast_channel_unlock(chan);
2746 static void free_translation(struct ast_channel *clonechan)
2748 if (ast_channel_writetrans(clonechan))
2749 ast_translator_free_path(ast_channel_writetrans(clonechan));
2750 if (ast_channel_readtrans(clonechan))
2751 ast_translator_free_path(ast_channel_readtrans(clonechan));
2752 ast_channel_writetrans_set(clonechan, NULL);
2753 ast_channel_readtrans_set(clonechan, NULL);
2754 if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2755 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2756 ast_format_clear(ast_channel_rawreadformat(clonechan));
2758 struct ast_format tmpfmt;
2759 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2760 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2761 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2765 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2767 struct ast_channel *bridge;
2769 ast_channel_lock(chan);
2770 if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2771 ast_channel_hangupsource_set(chan, source);
2773 bridge = ast_bridged_channel(chan);
2775 ast_channel_ref(bridge);
2777 ast_channel_unlock(chan);
2780 ast_channel_lock(bridge);
2781 if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
2782 ast_channel_hangupsource_set(bridge, source);
2784 ast_channel_unlock(bridge);
2785 ast_channel_unref(bridge);
2789 static void destroy_hooks(struct ast_channel *chan)
2791 if (ast_channel_audiohooks(chan)) {
2792 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2793 ast_channel_audiohooks_set(chan, NULL);
2796 ast_framehook_list_destroy(chan);
2799 /*! \brief Hangup a channel */
2800 int ast_hangup(struct ast_channel *chan)
2802 char extra_str[64]; /* used for cel logging below */
2804 ast_autoservice_stop(chan);
2806 ast_channel_lock(chan);
2809 * Do the masquerade if someone is setup to masquerade into us.
2811 * NOTE: We must hold the channel lock after testing for a
2812 * pending masquerade and setting the channel as a zombie to
2813 * prevent __ast_channel_masquerade() from setting up a
2814 * masquerade with a dead channel.
2816 while (ast_channel_masq(chan)) {
2817 ast_channel_unlock(chan);
2818 ast_do_masquerade(chan);
2819 ast_channel_lock(chan);
2822 if (ast_channel_masqr(chan)) {
2824 * This channel is one which will be masqueraded into something.
2825 * Mark it as a zombie already so ast_do_masquerade() will know
2828 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2829 destroy_hooks(chan);
2830 ast_channel_unlock(chan);
2834 /* Mark as a zombie so a masquerade cannot be setup on this channel. */
2835 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2837 ast_channel_unlock(chan);
2840 * XXX if running the hangup handlers here causes problems
2841 * because the handlers take too long to execute, we could move
2842 * the meat of this function into another thread. A thread
2843 * where channels go to die.
2845 * If this is done, ast_autoservice_chan_hangup_peer() will no
2848 ast_pbx_hangup_handler_run(chan);
2849 ao2_unlink(channels, chan);
2850 ast_channel_lock(chan);
2852 destroy_hooks(chan);
2854 free_translation(chan);
2855 /* Close audio stream */
2856 if (ast_channel_stream(chan)) {
2857 ast_closestream(ast_channel_stream(chan));
2858 ast_channel_stream_set(chan, NULL);
2860 /* Close video stream */
2861 if (ast_channel_vstream(chan)) {
2862 ast_closestream(ast_channel_vstream(chan));
2863 ast_channel_vstream_set(chan, NULL);
2865 if (ast_channel_sched(chan)) {
2866 ast_sched_context_destroy(ast_channel_sched(chan));
2867 ast_channel_sched_set(chan, NULL);
2870 if (ast_channel_generatordata(chan)) { /* Clear any tone stuff remaining */
2871 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2872 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2875 ast_channel_generatordata_set(chan, NULL);
2876 ast_channel_generator_set(chan, NULL);
2878 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"), ""));
2879 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2881 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2882 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2883 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2884 (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2885 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2888 ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2889 if (ast_channel_tech(chan)->hangup) {
2890 ast_channel_tech(chan)->hangup(chan);
2893 ast_channel_unlock(chan);
2897 <managerEventInstance>
2898 <synopsis>Raised when a channel is hung up.</synopsis>
2900 <parameter name="Cause">
2901 <para>A numeric cause code for why the channel was hung up.</para>
2903 <parameter name="Cause-txt">
2904 <para>A description of why the channel was hung up.</para>
2907 </managerEventInstance>
2909 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2912 "CallerIDNum: %s\r\n"
2913 "CallerIDName: %s\r\n"
2914 "ConnectedLineNum: %s\r\n"
2915 "ConnectedLineName: %s\r\n"
2916 "AccountCode: %s\r\n"
2918 "Cause-txt: %s\r\n",
2919 ast_channel_name(chan),
2920 ast_channel_uniqueid(chan),
2921 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
2922 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
2923 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
2924 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
2925 ast_channel_accountcode(chan),
2926 ast_channel_hangupcause(chan),
2927 ast_cause2str(ast_channel_hangupcause(chan))
2930 if (ast_channel_cdr(chan) && !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_BRIDGED) &&
2931 !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_POST_DISABLED) &&
2932 (ast_channel_cdr(chan)->disposition != AST_CDR_NULL || ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_DIALED))) {
2933 ast_channel_lock(chan);
2934 ast_cdr_end(ast_channel_cdr(chan));
2935 ast_cdr_detach(ast_channel_cdr(chan));
2936 ast_channel_cdr_set(chan, NULL);
2937 ast_channel_unlock(chan);
2940 ast_channel_unref(chan);
2945 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2949 ast_channel_lock(chan);
2951 /* You can't answer an outbound call */
2952 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2953 ast_channel_unlock(chan);
2957 /* Stop if we're a zombie or need a soft hangup */
2958 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2959 ast_channel_unlock(chan);
2963 ast_channel_unlock(chan);
2965 switch (ast_channel_state(chan)) {
2966 case AST_STATE_RINGING:
2967 case AST_STATE_RING:
2968 ast_channel_lock(chan);
2969 if (ast_channel_tech(chan)->answer) {
2970 res = ast_channel_tech(chan)->answer(chan);
2972 ast_setstate(chan, AST_STATE_UP);
2974 ast_cdr_answer(ast_channel_cdr(chan));
2976 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2977 ast_channel_unlock(chan);
2980 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2981 /* Calling ast_cdr_answer when it it has previously been called
2982 * is essentially a no-op, so it is safe.
2985 ast_cdr_answer(ast_channel_cdr(chan));
2992 ast_indicate(chan, -1);
2997 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
3000 enum ast_channel_state old_state;
3002 old_state = ast_channel_state(chan);
3003 if ((res = ast_raw_answer(chan, cdr_answer))) {
3007 switch (old_state) {
3008 case AST_STATE_RINGING:
3009 case AST_STATE_RING:
3010 /* wait for media to start flowing, but don't wait any longer
3011 * than 'delay' or 500 milliseconds, whichever is longer
3014 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
3015 struct ast_frame *cur, *new;
3016 int timeout_ms = MAX(delay, 500);
3017 unsigned int done = 0;
3018 struct timeval start;
3020 AST_LIST_HEAD_INIT_NOLOCK(&frames);
3022 start = ast_tvnow();
3024 int ms = ast_remaining_ms(start, timeout_ms);
3025 ms = ast_waitfor(chan, ms);
3027 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
3032 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));
3035 cur = ast_read(chan);
3036 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
3037 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
3042 ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
3046 if ((new = ast_frisolate(cur)) != cur) {
3050 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
3052 /* if a specific delay period was requested, continue
3053 * until that delay has passed. don't stop just because
3054 * incoming media has arrived.
3060 switch (new->frametype) {
3061 /* all of these frametypes qualify as 'media' */
3062 case AST_FRAME_VOICE:
3063 case AST_FRAME_VIDEO:
3064 case AST_FRAME_TEXT:
3065 case AST_FRAME_DTMF_BEGIN:
3066 case AST_FRAME_DTMF_END:
3067 case AST_FRAME_IMAGE:
3068 case AST_FRAME_HTML:
3069 case AST_FRAME_MODEM:
3072 case AST_FRAME_CONTROL:
3074 case AST_FRAME_NULL:
3085 ast_channel_lock(chan);
3086 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
3087 ast_queue_frame_head(chan, cur);
3090 ast_channel_unlock(chan);
3101 int ast_answer(struct ast_channel *chan)
3103 return __ast_answer(chan, 0, 1);
3106 void ast_deactivate_generator(struct ast_channel *chan)
3108 ast_channel_lock(chan);
3109 if (ast_channel_generatordata(chan)) {
3110 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3111 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3113 ast_channel_generatordata_set(chan, NULL);
3114 ast_channel_generator_set(chan, NULL);
3115 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
3116 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
3117 ast_settimeout(chan, 0, NULL, NULL);
3119 ast_channel_unlock(chan);
3122 static void generator_write_format_change(struct ast_channel *chan)
3124 ast_channel_lock(chan);
3125 if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
3126 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
3128 ast_channel_unlock(chan);
3131 static int generator_force(const void *data)
3133 /* Called if generator doesn't have data */
3136 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
3137 struct ast_channel *chan = (struct ast_channel *)data;
3139 ast_channel_lock(chan);
3140 tmp = ast_channel_generatordata(chan);
3141 ast_channel_generatordata_set(chan, NULL);
3142 if (ast_channel_generator(chan))
3143 generate = ast_channel_generator(chan)->generate;
3144 ast_channel_unlock(chan);
3146 if (!tmp || !generate)
3149 res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
3151 ast_channel_lock(chan);
3152 if (ast_channel_generator(chan) && generate == ast_channel_generator(chan)->generate) {
3153 ast_channel_generatordata_set(chan, tmp);
3155 ast_channel_unlock(chan);
3158 ast_debug(1, "Auto-deactivating generator\n");
3159 ast_deactivate_generator(chan);
3165 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
3168 void *generatordata = NULL;
3170 ast_channel_lock(chan);
3171 if (ast_channel_generatordata(chan)) {
3172 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3173 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3176 if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
3179 ast_channel_generatordata_set(chan, generatordata);
3181 ast_settimeout(chan, 50, generator_force, chan);
3182 ast_channel_generator_set(chan, gen);
3184 ast_channel_unlock(chan);
3191 /*! \brief Wait for x amount of time on a file descriptor to have input. */
3192 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
3195 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
3199 /*! \brief Wait for x amount of time on a file descriptor to have input. */
3201 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
3202 int *exception, int *outfd, int *ms)
3204 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3205 int *exception, int *outfd, int *ms)
3208 struct timeval start = { 0 , 0 };
3209 struct pollfd *pfds = NULL;
3214 struct timeval now = { 0, 0 };
3215 struct timeval whentohangup = { 0, 0 }, diff;
3216 struct ast_channel *winner = NULL;
3229 if ((sz = n * AST_MAX_FDS + nfds)) {
3230 pfds = ast_alloca(sizeof(*pfds) * sz);
3231 fdmap = ast_alloca(sizeof(*fdmap) * sz);
3233 /* nothing to allocate and no FDs to check */
3237 /* Perform any pending masquerades */
3238 for (x = 0; x < n; x++) {
3239 while (ast_channel_masq(c[x])) {
3240 ast_do_masquerade(c[x]);
3243 ast_channel_lock(c[x]);
3244 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
3245 if (ast_tvzero(whentohangup))
3247 diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
3248 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3249 ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3250 /* Should already be hungup */
3251 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3252 ast_channel_unlock(c[x]);
3255 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3256 whentohangup = diff;
3258 ast_channel_unlock(c[x]);
3260 /* Wait full interval */
3262 /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3263 if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3264 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
3265 if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
3268 } else if (!ast_tvzero(whentohangup) && rms < 0) {
3269 /* Tiny corner case... call would need to last >24 days */
3273 * Build the pollfd array, putting the channels' fds first,
3274 * followed by individual fds. Order is important because
3275 * individual fd's must have priority over channel fds.
3278 for (x = 0; x < n; x++) {
3279 for (y = 0; y < AST_MAX_FDS; y++) {
3280 fdmap[max].fdno = y; /* fd y is linked to this pfds */
3281 fdmap[max].chan = x; /* channel x is linked to this pfds */
3282 max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3284 CHECK_BLOCKING(c[x]);
3286 /* Add the individual fds */
3287 for (x = 0; x < nfds; x++) {
3288 fdmap[max].chan = -1;
3289 max += ast_add_fd(&pfds[max], fds[x]);
3293 start = ast_tvnow();
3296 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3299 if (kbrms > 600000) {
3302 res = ast_poll(pfds, max, kbrms);
3306 } while (!res && (rms > 0));
3308 res = ast_poll(pfds, max, rms);
3310 for (x = 0; x < n; x++) {
3311 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3313 if (res < 0) { /* Simulate a timeout if we were interrupted */
3314 if (errno != EINTR) {
3319 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
3321 for (x = 0; x < n; x++) {
3322 if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3323 ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3324 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3325 if (winner == NULL) {
3331 if (res == 0) { /* no fd ready, reset timeout and done */
3332 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
3336 * Then check if any channel or fd has a pending event.
3337 * Remember to check channels first and fds last, as they
3338 * must have priority on setting 'winner'
3340 for (x = 0; x < max; x++) {
3341 res = pfds[x].revents;
3345 if (fdmap[x].chan >= 0) { /* this is a channel */
3346 winner = c[fdmap[x].chan]; /* override previous winners */
3347 if (res & POLLPRI) {
3348 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3350 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3352 ast_channel_fdno_set(winner, fdmap[x].fdno);
3353 } else { /* this is an fd */
3355 *outfd = pfds[x].fd;