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"
80 #include <sys/epoll.h>
83 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
86 #endif /* defined(HAVE_PRI) */
87 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
89 struct ast_epoll_data {
90 struct ast_channel *chan;
94 /* uncomment if you have problems with 'monitoring' synchronized files */
96 #define MONITOR_CONSTANT_DELAY
97 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
100 /*! \brief Prevent new channel allocation if shutting down. */
101 static int shutting_down;
103 static int uniqueint;
104 static int chancount;
106 unsigned long global_fin, global_fout;
108 AST_THREADSTORAGE(state2str_threadbuf);
109 #define STATE2STR_BUFSIZE 32
111 /*! Default amount of time to use when emulating a digit as a begin and end
113 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
115 /*! Minimum amount of time between the end of the last digit and the beginning
116 * of a new one - 45ms */
117 #define AST_MIN_DTMF_GAP 45
119 /*! \brief List of channel drivers */
121 const struct ast_channel_tech *tech;
122 AST_LIST_ENTRY(chanlist) list;
126 /*! \brief Structure to hold channel context backtrace data */
127 struct ast_chan_trace_data {
129 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
132 /*! \brief Structure to save contexts where an ast_chan has been into */
133 struct ast_chan_trace {
134 char context[AST_MAX_CONTEXT];
135 char exten[AST_MAX_EXTENSION];
137 AST_LIST_ENTRY(ast_chan_trace) entry;
141 /*! \brief the list of registered channel types */
142 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
145 #define NUM_CHANNEL_BUCKETS 61
147 #define NUM_CHANNEL_BUCKETS 1567
150 /*! \brief All active channels on the system */
151 static struct ao2_container *channels;
153 /*! \brief map AST_CAUSE's to readable string representations
157 static const struct {
162 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
163 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
164 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
165 { AST_CAUSE_MISDIALLED_TRUNK_PREFIX, "MISDIALLED_TRUNK_PREFIX", "Misdialed trunk prefix" },
166 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
167 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
168 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
169 { AST_CAUSE_NUMBER_PORTED_NOT_HERE, "NUMBER_PORTED_NOT_HERE", "Number ported elsewhere" },
170 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
171 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
172 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
173 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
174 { AST_CAUSE_SUBSCRIBER_ABSENT, "SUBSCRIBER_ABSENT", "Subscriber absent" },
175 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
176 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
177 { AST_CAUSE_REDIRECTED_TO_NEW_DESTINATION, "REDIRECTED_TO_NEW_DESTINATION", "Redirected to new destination" },
178 { AST_CAUSE_ANSWERED_ELSEWHERE, "ANSWERED_ELSEWHERE", "Answered elsewhere" },
179 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
180 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
181 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
182 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
183 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
184 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
185 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
186 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
187 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
188 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
189 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
190 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
191 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
192 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
193 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
194 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
195 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
196 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
197 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
198 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
199 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
200 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
201 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
202 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
203 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
204 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
205 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
206 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
207 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
208 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
209 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
210 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
213 struct ast_variable *ast_channeltype_list(void)
216 struct ast_variable *var = NULL, *prev = NULL;
218 AST_RWLIST_RDLOCK(&backends);
219 AST_RWLIST_TRAVERSE(&backends, cl, list) {
221 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
224 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
228 AST_RWLIST_UNLOCK(&backends);
233 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
234 static const char *party_number_ton2str(int ton)
236 #if defined(HAVE_PRI)
237 switch ((ton >> 4) & 0x07) {
238 case PRI_TON_INTERNATIONAL:
239 return "International";
240 case PRI_TON_NATIONAL:
242 case PRI_TON_NET_SPECIFIC:
243 return "Network Specific";
244 case PRI_TON_SUBSCRIBER:
246 case PRI_TON_ABBREVIATED:
247 return "Abbreviated";
248 case PRI_TON_RESERVED:
250 case PRI_TON_UNKNOWN:
254 #endif /* defined(HAVE_PRI) */
257 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
259 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
260 static const char *party_number_plan2str(int plan)
262 #if defined(HAVE_PRI)
263 switch (plan & 0x0F) {
265 case PRI_NPI_UNKNOWN:
267 case PRI_NPI_E163_E164:
268 return "Public (E.163/E.164)";
270 return "Data (X.121)";
272 return "Telex (F.69)";
273 case PRI_NPI_NATIONAL:
274 return "National Standard";
275 case PRI_NPI_PRIVATE:
277 case PRI_NPI_RESERVED:
280 #endif /* defined(HAVE_PRI) */
283 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
285 /*! \brief Show channel types - CLI command */
286 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
288 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
294 e->command = "core show channeltypes";
296 "Usage: core show channeltypes\n"
297 " Lists available channel types registered in your\n"
298 " Asterisk server.\n";
305 return CLI_SHOWUSAGE;
307 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
308 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
310 AST_RWLIST_RDLOCK(&backends);
311 AST_RWLIST_TRAVERSE(&backends, cl, list) {
312 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
313 (cl->tech->devicestate) ? "yes" : "no",
314 (cl->tech->indicate) ? "yes" : "no",
315 (cl->tech->transfer) ? "yes" : "no");
318 AST_RWLIST_UNLOCK(&backends);
320 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
327 static char *complete_channeltypes(struct ast_cli_args *a)
337 wordlen = strlen(a->word);
339 AST_RWLIST_RDLOCK(&backends);
340 AST_RWLIST_TRAVERSE(&backends, cl, list) {
341 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
342 ret = ast_strdup(cl->tech->type);
346 AST_RWLIST_UNLOCK(&backends);
351 /*! \brief Show details about a channel driver - CLI command */
352 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
354 struct chanlist *cl = NULL;
359 e->command = "core show channeltype";
361 "Usage: core show channeltype <name>\n"
362 " Show details about the specified channel type, <name>.\n";
365 return complete_channeltypes(a);
369 return CLI_SHOWUSAGE;
371 AST_RWLIST_RDLOCK(&backends);
373 AST_RWLIST_TRAVERSE(&backends, cl, list) {
374 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
380 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
381 AST_RWLIST_UNLOCK(&backends);
386 "-- Info about channel driver: %s --\n"
387 " Device State: %s\n"
390 " Capabilities: %s\n"
394 " Image Support: %s\n"
395 " Text Support: %s\n",
397 (cl->tech->devicestate) ? "yes" : "no",
398 (cl->tech->indicate) ? "yes" : "no",
399 (cl->tech->transfer) ? "yes" : "no",
400 ast_getformatname_multiple(buf, sizeof(buf), cl->tech->capabilities),
401 (cl->tech->send_digit_begin) ? "yes" : "no",
402 (cl->tech->send_digit_end) ? "yes" : "no",
403 (cl->tech->send_html) ? "yes" : "no",
404 (cl->tech->send_image) ? "yes" : "no",
405 (cl->tech->send_text) ? "yes" : "no"
409 AST_RWLIST_UNLOCK(&backends);
414 static struct ast_cli_entry cli_channel[] = {
415 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
416 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
419 static struct ast_frame *kill_read(struct ast_channel *chan)
421 /* Hangup channel. */
425 static struct ast_frame *kill_exception(struct ast_channel *chan)
427 /* Hangup channel. */
431 static int kill_write(struct ast_channel *chan, struct ast_frame *frame)
433 /* Hangup channel. */
437 static int kill_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
439 /* No problem fixing up the channel. */
443 static int kill_hangup(struct ast_channel *chan)
445 ast_channel_tech_pvt_set(chan, NULL);
450 * \brief Kill the channel channel driver technology descriptor.
453 * The purpose of this channel technology is to encourage the
454 * channel to hangup as quickly as possible.
456 * \note Used by DTMF atxfer and zombie channels.
458 const struct ast_channel_tech ast_kill_tech = {
460 .description = "Kill channel (should not see this)",
462 .exception = kill_exception,
465 .hangup = kill_hangup,
469 /*! \brief Destructor for the channel trace datastore */
470 static void ast_chan_trace_destroy_cb(void *data)
472 struct ast_chan_trace *trace;
473 struct ast_chan_trace_data *traced = data;
474 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
480 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
481 static const const struct ast_datastore_info ast_chan_trace_datastore_info = {
483 .destroy = ast_chan_trace_destroy_cb
486 /*! \brief Put the channel backtrace in a string */
487 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
490 struct ast_chan_trace *trace;
491 struct ast_chan_trace_data *traced;
492 struct ast_datastore *store;
494 ast_channel_lock(chan);
495 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
497 ast_channel_unlock(chan);
500 traced = store->data;
502 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
503 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
504 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
510 ast_channel_unlock(chan);
514 /* !\brief Whether or not context tracing is enabled */
515 int ast_channel_trace_is_enabled(struct ast_channel *chan)
517 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
520 return ((struct ast_chan_trace_data *)store->data)->enabled;
523 /*! \brief Update the context backtrace data if tracing is enabled */
524 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
526 struct ast_chan_trace *trace;
527 if (!traced->enabled)
529 /* If the last saved context does not match the current one
530 OR we have not saved any context so far, then save the current context */
531 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan))) ||
532 (AST_LIST_EMPTY(&traced->trace))) {
533 /* Just do some debug logging */
534 if (AST_LIST_EMPTY(&traced->trace))
535 ast_debug(1, "Setting initial trace context to %s\n", ast_channel_context(chan));
537 ast_debug(1, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan));
538 /* alloc or bail out */
539 trace = ast_malloc(sizeof(*trace));
542 /* save the current location and store it in the trace list */
543 ast_copy_string(trace->context, ast_channel_context(chan), sizeof(trace->context));
544 ast_copy_string(trace->exten, ast_channel_exten(chan), sizeof(trace->exten));
545 trace->priority = ast_channel_priority(chan);
546 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
551 /*! \brief Update the context backtrace if tracing is enabled */
552 int ast_channel_trace_update(struct ast_channel *chan)
554 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
557 return ast_channel_trace_data_update(chan, store->data);
560 /*! \brief Enable context tracing in the channel */
561 int ast_channel_trace_enable(struct ast_channel *chan)
563 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
564 struct ast_chan_trace_data *traced;
566 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
569 traced = ast_calloc(1, sizeof(*traced));
571 ast_datastore_free(store);
574 store->data = traced;
575 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
576 ast_channel_datastore_add(chan, store);
578 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
579 ast_channel_trace_data_update(chan, store->data);
583 /*! \brief Disable context tracing in the channel */
584 int ast_channel_trace_disable(struct ast_channel *chan)
586 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
589 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
592 #endif /* CHANNEL_TRACE */
594 /*! \brief Checks to see if a channel is needing hang up */
595 int ast_check_hangup(struct ast_channel *chan)
597 if (ast_channel_softhangup_internal_flag(chan)) /* yes if soft hangup flag set */
599 if (ast_tvzero(*ast_channel_whentohangup(chan))) /* no if no hangup scheduled */
601 if (ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()) > 0) /* no if hangup time has not come yet. */
603 ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()));
604 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT); /* record event */
608 int ast_check_hangup_locked(struct ast_channel *chan)
611 ast_channel_lock(chan);
612 res = ast_check_hangup(chan);
613 ast_channel_unlock(chan);
617 void ast_channel_softhangup_withcause_locked(struct ast_channel *chan, int causecode)
619 ast_channel_lock(chan);
622 ast_debug(1, "Setting hangupcause of channel %s to %d (is %d now)\n",
623 ast_channel_name(chan), causecode, ast_channel_hangupcause(chan));
625 ast_channel_hangupcause_set(chan, causecode);
628 ast_softhangup_nolock(chan, AST_SOFTHANGUP_EXPLICIT);
630 ast_channel_unlock(chan);
633 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
635 struct ast_channel *chan = obj;
637 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
642 void ast_begin_shutdown(int hangup)
647 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
651 /*! \brief returns number of active/allocated channels */
652 int ast_active_channels(void)
654 return channels ? ao2_container_count(channels) : 0;
657 int ast_undestroyed_channels(void)
659 return ast_atomic_fetchadd_int(&chancount, 0);
662 /*! \brief Cancel a shutdown in progress */
663 void ast_cancel_shutdown(void)
668 /*! \brief Returns non-zero if Asterisk is being shut down */
669 int ast_shutting_down(void)
671 return shutting_down;
674 /*! \brief Set when to hangup channel */
675 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
677 if (ast_tvzero(offset)) {
678 ast_channel_whentohangup_set(chan, &offset);
680 struct timeval tv = ast_tvadd(offset, ast_tvnow());
681 ast_channel_whentohangup_set(chan, &tv);
683 ast_queue_frame(chan, &ast_null_frame);
687 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
689 struct timeval when = { offset, };
690 ast_channel_setwhentohangup_tv(chan, when);
693 /*! \brief Compare a offset with when to hangup channel */
694 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
696 struct timeval whentohangup;
698 if (ast_tvzero(*ast_channel_whentohangup(chan)))
699 return ast_tvzero(offset) ? 0 : -1;
701 if (ast_tvzero(offset))
704 whentohangup = ast_tvadd(offset, ast_tvnow());
706 return ast_tvdiff_ms(whentohangup, *ast_channel_whentohangup(chan));
709 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
711 struct timeval when = { offset, };
712 return ast_channel_cmpwhentohangup_tv(chan, when);
715 /*! \brief Register a new telephony channel in Asterisk */
716 int ast_channel_register(const struct ast_channel_tech *tech)
718 struct chanlist *chan;
720 AST_RWLIST_WRLOCK(&backends);
722 AST_RWLIST_TRAVERSE(&backends, chan, list) {
723 if (!strcasecmp(tech->type, chan->tech->type)) {
724 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
725 AST_RWLIST_UNLOCK(&backends);
730 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
731 AST_RWLIST_UNLOCK(&backends);
735 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
737 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
739 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
741 AST_RWLIST_UNLOCK(&backends);
746 /*! \brief Unregister channel driver */
747 void ast_channel_unregister(const struct ast_channel_tech *tech)
749 struct chanlist *chan;
751 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
753 AST_RWLIST_WRLOCK(&backends);
755 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
756 if (chan->tech == tech) {
757 AST_LIST_REMOVE_CURRENT(list);
759 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
763 AST_LIST_TRAVERSE_SAFE_END;
765 AST_RWLIST_UNLOCK(&backends);
768 /*! \brief Get handle to channel driver based on name */
769 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
771 struct chanlist *chanls;
772 const struct ast_channel_tech *ret = NULL;
774 AST_RWLIST_RDLOCK(&backends);
776 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
777 if (!strcasecmp(name, chanls->tech->type)) {
783 AST_RWLIST_UNLOCK(&backends);
788 /*! \brief Gives the string form of a given hangup cause */
789 const char *ast_cause2str(int cause)
793 for (x = 0; x < ARRAY_LEN(causes); x++) {
794 if (causes[x].cause == cause)
795 return causes[x].desc;
801 /*! \brief Convert a symbolic hangup cause to number */
802 int ast_str2cause(const char *name)
806 for (x = 0; x < ARRAY_LEN(causes); x++)
807 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
808 return causes[x].cause;
813 /*! \brief Gives the string form of a given channel state.
814 \note This function is not reentrant.
816 const char *ast_state2str(enum ast_channel_state state)
823 case AST_STATE_RESERVED:
825 case AST_STATE_OFFHOOK:
827 case AST_STATE_DIALING:
831 case AST_STATE_RINGING:
837 case AST_STATE_DIALING_OFFHOOK:
838 return "Dialing Offhook";
839 case AST_STATE_PRERING:
842 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
844 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
849 /*! \brief Gives the string form of a given transfer capability */
850 char *ast_transfercapability2str(int transfercapability)
852 switch (transfercapability) {
853 case AST_TRANS_CAP_SPEECH:
855 case AST_TRANS_CAP_DIGITAL:
857 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
858 return "RESTRICTED_DIGITAL";
859 case AST_TRANS_CAP_3_1K_AUDIO:
861 case AST_TRANS_CAP_DIGITAL_W_TONES:
862 return "DIGITAL_W_TONES";
863 case AST_TRANS_CAP_VIDEO:
870 /*! \brief Pick the best audio codec */
871 struct ast_format *ast_best_codec(struct ast_format_cap *cap, struct ast_format *result)
873 /* This just our opinion, expressed in code. We are asked to choose
874 the best codec to use, given no information */
875 static const enum ast_format_id prefs[] =
877 /*! Okay, ulaw is used by all telephony equipment, so start with it */
879 /*! Unless of course, you're a silly European, so then prefer ALAW */
885 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
887 /*! Okay, well, signed linear is easy to translate into other stuff */
888 AST_FORMAT_SLINEAR192,
889 AST_FORMAT_SLINEAR96,
890 AST_FORMAT_SLINEAR48,
891 AST_FORMAT_SLINEAR44,
892 AST_FORMAT_SLINEAR32,
893 AST_FORMAT_SLINEAR24,
894 AST_FORMAT_SLINEAR16,
895 AST_FORMAT_SLINEAR12,
897 /*! G.726 is standard ADPCM, in RFC3551 packing order */
899 /*! G.726 is standard ADPCM, in AAL2 packing order */
900 AST_FORMAT_G726_AAL2,
901 /*! ADPCM has great sound quality and is still pretty easy to translate */
903 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
904 translate and sounds pretty good */
906 /*! iLBC is not too bad */
908 /*! Speex is free, but computationally more expensive than GSM */
912 /*! SILK is pretty awesome. */
914 /*! CELT supports crazy high sample rates */
916 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
919 /*! G.729a is faster than 723 and slightly less expensive */
921 /*! Down to G.723.1 which is proprietary but at least designed for voice */
927 /* Find the first preferred codec in the format given */
928 for (x = 0; x < ARRAY_LEN(prefs); x++) {
929 if (ast_format_cap_best_byid(cap, prefs[x], result)) {
934 ast_format_clear(result);
935 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
940 static const struct ast_channel_tech null_tech = {
942 .description = "Null channel (should not see this)",
945 static void ast_channel_destructor(void *obj);
946 static void ast_dummy_channel_destructor(void *obj);
948 /*! \brief Create a new channel structure */
949 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
950 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
951 const char *acctcode, const char *exten, const char *context,
952 const char *linkedid, const int amaflag, const char *file, int line,
953 const char *function, const char *name_fmt, va_list ap)
955 struct ast_channel *tmp;
956 struct varshead *headp;
957 char *tech = "", *tech2 = NULL;
958 struct ast_format_cap *nativeformats;
959 struct ast_sched_context *schedctx;
960 struct ast_timer *timer;
963 /* If shutting down, don't allocate any new channels */
964 if (ast_shutting_down()) {
965 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
969 if (!(tmp = ast_channel_internal_alloc(ast_channel_destructor))) {
970 /* Channel structure allocation failure. */
973 if (!(nativeformats = ast_format_cap_alloc())) {
975 /* format capabilities structure allocation failure */
978 ast_channel_nativeformats_set(tmp, nativeformats);
981 * Init file descriptors to unopened state so
982 * the destructor can know not to close them.
984 ast_channel_timingfd_set(tmp, -1);
985 ast_channel_internal_alertpipe_clear(tmp);
986 ast_channel_internal_fd_clear_all(tmp);
989 ast_channel_epfd(tmp) = epoll_create(25);
992 if (!(schedctx = ast_sched_context_create())) {
993 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
994 return ast_channel_unref(tmp);
996 ast_channel_sched_set(tmp, schedctx);
998 ast_party_dialed_init(ast_channel_dialed(tmp));
999 ast_party_caller_init(ast_channel_caller(tmp));
1000 ast_party_connected_line_init(ast_channel_connected(tmp));
1001 ast_party_redirecting_init(ast_channel_redirecting(tmp));
1004 ast_channel_caller(tmp)->id.name.valid = 1;
1005 ast_channel_caller(tmp)->id.name.str = ast_strdup(cid_name);
1006 if (!ast_channel_caller(tmp)->id.name.str) {
1007 return ast_channel_unref(tmp);
1011 ast_channel_caller(tmp)->id.number.valid = 1;
1012 ast_channel_caller(tmp)->id.number.str = ast_strdup(cid_num);
1013 if (!ast_channel_caller(tmp)->id.number.str) {
1014 return ast_channel_unref(tmp);
1018 if ((timer = ast_timer_open())) {
1019 ast_channel_timer_set(tmp, timer);
1020 if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
1023 ast_channel_timingfd_set(tmp, ast_timer_fd(ast_channel_timer(tmp)));
1027 * This is the last place the channel constructor can fail.
1029 * The destructor takes advantage of this fact to ensure that the
1030 * AST_CEL_CHANNEL_END is not posted if we have not posted the
1031 * AST_CEL_CHANNEL_START yet.
1034 if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
1035 return ast_channel_unref(tmp);
1038 /* Always watch the alertpipe */
1039 ast_channel_set_fd(tmp, AST_ALERT_FD, ast_channel_internal_alert_readfd(tmp));
1040 /* And timing pipe */
1041 ast_channel_set_fd(tmp, AST_TIMING_FD, ast_channel_timingfd(tmp));
1044 ast_channel_state_set(tmp, state);
1046 ast_channel_streamid_set(tmp, -1);
1048 ast_channel_fin_set(tmp, global_fin);
1049 ast_channel_fout_set(tmp, global_fout);
1052 ast_channel_creationtime_set(tmp, &now);
1054 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1055 ast_channel_uniqueid_build(tmp, "%li.%d", (long) time(NULL),
1056 ast_atomic_fetchadd_int(&uniqueint, 1));
1058 ast_channel_uniqueid_build(tmp, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
1059 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1062 if (!ast_strlen_zero(linkedid)) {
1063 ast_channel_linkedid_set(tmp, linkedid);
1065 ast_channel_linkedid_set(tmp, ast_channel_uniqueid(tmp));
1068 if (!ast_strlen_zero(name_fmt)) {
1069 char *slash, *slash2;
1070 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1071 * And they all use slightly different formats for their name string.
1072 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1073 * This means, that the stringfields must have a routine that takes the va_lists directly, and
1074 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1075 * This new function was written so this can be accomplished.
1077 ast_channel_name_build_va(tmp, name_fmt, ap);
1078 tech = ast_strdupa(ast_channel_name(tmp));
1079 if ((slash = strchr(tech, '/'))) {
1080 if ((slash2 = strchr(slash + 1, '/'))) {
1088 * Start the string with '-' so it becomes an empty string
1089 * in the destructor.
1091 ast_channel_name_set(tmp, "-**Unknown**");
1094 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1096 /* These 4 variables need to be set up for the cdr_init() to work right */
1098 ast_channel_amaflags_set(tmp, amaflag);
1100 ast_channel_amaflags_set(tmp, ast_default_amaflags);
1103 if (!ast_strlen_zero(acctcode))
1104 ast_channel_accountcode_set(tmp, acctcode);
1106 ast_channel_accountcode_set(tmp, ast_default_accountcode);
1108 ast_channel_context_set(tmp, S_OR(context, "default"));
1109 ast_channel_exten_set(tmp, S_OR(exten, "s"));
1110 ast_channel_priority_set(tmp, 1);
1112 ast_channel_cdr_set(tmp, ast_cdr_alloc());
1113 ast_cdr_init(ast_channel_cdr(tmp), tmp);
1114 ast_cdr_start(ast_channel_cdr(tmp));
1116 ast_atomic_fetchadd_int(&chancount, +1);
1117 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1119 headp = ast_channel_varshead(tmp);
1120 AST_LIST_HEAD_INIT_NOLOCK(headp);
1122 ast_pbx_hangup_handler_init(tmp);
1123 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1125 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_autochans(tmp));
1127 ast_channel_language_set(tmp, defaultlanguage);
1129 ast_channel_tech_set(tmp, &null_tech);
1131 ao2_link(channels, tmp);
1134 * And now, since the channel structure is built, and has its name, let's
1135 * call the manager event generator with this Newchannel event. This is the
1136 * proper and correct place to make this call, but you sure do have to pass
1137 * a lot of data into this func to do it here!
1139 if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1141 <managerEventInstance>
1142 <synopsis>Raised when a new channel is created.</synopsis>
1144 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Newstate']/managerEventInstance/syntax/parameter[@name='ChannelState'])" />
1145 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Newstate']/managerEventInstance/syntax/parameter[@name='ChannelStateDesc'])" />
1147 </managerEventInstance>
1149 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1151 "ChannelState: %d\r\n"
1152 "ChannelStateDesc: %s\r\n"
1153 "CallerIDNum: %s\r\n"
1154 "CallerIDName: %s\r\n"
1155 "AccountCode: %s\r\n"
1159 ast_channel_name(tmp),
1161 ast_state2str(state),
1164 ast_channel_accountcode(tmp),
1167 ast_channel_uniqueid(tmp));
1170 ast_channel_internal_finalize(tmp);
1174 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1175 const char *cid_name, const char *acctcode,
1176 const char *exten, const char *context,
1177 const char *linkedid, const int amaflag,
1178 const char *file, int line, const char *function,
1179 const char *name_fmt, ...)
1182 struct ast_channel *result;
1184 va_start(ap, name_fmt);
1185 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1186 linkedid, amaflag, file, line, function, name_fmt, ap);
1192 /* only do the minimum amount of work needed here to make a channel
1193 * structure that can be used to expand channel vars */
1194 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1195 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1197 struct ast_channel *ast_dummy_channel_alloc(void)
1200 struct ast_channel *tmp;
1201 struct varshead *headp;
1203 if (!(tmp = ast_channel_internal_alloc(ast_dummy_channel_destructor))) {
1204 /* Dummy channel structure allocation failure. */
1208 ast_pbx_hangup_handler_init(tmp);
1209 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1211 headp = ast_channel_varshead(tmp);
1212 AST_LIST_HEAD_INIT_NOLOCK(headp);
1217 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1219 struct ast_frame *f;
1220 struct ast_frame *cur;
1221 unsigned int new_frames = 0;
1222 unsigned int new_voice_frames = 0;
1223 unsigned int queued_frames = 0;
1224 unsigned int queued_voice_frames = 0;
1225 AST_LIST_HEAD_NOLOCK(,ast_frame) frames;
1227 ast_channel_lock(chan);
1230 * Check the last frame on the queue if we are queuing the new
1233 cur = AST_LIST_LAST(ast_channel_readq(chan));
1234 if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1235 switch (cur->subclass.integer) {
1236 case AST_CONTROL_END_OF_Q:
1237 if (fin->frametype == AST_FRAME_CONTROL
1238 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1240 * Destroy the end-of-Q marker frame so we can queue the hangup
1241 * frame in its place.
1243 AST_LIST_REMOVE(ast_channel_readq(chan), cur, frame_list);
1247 * This has degenerated to a normal queue append anyway. Since
1248 * we just destroyed the last frame in the queue we must make
1249 * sure that "after" is NULL or bad things will happen.
1255 case AST_CONTROL_HANGUP:
1256 /* Don't queue anything. */
1257 ast_channel_unlock(chan);
1264 /* Build copies of all the new frames and count them */
1265 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1266 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1267 if (!(f = ast_frdup(cur))) {
1268 if (AST_LIST_FIRST(&frames)) {
1269 ast_frfree(AST_LIST_FIRST(&frames));
1271 ast_channel_unlock(chan);
1275 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1277 if (f->frametype == AST_FRAME_VOICE) {
1282 /* Count how many frames exist on the queue */
1283 AST_LIST_TRAVERSE(ast_channel_readq(chan), cur, frame_list) {
1285 if (cur->frametype == AST_FRAME_VOICE) {
1286 queued_voice_frames++;
1290 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1292 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1293 AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), cur, frame_list) {
1294 /* Save the most recent frame */
1295 if (!AST_LIST_NEXT(cur, frame_list)) {
1297 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1301 AST_LIST_REMOVE_CURRENT(frame_list);
1305 AST_LIST_TRAVERSE_SAFE_END;
1309 AST_LIST_INSERT_LIST_AFTER(ast_channel_readq(chan), &frames, after, frame_list);
1312 AST_LIST_APPEND_LIST(&frames, ast_channel_readq(chan), frame_list);
1313 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_readq(chan));
1315 AST_LIST_APPEND_LIST(ast_channel_readq(chan), &frames, frame_list);
1318 if (ast_channel_alert_writable(chan)) {
1319 if (ast_channel_alert_write(chan)) {
1320 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1321 ast_channel_name(chan), queued_frames, strerror(errno));
1323 } else if (ast_channel_timingfd(chan) > -1) {
1324 ast_timer_enable_continuous(ast_channel_timer(chan));
1325 } else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
1326 pthread_kill(ast_channel_blocker(chan), SIGURG);
1329 ast_channel_unlock(chan);
1334 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1336 return __ast_queue_frame(chan, fin, 0, NULL);
1339 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1341 return __ast_queue_frame(chan, fin, 1, NULL);
1344 /*! \brief Queue a hangup frame for channel */
1345 int ast_queue_hangup(struct ast_channel *chan)
1347 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1350 /* Yeah, let's not change a lock-critical value without locking */
1351 ast_channel_lock(chan);
1352 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1354 <managerEventInstance>
1355 <synopsis>Raised when a hangup is requested with no set cause.</synopsis>
1356 </managerEventInstance>
1358 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1361 ast_channel_name(chan),
1362 ast_channel_uniqueid(chan));
1364 res = ast_queue_frame(chan, &f);
1365 ast_channel_unlock(chan);
1369 /*! \brief Queue a hangup frame for channel */
1370 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1372 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1376 f.data.uint32 = cause;
1379 /* Yeah, let's not change a lock-critical value without locking */
1380 ast_channel_lock(chan);
1381 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1383 f.data.uint32 = ast_channel_hangupcause(chan);
1386 <managerEventInstance>
1387 <synopsis>Raised when a hangup is requested with a specific cause code.</synopsis>
1389 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Hangup']/managerEventInstance/syntax/parameter[@name='Cause'])" />
1391 </managerEventInstance>
1393 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1397 ast_channel_name(chan),
1398 ast_channel_uniqueid(chan),
1401 res = ast_queue_frame(chan, &f);
1402 ast_channel_unlock(chan);
1406 /*! \brief Queue a control frame */
1407 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1409 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1410 return ast_queue_frame(chan, &f);
1413 /*! \brief Queue a control frame with payload */
1414 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1415 const void *data, size_t datalen)
1417 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1418 return ast_queue_frame(chan, &f);
1421 /*! \brief Set defer DTMF flag on channel */
1422 int ast_channel_defer_dtmf(struct ast_channel *chan)
1427 pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1428 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1433 /*! \brief Unset defer DTMF flag on channel */
1434 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1437 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1440 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1441 void *data, int ao2_flags)
1443 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1446 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1448 struct ast_channel *chan = obj;
1449 const char *name = arg;
1450 size_t name_len = *(size_t *) data;
1451 int ret = CMP_MATCH;
1453 if (ast_strlen_zero(name)) {
1454 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1458 ast_channel_lock(chan);
1459 if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1460 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1461 ret = 0; /* name match failed, keep looking */
1463 ast_channel_unlock(chan);
1468 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1470 struct ast_channel *chan = obj;
1471 char *context = arg;
1473 int ret = CMP_MATCH;
1475 if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1476 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1480 ast_channel_lock(chan);
1481 if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1482 ret = 0; /* Context match failed, continue */
1483 } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1484 ret = 0; /* Extension match failed, continue */
1486 ast_channel_unlock(chan);
1491 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1493 struct ast_channel *chan = obj;
1494 char *uniqueid = arg;
1495 size_t id_len = *(size_t *) data;
1496 int ret = CMP_MATCH;
1498 if (ast_strlen_zero(uniqueid)) {
1499 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1503 ast_channel_lock(chan);
1504 if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1505 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1506 ret = 0; /* uniqueid match failed, keep looking */
1508 ast_channel_unlock(chan);
1513 struct ast_channel_iterator {
1514 /* storage for non-dynamically allocated iterator */
1515 struct ao2_iterator simple_iterator;
1516 /* pointer to the actual iterator (simple_iterator or a dynamically
1517 * allocated iterator)
1519 struct ao2_iterator *active_iterator;
1522 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1524 ao2_iterator_destroy(i->active_iterator);
1530 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1532 struct ast_channel_iterator *i;
1533 char *l_exten = (char *) exten;
1534 char *l_context = (char *) context;
1536 if (!(i = ast_calloc(1, sizeof(*i)))) {
1540 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1541 l_context, l_exten, OBJ_MULTIPLE);
1542 if (!i->active_iterator) {
1550 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1552 struct ast_channel_iterator *i;
1553 char *l_name = (char *) name;
1555 if (!(i = ast_calloc(1, sizeof(*i)))) {
1559 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1561 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1562 if (!i->active_iterator) {
1570 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1572 struct ast_channel_iterator *i;
1574 if (!(i = ast_calloc(1, sizeof(*i)))) {
1578 i->simple_iterator = ao2_iterator_init(channels, 0);
1579 i->active_iterator = &i->simple_iterator;
1584 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1586 return ao2_iterator_next(i->active_iterator);
1589 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1590 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1592 ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1596 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1598 struct ast_channel *chan;
1599 char *l_name = (char *) name;
1601 chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1602 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1607 if (ast_strlen_zero(l_name)) {
1608 /* We didn't have a name to search for so quit. */
1612 /* Now try a search for uniqueid. */
1613 return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1616 struct ast_channel *ast_channel_get_by_name(const char *name)
1618 return ast_channel_get_by_name_prefix(name, 0);
1621 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1623 char *l_exten = (char *) exten;
1624 char *l_context = (char *) context;
1626 return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1629 int ast_is_deferrable_frame(const struct ast_frame *frame)
1631 /* Do not add a default entry in this switch statement. Each new
1632 * frame type should be addressed directly as to whether it should
1633 * be queued up or not.
1635 switch (frame->frametype) {
1636 case AST_FRAME_CONTROL:
1637 case AST_FRAME_TEXT:
1638 case AST_FRAME_IMAGE:
1639 case AST_FRAME_HTML:
1642 case AST_FRAME_DTMF_END:
1643 case AST_FRAME_DTMF_BEGIN:
1644 case AST_FRAME_VOICE:
1645 case AST_FRAME_VIDEO:
1646 case AST_FRAME_NULL:
1649 case AST_FRAME_MODEM:
1655 /*! \brief Wait, look for hangups and condition arg */
1656 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1658 struct ast_frame *f;
1659 struct ast_silence_generator *silgen = NULL;
1661 AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1663 AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1665 /* If no other generator is present, start silencegen while waiting */
1666 if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1667 silgen = ast_channel_start_silence_generator(chan);
1671 struct ast_frame *dup_f = NULL;
1672 if (cond && ((*cond)(data) == 0)) {
1675 ms = ast_waitfor(chan, ms);
1687 if (!ast_is_deferrable_frame(f)) {
1692 if ((dup_f = ast_frisolate(f))) {
1696 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1701 /* stop silgen if present */
1703 ast_channel_stop_silence_generator(chan, silgen);
1706 /* We need to free all the deferred frames, but we only need to
1707 * queue the deferred frames if there was no error and no
1708 * hangup was received
1710 ast_channel_lock(chan);
1711 while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1713 ast_queue_frame_head(chan, f);
1717 ast_channel_unlock(chan);
1722 /*! \brief Wait, look for hangups */
1723 int ast_safe_sleep(struct ast_channel *chan, int ms)
1725 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1728 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1730 /* Safe, even if already unlinked. */
1731 ao2_unlink(channels, chan);
1732 return ast_channel_unref(chan);
1735 void ast_party_name_init(struct ast_party_name *init)
1738 init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1739 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1743 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1746 /* Don't copy to self */
1750 ast_free(dest->str);
1751 dest->str = ast_strdup(src->str);
1752 dest->char_set = src->char_set;
1753 dest->presentation = src->presentation;
1754 dest->valid = src->valid;
1757 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1760 init->char_set = guide->char_set;
1761 init->presentation = guide->presentation;
1762 init->valid = guide->valid;
1765 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1768 /* Don't set to self */
1772 if (src->str && src->str != dest->str) {
1773 ast_free(dest->str);
1774 dest->str = ast_strdup(src->str);
1777 dest->char_set = src->char_set;
1778 dest->presentation = src->presentation;
1779 dest->valid = src->valid;
1782 void ast_party_name_free(struct ast_party_name *doomed)
1784 ast_free(doomed->str);
1788 void ast_party_number_init(struct ast_party_number *init)
1791 init->plan = 0;/* Unknown */
1792 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1796 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1799 /* Don't copy to self */
1803 ast_free(dest->str);
1804 dest->str = ast_strdup(src->str);
1805 dest->plan = src->plan;
1806 dest->presentation = src->presentation;
1807 dest->valid = src->valid;
1810 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1813 init->plan = guide->plan;
1814 init->presentation = guide->presentation;
1815 init->valid = guide->valid;
1818 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1821 /* Don't set to self */
1825 if (src->str && src->str != dest->str) {
1826 ast_free(dest->str);
1827 dest->str = ast_strdup(src->str);
1830 dest->plan = src->plan;
1831 dest->presentation = src->presentation;
1832 dest->valid = src->valid;
1835 void ast_party_number_free(struct ast_party_number *doomed)
1837 ast_free(doomed->str);
1841 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1845 init->odd_even_indicator = 0;
1849 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1852 /* Don't copy to self */
1856 ast_free(dest->str);
1857 dest->str = ast_strdup(src->str);
1858 dest->type = src->type;
1859 dest->odd_even_indicator = src->odd_even_indicator;
1860 dest->valid = src->valid;
1863 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1866 init->type = guide->type;
1867 init->odd_even_indicator = guide->odd_even_indicator;
1868 init->valid = guide->valid;
1871 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1874 /* Don't set to self */
1878 if (src->str && src->str != dest->str) {
1879 ast_free(dest->str);
1880 dest->str = ast_strdup(src->str);
1883 dest->type = src->type;
1884 dest->odd_even_indicator = src->odd_even_indicator;
1885 dest->valid = src->valid;
1888 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1890 ast_free(doomed->str);
1894 void ast_party_id_init(struct ast_party_id *init)
1896 ast_party_name_init(&init->name);
1897 ast_party_number_init(&init->number);
1898 ast_party_subaddress_init(&init->subaddress);
1902 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1905 /* Don't copy to self */
1909 ast_party_name_copy(&dest->name, &src->name);
1910 ast_party_number_copy(&dest->number, &src->number);
1911 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1913 ast_free(dest->tag);
1914 dest->tag = ast_strdup(src->tag);
1917 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1919 ast_party_name_set_init(&init->name, &guide->name);
1920 ast_party_number_set_init(&init->number, &guide->number);
1921 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1925 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1928 /* Don't set to self */
1932 if (!update || update->name) {
1933 ast_party_name_set(&dest->name, &src->name);
1935 if (!update || update->number) {
1936 ast_party_number_set(&dest->number, &src->number);
1938 if (!update || update->subaddress) {
1939 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1942 if (src->tag && src->tag != dest->tag) {
1943 ast_free(dest->tag);
1944 dest->tag = ast_strdup(src->tag);
1948 void ast_party_id_free(struct ast_party_id *doomed)
1950 ast_party_name_free(&doomed->name);
1951 ast_party_number_free(&doomed->number);
1952 ast_party_subaddress_free(&doomed->subaddress);
1954 ast_free(doomed->tag);
1958 int ast_party_id_presentation(const struct ast_party_id *id)
1960 int number_priority;
1962 int number_screening;
1966 /* Determine name presentation priority. */
1967 if (!id->name.valid) {
1968 name_value = AST_PRES_UNAVAILABLE;
1971 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1972 switch (name_value) {
1973 case AST_PRES_RESTRICTED:
1976 case AST_PRES_ALLOWED:
1979 case AST_PRES_UNAVAILABLE:
1983 name_value = AST_PRES_UNAVAILABLE;
1989 /* Determine number presentation priority. */
1990 if (!id->number.valid) {
1991 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1992 number_value = AST_PRES_UNAVAILABLE;
1993 number_priority = 3;
1995 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1996 number_value = id->number.presentation & AST_PRES_RESTRICTION;
1997 switch (number_value) {
1998 case AST_PRES_RESTRICTED:
1999 number_priority = 0;
2001 case AST_PRES_ALLOWED:
2002 number_priority = 1;
2004 case AST_PRES_UNAVAILABLE:
2005 number_priority = 2;
2008 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2009 number_value = AST_PRES_UNAVAILABLE;
2010 number_priority = 3;
2015 /* Select the wining presentation value. */
2016 if (name_priority < number_priority) {
2017 number_value = name_value;
2019 if (number_value == AST_PRES_UNAVAILABLE) {
2020 return AST_PRES_NUMBER_NOT_AVAILABLE;
2023 return number_value | number_screening;
2026 void ast_party_dialed_init(struct ast_party_dialed *init)
2028 init->number.str = NULL;
2029 init->number.plan = 0;/* Unknown */
2030 ast_party_subaddress_init(&init->subaddress);
2031 init->transit_network_select = 0;
2034 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2037 /* Don't copy to self */
2041 ast_free(dest->number.str);
2042 dest->number.str = ast_strdup(src->number.str);
2043 dest->number.plan = src->number.plan;
2044 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2045 dest->transit_network_select = src->transit_network_select;
2048 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2050 init->number.str = NULL;
2051 init->number.plan = guide->number.plan;
2052 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2053 init->transit_network_select = guide->transit_network_select;
2056 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2058 if (src->number.str && src->number.str != dest->number.str) {
2059 ast_free(dest->number.str);
2060 dest->number.str = ast_strdup(src->number.str);
2062 dest->number.plan = src->number.plan;
2064 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2066 dest->transit_network_select = src->transit_network_select;
2069 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2071 ast_free(doomed->number.str);
2072 doomed->number.str = NULL;
2073 ast_party_subaddress_free(&doomed->subaddress);
2076 void ast_party_caller_init(struct ast_party_caller *init)
2078 ast_party_id_init(&init->id);
2079 ast_party_id_init(&init->ani);
2083 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2086 /* Don't copy to self */
2090 ast_party_id_copy(&dest->id, &src->id);
2091 ast_party_id_copy(&dest->ani, &src->ani);
2092 dest->ani2 = src->ani2;
2095 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2097 ast_party_id_set_init(&init->id, &guide->id);
2098 ast_party_id_set_init(&init->ani, &guide->ani);
2099 init->ani2 = guide->ani2;
2102 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2104 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2105 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2106 dest->ani2 = src->ani2;
2109 void ast_party_caller_free(struct ast_party_caller *doomed)
2111 ast_party_id_free(&doomed->id);
2112 ast_party_id_free(&doomed->ani);
2115 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2117 ast_party_id_init(&init->id);
2118 ast_party_id_init(&init->ani);
2120 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2123 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2126 /* Don't copy to self */
2130 ast_party_id_copy(&dest->id, &src->id);
2131 ast_party_id_copy(&dest->ani, &src->ani);
2132 dest->ani2 = src->ani2;
2133 dest->source = src->source;
2136 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2138 ast_party_id_set_init(&init->id, &guide->id);
2139 ast_party_id_set_init(&init->ani, &guide->ani);
2140 init->ani2 = guide->ani2;
2141 init->source = guide->source;
2144 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)
2146 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2147 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2148 dest->ani2 = src->ani2;
2149 dest->source = src->source;
2152 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2154 connected->id = caller->id;
2155 connected->ani = caller->ani;
2156 connected->ani2 = caller->ani2;
2157 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2160 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2162 ast_party_id_free(&doomed->id);
2163 ast_party_id_free(&doomed->ani);
2166 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2168 ast_party_id_init(&init->orig);
2169 ast_party_id_init(&init->from);
2170 ast_party_id_init(&init->to);
2172 init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2173 init->orig_reason = AST_REDIRECTING_REASON_UNKNOWN;
2176 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2179 /* Don't copy to self */
2183 ast_party_id_copy(&dest->orig, &src->orig);
2184 ast_party_id_copy(&dest->from, &src->from);
2185 ast_party_id_copy(&dest->to, &src->to);
2186 dest->count = src->count;
2187 dest->reason = src->reason;
2188 dest->orig_reason = src->orig_reason;
2191 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2193 ast_party_id_set_init(&init->orig, &guide->orig);
2194 ast_party_id_set_init(&init->from, &guide->from);
2195 ast_party_id_set_init(&init->to, &guide->to);
2196 init->count = guide->count;
2197 init->reason = guide->reason;
2198 init->orig_reason = guide->orig_reason;
2201 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2203 ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2204 ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2205 ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2206 dest->count = src->count;
2207 dest->reason = src->reason;
2208 dest->orig_reason = src->orig_reason;
2211 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2213 ast_party_id_free(&doomed->orig);
2214 ast_party_id_free(&doomed->from);
2215 ast_party_id_free(&doomed->to);
2218 /*! \brief Free a channel structure */
2219 static void ast_channel_destructor(void *obj)
2221 struct ast_channel *chan = obj;
2225 struct ast_var_t *vardata;
2226 struct ast_frame *f;
2227 struct varshead *headp;
2228 struct ast_datastore *datastore;
2229 char device_name[AST_CHANNEL_NAME];
2230 struct ast_callid *callid;
2232 if (ast_channel_internal_is_finalized(chan)) {
2233 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2234 ast_cel_check_retire_linkedid(chan);
2237 ast_pbx_hangup_handler_destroy(chan);
2239 ast_channel_lock(chan);
2241 /* Get rid of each of the data stores on the channel */
2242 while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2243 /* Free the data store */
2244 ast_datastore_free(datastore);
2246 /* While the channel is locked, take the reference to its callid while we tear down the call. */
2247 callid = ast_channel_callid(chan);
2248 ast_channel_callid_cleanup(chan);
2250 ast_channel_unlock(chan);
2252 /* Lock and unlock the channel just to be sure nobody has it locked still
2253 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2254 ast_channel_lock(chan);
2255 ast_channel_unlock(chan);
2257 if (ast_channel_tech_pvt(chan)) {
2258 ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2259 ast_free(ast_channel_tech_pvt(chan));
2262 if (ast_channel_sched(chan)) {
2263 ast_sched_context_destroy(ast_channel_sched(chan));
2266 if (ast_channel_internal_is_finalized(chan)) {
2269 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2270 if ((dashptr = strrchr(device_name, '-'))) {
2274 device_name[0] = '\0';
2277 /* Stop monitoring */
2278 if (ast_channel_monitor(chan))
2279 ast_channel_monitor(chan)->stop( chan, 0 );
2281 /* If there is native format music-on-hold state, free it */
2282 if (ast_channel_music_state(chan))
2283 ast_moh_cleanup(chan);
2285 /* Free translators */
2286 if (ast_channel_readtrans(chan))
2287 ast_translator_free_path(ast_channel_readtrans(chan));
2288 if (ast_channel_writetrans(chan))
2289 ast_translator_free_path(ast_channel_writetrans(chan));
2290 if (ast_channel_pbx(chan))
2291 ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2293 ast_party_dialed_free(ast_channel_dialed(chan));
2294 ast_party_caller_free(ast_channel_caller(chan));
2295 ast_party_connected_line_free(ast_channel_connected(chan));
2296 ast_party_redirecting_free(ast_channel_redirecting(chan));
2298 /* Close pipes if appropriate */
2299 ast_channel_internal_alertpipe_close(chan);
2300 if (ast_channel_timer(chan)) {
2301 ast_timer_close(ast_channel_timer(chan));
2304 for (i = 0; i < AST_MAX_FDS; i++) {
2305 if (ast_channel_internal_epfd_data(chan, i)) {
2306 ast_free(ast_channel_internal_epfd_data(chan, i));
2309 close(ast_channel_epfd(chan));
2311 while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2314 /* loop over the variables list, freeing all data and deleting list items */
2315 /* no need to lock the list, as the channel is already locked */
2316 headp = ast_channel_varshead(chan);
2317 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2318 ast_var_delete(vardata);
2320 ast_app_group_discard(chan);
2322 /* Destroy the jitterbuffer */
2323 ast_jb_destroy(chan);
2325 if (ast_channel_cdr(chan)) {
2326 ast_cdr_discard(ast_channel_cdr(chan));
2327 ast_channel_cdr_set(chan, NULL);
2330 if (ast_channel_zone(chan)) {
2331 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2334 ast_channel_internal_cleanup(chan);
2336 if (device_name[0]) {
2338 * We have a device name to notify of a new state.
2340 * Queue an unknown state, because, while we know that this particular
2341 * instance is dead, we don't know the state of all other possible
2344 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2347 ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2349 ast_callid_unref(callid);
2352 ast_channel_named_callgroups_set(chan, NULL);
2353 ast_channel_named_pickupgroups_set(chan, NULL);
2355 ast_atomic_fetchadd_int(&chancount, -1);
2358 /*! \brief Free a dummy channel structure */
2359 static void ast_dummy_channel_destructor(void *obj)
2361 struct ast_channel *chan = obj;
2362 struct ast_datastore *datastore;
2363 struct ast_var_t *vardata;
2364 struct varshead *headp;
2366 ast_pbx_hangup_handler_destroy(chan);
2368 /* Get rid of each of the data stores on the channel */
2369 while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
2370 /* Free the data store */
2371 ast_datastore_free(datastore);
2374 ast_party_dialed_free(ast_channel_dialed(chan));
2375 ast_party_caller_free(ast_channel_caller(chan));
2376 ast_party_connected_line_free(ast_channel_connected(chan));
2377 ast_party_redirecting_free(ast_channel_redirecting(chan));
2379 /* loop over the variables list, freeing all data and deleting list items */
2380 /* no need to lock the list, as the channel is already locked */
2381 headp = ast_channel_varshead(chan);
2382 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2383 ast_var_delete(vardata);
2385 if (ast_channel_cdr(chan)) {
2386 ast_cdr_discard(ast_channel_cdr(chan));
2387 ast_channel_cdr_set(chan, NULL);
2390 ast_channel_internal_cleanup(chan);
2393 struct ast_datastore *ast_channel_datastore_alloc(const const struct ast_datastore_info *info, const char *uid)
2395 return ast_datastore_alloc(info, uid);
2398 int ast_channel_datastore_free(struct ast_datastore *datastore)
2400 return ast_datastore_free(datastore);
2403 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2405 struct ast_datastore *datastore = NULL, *datastore2;
2407 AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2408 if (datastore->inheritance > 0) {
2409 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2411 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2412 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2413 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2420 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2424 AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2429 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2431 return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2434 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const const struct ast_datastore_info *info, const char *uid)
2436 struct ast_datastore *datastore = NULL;
2441 AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2442 if (datastore->info != info) {
2447 /* matched by type only */
2451 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2452 /* Matched by type AND uid */
2460 /*! Set the file descriptor on the channel */
2461 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2464 struct epoll_event ev;
2465 struct ast_epoll_data *aed = NULL;
2467 if (ast_channel_fd_isset(chan, which)) {
2468 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2469 aed = ast_channel_internal_epfd_data(chan, which);
2472 /* If this new fd is valid, add it to the epoll */
2474 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2477 ast_channel_internal_epfd_data_set(chan, which, aed);
2481 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2483 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2485 /* We don't have to keep around this epoll data structure now */
2487 ast_channel_epfd_data_set(chan, which, NULL);
2490 ast_channel_internal_fd_set(chan, which, fd);
2494 /*! Add a channel to an optimized waitfor */
2495 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2498 struct epoll_event ev;
2501 if (ast_channel_epfd(chan0) == -1)
2504 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2505 for (i = 0; i < AST_MAX_FDS; i++) {
2506 if (!ast_channel_fd_isset(chan1, i)) {
2509 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2510 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2511 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2518 /*! Delete a channel from an optimized waitfor */
2519 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2522 struct epoll_event ev;
2525 if (ast_channel_epfd(chan0) == -1)
2528 for (i = 0; i < AST_MAX_FDS; i++) {
2529 if (!ast_channel_fd_isset(chan1, i)) {
2532 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2539 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2541 ast_channel_lock(chan);
2543 ast_channel_softhangup_internal_flag_clear(chan, flag);
2545 if (!ast_channel_softhangup_internal_flag(chan)) {
2546 struct ast_frame *fr;
2548 /* If we have completely cleared the softhangup flag,
2549 * then we need to fully abort the hangup process. This requires
2550 * pulling the END_OF_Q frame out of the channel frame queue if it
2551 * still happens to be there. */
2553 fr = AST_LIST_LAST(ast_channel_readq(chan));
2554 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2555 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2556 AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2561 ast_channel_unlock(chan);
2564 /*! \brief Softly hangup a channel, don't lock */
2565 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2567 ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2568 /* Inform channel driver that we need to be hung up, if it cares */
2569 ast_channel_softhangup_internal_flag_add(chan, cause);
2570 ast_queue_frame(chan, &ast_null_frame);
2571 /* Interrupt any poll call or such */
2572 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2573 pthread_kill(ast_channel_blocker(chan), SIGURG);
2577 /*! \brief Softly hangup a channel, lock */
2578 int ast_softhangup(struct ast_channel *chan, int cause)
2582 ast_channel_lock(chan);
2583 res = ast_softhangup_nolock(chan, cause);
2585 <managerEventInstance>
2586 <synopsis>Raised when a soft hangup is requested with a specific cause code.</synopsis>
2588 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Hangup']/managerEventInstance/syntax/parameter[@name='Cause'])" />
2590 </managerEventInstance>
2592 manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2596 ast_channel_name(chan),
2597 ast_channel_uniqueid(chan),
2599 ast_channel_unlock(chan);
2604 static void free_translation(struct ast_channel *clonechan)
2606 if (ast_channel_writetrans(clonechan))
2607 ast_translator_free_path(ast_channel_writetrans(clonechan));
2608 if (ast_channel_readtrans(clonechan))
2609 ast_translator_free_path(ast_channel_readtrans(clonechan));
2610 ast_channel_writetrans_set(clonechan, NULL);
2611 ast_channel_readtrans_set(clonechan, NULL);
2612 if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2613 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2614 ast_format_clear(ast_channel_rawreadformat(clonechan));
2616 struct ast_format tmpfmt;
2617 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2618 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2619 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2623 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2625 struct ast_channel *bridge;
2627 ast_channel_lock(chan);
2628 if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2629 ast_channel_hangupsource_set(chan, source);
2631 bridge = ast_bridged_channel(chan);
2633 ast_channel_ref(bridge);
2635 ast_channel_unlock(chan);
2638 ast_channel_lock(bridge);
2639 if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
2640 ast_channel_hangupsource_set(bridge, source);
2642 ast_channel_unlock(bridge);
2643 ast_channel_unref(bridge);
2647 static void destroy_hooks(struct ast_channel *chan)
2649 if (ast_channel_audiohooks(chan)) {
2650 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2651 ast_channel_audiohooks_set(chan, NULL);
2654 ast_framehook_list_destroy(chan);
2657 /*! \brief Hangup a channel */
2658 int ast_hangup(struct ast_channel *chan)
2660 char extra_str[64]; /* used for cel logging below */
2662 ast_autoservice_stop(chan);
2664 ast_channel_lock(chan);
2667 * Do the masquerade if someone is setup to masquerade into us.
2669 * NOTE: We must hold the channel lock after testing for a
2670 * pending masquerade and setting the channel as a zombie to
2671 * prevent __ast_channel_masquerade() from setting up a
2672 * masquerade with a dead channel.
2674 while (ast_channel_masq(chan)) {
2675 ast_channel_unlock(chan);
2676 ast_do_masquerade(chan);
2677 ast_channel_lock(chan);
2680 if (ast_channel_masqr(chan)) {
2682 * This channel is one which will be masqueraded into something.
2683 * Mark it as a zombie already so ast_do_masquerade() will know
2686 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2687 destroy_hooks(chan);
2688 ast_channel_unlock(chan);
2692 /* Mark as a zombie so a masquerade cannot be setup on this channel. */
2693 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2695 ast_channel_unlock(chan);
2698 * XXX if running the hangup handlers here causes problems
2699 * because the handlers take too long to execute, we could move
2700 * the meat of this function into another thread. A thread
2701 * where channels go to die.
2703 * If this is done, ast_autoservice_chan_hangup_peer() will no
2706 ast_pbx_hangup_handler_run(chan);
2707 ao2_unlink(channels, chan);
2708 ast_channel_lock(chan);
2710 destroy_hooks(chan);
2712 free_translation(chan);
2713 /* Close audio stream */
2714 if (ast_channel_stream(chan)) {
2715 ast_closestream(ast_channel_stream(chan));
2716 ast_channel_stream_set(chan, NULL);
2718 /* Close video stream */
2719 if (ast_channel_vstream(chan)) {
2720 ast_closestream(ast_channel_vstream(chan));
2721 ast_channel_vstream_set(chan, NULL);
2723 if (ast_channel_sched(chan)) {
2724 ast_sched_context_destroy(ast_channel_sched(chan));
2725 ast_channel_sched_set(chan, NULL);
2728 if (ast_channel_generatordata(chan)) { /* Clear any tone stuff remaining */
2729 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2730 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2733 ast_channel_generatordata_set(chan, NULL);
2734 ast_channel_generator_set(chan, NULL);
2736 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"), ""));
2737 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2739 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2740 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2741 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2742 (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2743 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2746 ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2747 if (ast_channel_tech(chan)->hangup) {
2748 ast_channel_tech(chan)->hangup(chan);
2751 ast_channel_unlock(chan);
2755 <managerEventInstance>
2756 <synopsis>Raised when a channel is hung up.</synopsis>
2758 <parameter name="Cause">
2759 <para>A numeric cause code for why the channel was hung up.</para>
2761 <parameter name="Cause-txt">
2762 <para>A description of why the channel was hung up.</para>
2765 </managerEventInstance>
2767 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2770 "CallerIDNum: %s\r\n"
2771 "CallerIDName: %s\r\n"
2772 "ConnectedLineNum: %s\r\n"
2773 "ConnectedLineName: %s\r\n"
2774 "AccountCode: %s\r\n"
2776 "Cause-txt: %s\r\n",
2777 ast_channel_name(chan),
2778 ast_channel_uniqueid(chan),
2779 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
2780 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
2781 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
2782 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
2783 ast_channel_accountcode(chan),
2784 ast_channel_hangupcause(chan),
2785 ast_cause2str(ast_channel_hangupcause(chan))
2788 if (ast_channel_cdr(chan) && !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_BRIDGED) &&
2789 !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_POST_DISABLED) &&
2790 (ast_channel_cdr(chan)->disposition != AST_CDR_NULL || ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_DIALED))) {
2791 ast_channel_lock(chan);
2792 ast_cdr_end(ast_channel_cdr(chan));
2793 ast_cdr_detach(ast_channel_cdr(chan));
2794 ast_channel_cdr_set(chan, NULL);
2795 ast_channel_unlock(chan);
2798 ast_channel_unref(chan);
2803 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2807 ast_channel_lock(chan);
2809 /* You can't answer an outbound call */
2810 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2811 ast_channel_unlock(chan);
2815 /* Stop if we're a zombie or need a soft hangup */
2816 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2817 ast_channel_unlock(chan);
2821 ast_channel_unlock(chan);
2823 switch (ast_channel_state(chan)) {
2824 case AST_STATE_RINGING:
2825 case AST_STATE_RING:
2826 ast_channel_lock(chan);
2827 if (ast_channel_tech(chan)->answer) {
2828 res = ast_channel_tech(chan)->answer(chan);
2830 ast_setstate(chan, AST_STATE_UP);
2832 ast_cdr_answer(ast_channel_cdr(chan));
2834 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2835 ast_channel_unlock(chan);
2838 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2839 /* Calling ast_cdr_answer when it it has previously been called
2840 * is essentially a no-op, so it is safe.
2843 ast_cdr_answer(ast_channel_cdr(chan));
2850 ast_indicate(chan, -1);
2855 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2858 enum ast_channel_state old_state;
2860 old_state = ast_channel_state(chan);
2861 if ((res = ast_raw_answer(chan, cdr_answer))) {
2865 switch (old_state) {
2866 case AST_STATE_RINGING:
2867 case AST_STATE_RING:
2868 /* wait for media to start flowing, but don't wait any longer
2869 * than 'delay' or 500 milliseconds, whichever is longer
2872 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2873 struct ast_frame *cur, *new;
2874 int ms = MAX(delay, 500);
2875 unsigned int done = 0;
2877 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2880 ms = ast_waitfor(chan, ms);
2882 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2887 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));
2890 cur = ast_read(chan);
2891 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2892 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2897 ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2901 if ((new = ast_frisolate(cur)) != cur) {
2905 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2907 /* if a specific delay period was requested, continue
2908 * until that delay has passed. don't stop just because
2909 * incoming media has arrived.
2915 switch (new->frametype) {
2916 /* all of these frametypes qualify as 'media' */
2917 case AST_FRAME_VOICE:
2918 case AST_FRAME_VIDEO:
2919 case AST_FRAME_TEXT:
2920 case AST_FRAME_DTMF_BEGIN:
2921 case AST_FRAME_DTMF_END:
2922 case AST_FRAME_IMAGE:
2923 case AST_FRAME_HTML:
2924 case AST_FRAME_MODEM:
2927 case AST_FRAME_CONTROL:
2929 case AST_FRAME_NULL:
2940 ast_channel_lock(chan);
2941 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2942 ast_queue_frame_head(chan, cur);
2945 ast_channel_unlock(chan);
2956 int ast_answer(struct ast_channel *chan)
2958 return __ast_answer(chan, 0, 1);
2961 void ast_deactivate_generator(struct ast_channel *chan)
2963 ast_channel_lock(chan);
2964 if (ast_channel_generatordata(chan)) {
2965 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2966 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2968 ast_channel_generatordata_set(chan, NULL);
2969 ast_channel_generator_set(chan, NULL);
2970 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2971 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
2972 ast_settimeout(chan, 0, NULL, NULL);
2974 ast_channel_unlock(chan);
2977 static void generator_write_format_change(struct ast_channel *chan)
2979 ast_channel_lock(chan);
2980 if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
2981 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
2983 ast_channel_unlock(chan);
2986 static int generator_force(const void *data)
2988 /* Called if generator doesn't have data */
2991 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2992 struct ast_channel *chan = (struct ast_channel *)data;
2994 ast_channel_lock(chan);
2995 tmp = ast_channel_generatordata(chan);
2996 ast_channel_generatordata_set(chan, NULL);
2997 if (ast_channel_generator(chan))
2998 generate = ast_channel_generator(chan)->generate;
2999 ast_channel_unlock(chan);
3001 if (!tmp || !generate)
3004 res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
3006 ast_channel_generatordata_set(chan, tmp);
3009 ast_debug(1, "Auto-deactivating generator\n");
3010 ast_deactivate_generator(chan);
3016 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
3019 void *generatordata = NULL;
3021 ast_channel_lock(chan);
3022 if (ast_channel_generatordata(chan)) {
3023 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3024 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3027 if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
3030 ast_channel_generatordata_set(chan, generatordata);
3032 ast_settimeout(chan, 50, generator_force, chan);
3033 ast_channel_generator_set(chan, gen);
3035 ast_channel_unlock(chan);
3042 /*! \brief Wait for x amount of time on a file descriptor to have input. */
3043 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
3046 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
3050 /*! \brief Wait for x amount of time on a file descriptor to have input. */
3052 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
3053 int *exception, int *outfd, int *ms)
3055 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3056 int *exception, int *outfd, int *ms)
3059 struct timeval start = { 0 , 0 };
3060 struct pollfd *pfds = NULL;
3065 struct timeval now = { 0, 0 };
3066 struct timeval whentohangup = { 0, 0 }, diff;
3067 struct ast_channel *winner = NULL;
3080 if ((sz = n * AST_MAX_FDS + nfds)) {
3081 pfds = ast_alloca(sizeof(*pfds) * sz);
3082 fdmap = ast_alloca(sizeof(*fdmap) * sz);
3084 /* nothing to allocate and no FDs to check */
3088 /* Perform any pending masquerades */
3089 for (x = 0; x < n; x++) {
3090 while (ast_channel_masq(c[x])) {
3091 ast_do_masquerade(c[x]);
3094 ast_channel_lock(c[x]);
3095 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
3096 if (ast_tvzero(whentohangup))
3098 diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
3099 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3100 /* Should already be hungup */
3101 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3102 ast_channel_unlock(c[x]);
3105 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3106 whentohangup = diff;
3108 ast_channel_unlock(c[x]);
3110 /* Wait full interval */
3112 /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3113 if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3114 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
3115 if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
3118 } else if (!ast_tvzero(whentohangup) && rms < 0) {
3119 /* Tiny corner case... call would need to last >24 days */
3123 * Build the pollfd array, putting the channels' fds first,
3124 * followed by individual fds. Order is important because
3125 * individual fd's must have priority over channel fds.
3128 for (x = 0; x < n; x++) {
3129 for (y = 0; y < AST_MAX_FDS; y++) {
3130 fdmap[max].fdno = y; /* fd y is linked to this pfds */
3131 fdmap[max].chan = x; /* channel x is linked to this pfds */
3132 max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3134 CHECK_BLOCKING(c[x]);
3136 /* Add the individual fds */
3137 for (x = 0; x < nfds; x++) {
3138 fdmap[max].chan = -1;
3139 max += ast_add_fd(&pfds[max], fds[x]);
3143 start = ast_tvnow();
3146 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3149 if (kbrms > 600000) {
3152 res = ast_poll(pfds, max, kbrms);
3156 } while (!res && (rms > 0));
3158 res = ast_poll(pfds, max, rms);
3160 for (x = 0; x < n; x++) {
3161 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3163 if (res < 0) { /* Simulate a timeout if we were interrupted */
3164 if (errno != EINTR) {
3169 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
3171 for (x = 0; x < n; x++) {
3172 if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3173 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3174 if (winner == NULL) {
3180 if (res == 0) { /* no fd ready, reset timeout and done */
3181 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
3185 * Then check if any channel or fd has a pending event.
3186 * Remember to check channels first and fds last, as they
3187 * must have priority on setting 'winner'
3189 for (x = 0; x < max; x++) {
3190 res = pfds[x].revents;
3194 if (fdmap[x].chan >= 0) { /* this is a channel */
3195 winner = c[fdmap[x].chan]; /* override previous winners */
3196 if (res & POLLPRI) {
3197 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3199 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3201 ast_channel_fdno_set(winner, fdmap[x].fdno);
3202 } else { /* this is an fd */
3204 *outfd = pfds[x].fd;
3207 *exception = (res & POLLPRI) ? -1 : 0;
3213 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3222 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3224 struct timeval start = { 0 , 0 };
3226 struct epoll_event ev[1];
3227 long diff, rms = *ms;
3228 struct ast_channel *winner = NULL;
3229 struct ast_epoll_data *aed = NULL;
3232 /* See if this channel needs to be masqueraded */
3233 while (ast_channel_masq(chan)) {
3234 ast_do_masquerade(chan);
3237 ast_channel_lock(chan);
3238 /* Figure out their timeout */
3239 if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3240 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow())) < 0) {
3241 /* They should already be hungup! */
3242 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3243 ast_channel_unlock(chan);
3246 /* If this value is smaller then the current one... make it priority */
3252 ast_channel_unlock(chan);
3254 /* Time to make this channel block... */
3255 CHECK_BLOCKING(chan);
3258 start = ast_tvnow();
3261 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3262 res = epoll_wait(ast_channel_epfd(chan), ev, 1, rms);
3265 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
3267 /* Simulate a timeout if we were interrupted */
3269 if (errno != EINTR) {
3275 /* If this channel has a timeout see if it expired */
3276 if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3277 if (ast_tvdiff_ms(ast_tvnow(), *ast_channel_whentohangup(chan)) >= 0) {
3278 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3283 /* No fd ready, reset timeout and be done for now */
3289 /* See what events are pending */
3290 aed = ev[0].data.ptr;
3291 ast_channel_fdno_set(chan, aed->which);
3292 if (ev[0].events & EPOLLPRI) {
3293 ast_set_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3295 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3299 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3308 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3310 struct timeval start = { 0 , 0 };
3312 struct epoll_event ev[25] = { { 0, } };
3313 struct timeval now = { 0, 0 };
3314 long whentohangup = 0, diff = 0, rms = *ms;
3315 struct ast_channel *winner = NULL;
3317 for (i = 0; i < n; i++) {
3318 while (ast_channel_masq(c[i])) {
3319 ast_do_masquerade(c[i]);
3322 ast_channel_lock(c[i]);
3323 if (!ast_tvzero(*ast_channel_whentohangup(c[i]))) {
3324 if (whentohangup == 0) {
3327 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(c[i]), now)) < 0) {
3328 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3329 ast_channel_unlock(c[i]);
3332 if (!whentohangup || whentohangup > diff) {
3333 whentohangup = diff;
3336 ast_channel_unlock(c[i]);
3337 CHECK_BLOCKING(c[i]);
3343 if (*ms >= 0 && *ms < rms) {