2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Channel Management
23 * \author Mark Spencer <markster@digium.com>
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include "asterisk/_private.h"
36 #include "asterisk/paths.h" /* use ast_config_AST_SYSTEM_NAME */
38 #include "asterisk/pbx.h"
39 #include "asterisk/frame.h"
40 #include "asterisk/mod_format.h"
41 #include "asterisk/sched.h"
42 #include "asterisk/channel.h"
43 #include "asterisk/musiconhold.h"
44 #include "asterisk/say.h"
45 #include "asterisk/file.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/translate.h"
48 #include "asterisk/manager.h"
49 #include "asterisk/cel.h"
50 #include "asterisk/chanvars.h"
51 #include "asterisk/linkedlists.h"
52 #include "asterisk/indications.h"
53 #include "asterisk/monitor.h"
54 #include "asterisk/causes.h"
55 #include "asterisk/callerid.h"
56 #include "asterisk/utils.h"
57 #include "asterisk/lock.h"
58 #include "asterisk/app.h"
59 #include "asterisk/transcap.h"
60 #include "asterisk/devicestate.h"
61 #include "asterisk/threadstorage.h"
62 #include "asterisk/slinfactory.h"
63 #include "asterisk/audiohook.h"
64 #include "asterisk/framehook.h"
65 #include "asterisk/timing.h"
66 #include "asterisk/autochan.h"
67 #include "asterisk/stringfields.h"
68 #include "asterisk/global_datastores.h"
69 #include "asterisk/data.h"
70 #include "asterisk/channel_internal.h"
73 #include <sys/epoll.h>
76 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
79 #endif /* defined(HAVE_PRI) */
80 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
82 struct ast_epoll_data {
83 struct ast_channel *chan;
87 /* uncomment if you have problems with 'monitoring' synchronized files */
89 #define MONITOR_CONSTANT_DELAY
90 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
93 /*! \brief Prevent new channel allocation if shutting down. */
94 static int shutting_down;
98 unsigned long global_fin, global_fout;
100 AST_THREADSTORAGE(state2str_threadbuf);
101 #define STATE2STR_BUFSIZE 32
103 /*! Default amount of time to use when emulating a digit as a begin and end
105 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
107 /*! Minimum amount of time between the end of the last digit and the beginning
108 * of a new one - 45ms */
109 #define AST_MIN_DTMF_GAP 45
111 /*! \brief List of channel drivers */
113 const struct ast_channel_tech *tech;
114 AST_LIST_ENTRY(chanlist) list;
118 /*! \brief Structure to hold channel context backtrace data */
119 struct ast_chan_trace_data {
121 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
124 /*! \brief Structure to save contexts where an ast_chan has been into */
125 struct ast_chan_trace {
126 char context[AST_MAX_CONTEXT];
127 char exten[AST_MAX_EXTENSION];
129 AST_LIST_ENTRY(ast_chan_trace) entry;
133 /*! \brief the list of registered channel types */
134 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
137 #define NUM_CHANNEL_BUCKETS 61
139 #define NUM_CHANNEL_BUCKETS 1567
142 /*! \brief All active channels on the system */
143 static struct ao2_container *channels;
145 /*! \brief map AST_CAUSE's to readable string representations
149 static const struct {
154 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
155 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
156 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
157 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
158 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
159 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
160 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
161 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
162 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
163 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
164 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
165 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
166 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
167 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
168 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
169 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
170 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
171 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
172 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
173 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
174 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
175 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
176 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
177 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
178 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
179 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
180 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
181 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
182 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
183 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
184 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
185 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
186 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
187 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
188 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
189 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
190 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
191 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
192 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
193 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
194 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
195 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
196 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
197 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
200 struct ast_variable *ast_channeltype_list(void)
203 struct ast_variable *var = NULL, *prev = NULL;
205 AST_RWLIST_RDLOCK(&backends);
206 AST_RWLIST_TRAVERSE(&backends, cl, list) {
208 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
211 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
215 AST_RWLIST_UNLOCK(&backends);
220 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
221 static const char *party_number_ton2str(int ton)
223 #if defined(HAVE_PRI)
224 switch ((ton >> 4) & 0x07) {
225 case PRI_TON_INTERNATIONAL:
226 return "International";
227 case PRI_TON_NATIONAL:
229 case PRI_TON_NET_SPECIFIC:
230 return "Network Specific";
231 case PRI_TON_SUBSCRIBER:
233 case PRI_TON_ABBREVIATED:
234 return "Abbreviated";
235 case PRI_TON_RESERVED:
237 case PRI_TON_UNKNOWN:
241 #endif /* defined(HAVE_PRI) */
244 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
246 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
247 static const char *party_number_plan2str(int plan)
249 #if defined(HAVE_PRI)
250 switch (plan & 0x0F) {
252 case PRI_NPI_UNKNOWN:
254 case PRI_NPI_E163_E164:
255 return "Public (E.163/E.164)";
257 return "Data (X.121)";
259 return "Telex (F.69)";
260 case PRI_NPI_NATIONAL:
261 return "National Standard";
262 case PRI_NPI_PRIVATE:
264 case PRI_NPI_RESERVED:
267 #endif /* defined(HAVE_PRI) */
270 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
272 /*! \brief Show channel types - CLI command */
273 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
275 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
281 e->command = "core show channeltypes";
283 "Usage: core show channeltypes\n"
284 " Lists available channel types registered in your\n"
285 " Asterisk server.\n";
292 return CLI_SHOWUSAGE;
294 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
295 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
297 AST_RWLIST_RDLOCK(&backends);
298 AST_RWLIST_TRAVERSE(&backends, cl, list) {
299 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
300 (cl->tech->devicestate) ? "yes" : "no",
301 (cl->tech->indicate) ? "yes" : "no",
302 (cl->tech->transfer) ? "yes" : "no");
305 AST_RWLIST_UNLOCK(&backends);
307 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
314 static char *complete_channeltypes(struct ast_cli_args *a)
324 wordlen = strlen(a->word);
326 AST_RWLIST_RDLOCK(&backends);
327 AST_RWLIST_TRAVERSE(&backends, cl, list) {
328 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
329 ret = ast_strdup(cl->tech->type);
333 AST_RWLIST_UNLOCK(&backends);
338 /*! \brief Show details about a channel driver - CLI command */
339 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
341 struct chanlist *cl = NULL;
346 e->command = "core show channeltype";
348 "Usage: core show channeltype <name>\n"
349 " Show details about the specified channel type, <name>.\n";
352 return complete_channeltypes(a);
356 return CLI_SHOWUSAGE;
358 AST_RWLIST_RDLOCK(&backends);
360 AST_RWLIST_TRAVERSE(&backends, cl, list) {
361 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
367 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
368 AST_RWLIST_UNLOCK(&backends);
373 "-- Info about channel driver: %s --\n"
374 " Device State: %s\n"
377 " Capabilities: %s\n"
381 " Image Support: %s\n"
382 " Text Support: %s\n",
384 (cl->tech->devicestate) ? "yes" : "no",
385 (cl->tech->indicate) ? "yes" : "no",
386 (cl->tech->transfer) ? "yes" : "no",
387 ast_getformatname_multiple(buf, sizeof(buf), cl->tech->capabilities),
388 (cl->tech->send_digit_begin) ? "yes" : "no",
389 (cl->tech->send_digit_end) ? "yes" : "no",
390 (cl->tech->send_html) ? "yes" : "no",
391 (cl->tech->send_image) ? "yes" : "no",
392 (cl->tech->send_text) ? "yes" : "no"
396 AST_RWLIST_UNLOCK(&backends);
401 static struct ast_cli_entry cli_channel[] = {
402 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
403 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
406 static struct ast_frame *kill_read(struct ast_channel *chan)
408 /* Hangup channel. */
412 static struct ast_frame *kill_exception(struct ast_channel *chan)
414 /* Hangup channel. */
418 static int kill_write(struct ast_channel *chan, struct ast_frame *frame)
420 /* Hangup channel. */
424 static int kill_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
426 /* No problem fixing up the channel. */
430 static int kill_hangup(struct ast_channel *chan)
432 ast_channel_tech_pvt_set(chan, NULL);
437 * \brief Kill the channel channel driver technology descriptor.
440 * The purpose of this channel technology is to encourage the
441 * channel to hangup as quickly as possible.
443 * \note Used by DTMF atxfer and zombie channels.
445 const struct ast_channel_tech ast_kill_tech = {
447 .description = "Kill channel (should not see this)",
449 .exception = kill_exception,
452 .hangup = kill_hangup,
456 /*! \brief Destructor for the channel trace datastore */
457 static void ast_chan_trace_destroy_cb(void *data)
459 struct ast_chan_trace *trace;
460 struct ast_chan_trace_data *traced = data;
461 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
467 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
468 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
470 .destroy = ast_chan_trace_destroy_cb
473 /*! \brief Put the channel backtrace in a string */
474 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
477 struct ast_chan_trace *trace;
478 struct ast_chan_trace_data *traced;
479 struct ast_datastore *store;
481 ast_channel_lock(chan);
482 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
484 ast_channel_unlock(chan);
487 traced = store->data;
489 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
490 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
491 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
497 ast_channel_unlock(chan);
501 /* !\brief Whether or not context tracing is enabled */
502 int ast_channel_trace_is_enabled(struct ast_channel *chan)
504 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
507 return ((struct ast_chan_trace_data *)store->data)->enabled;
510 /*! \brief Update the context backtrace data if tracing is enabled */
511 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
513 struct ast_chan_trace *trace;
514 if (!traced->enabled)
516 /* If the last saved context does not match the current one
517 OR we have not saved any context so far, then save the current context */
518 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan))) ||
519 (AST_LIST_EMPTY(&traced->trace))) {
520 /* Just do some debug logging */
521 if (AST_LIST_EMPTY(&traced->trace))
522 ast_debug(1, "Setting initial trace context to %s\n", ast_channel_context(chan));
524 ast_debug(1, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, ast_channel_context(chan));
525 /* alloc or bail out */
526 trace = ast_malloc(sizeof(*trace));
529 /* save the current location and store it in the trace list */
530 ast_copy_string(trace->context, ast_channel_context(chan), sizeof(trace->context));
531 ast_copy_string(trace->exten, ast_channel_exten(chan), sizeof(trace->exten));
532 trace->priority = ast_channel_priority(chan);
533 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
538 /*! \brief Update the context backtrace if tracing is enabled */
539 int ast_channel_trace_update(struct ast_channel *chan)
541 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
544 return ast_channel_trace_data_update(chan, store->data);
547 /*! \brief Enable context tracing in the channel */
548 int ast_channel_trace_enable(struct ast_channel *chan)
550 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
551 struct ast_chan_trace_data *traced;
553 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
556 traced = ast_calloc(1, sizeof(*traced));
558 ast_datastore_free(store);
561 store->data = traced;
562 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
563 ast_channel_datastore_add(chan, store);
565 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
566 ast_channel_trace_data_update(chan, store->data);
570 /*! \brief Disable context tracing in the channel */
571 int ast_channel_trace_disable(struct ast_channel *chan)
573 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
576 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
579 #endif /* CHANNEL_TRACE */
581 /*! \brief Checks to see if a channel is needing hang up */
582 int ast_check_hangup(struct ast_channel *chan)
584 if (ast_channel_softhangup_internal_flag(chan)) /* yes if soft hangup flag set */
586 if (ast_tvzero(*ast_channel_whentohangup(chan))) /* no if no hangup scheduled */
588 if (ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()) > 0) /* no if hangup time has not come yet. */
590 ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()));
591 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT); /* record event */
595 int ast_check_hangup_locked(struct ast_channel *chan)
598 ast_channel_lock(chan);
599 res = ast_check_hangup(chan);
600 ast_channel_unlock(chan);
604 int ast_channel_softhangup_withcause_locked(void *obj, int causecode)
606 struct ast_channel *chan = obj;
608 ast_channel_lock(chan);
611 ast_debug(1, "Setting hangupcause of channel %s to %d (is %d now)\n",
612 ast_channel_name(chan), causecode, ast_channel_hangupcause(chan));
614 ast_channel_hangupcause_set(chan, causecode);
617 ast_softhangup_nolock(chan, AST_SOFTHANGUP_EXPLICIT);
619 ast_channel_unlock(chan);
624 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
626 struct ast_channel *chan = obj;
628 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
633 void ast_begin_shutdown(int hangup)
638 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
642 /*! \brief returns number of active/allocated channels */
643 int ast_active_channels(void)
645 return channels ? ao2_container_count(channels) : 0;
648 /*! \brief Cancel a shutdown in progress */
649 void ast_cancel_shutdown(void)
654 /*! \brief Returns non-zero if Asterisk is being shut down */
655 int ast_shutting_down(void)
657 return shutting_down;
660 /*! \brief Set when to hangup channel */
661 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
663 if (ast_tvzero(offset)) {
664 ast_channel_whentohangup_set(chan, &offset);
666 struct timeval tv = ast_tvadd(offset, ast_tvnow());
667 ast_channel_whentohangup_set(chan, &tv);
669 ast_queue_frame(chan, &ast_null_frame);
673 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
675 struct timeval when = { offset, };
676 ast_channel_setwhentohangup_tv(chan, when);
679 /*! \brief Compare a offset with when to hangup channel */
680 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
682 struct timeval whentohangup;
684 if (ast_tvzero(*ast_channel_whentohangup(chan)))
685 return ast_tvzero(offset) ? 0 : -1;
687 if (ast_tvzero(offset))
690 whentohangup = ast_tvadd(offset, ast_tvnow());
692 return ast_tvdiff_ms(whentohangup, *ast_channel_whentohangup(chan));
695 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
697 struct timeval when = { offset, };
698 return ast_channel_cmpwhentohangup_tv(chan, when);
701 /*! \brief Register a new telephony channel in Asterisk */
702 int ast_channel_register(const struct ast_channel_tech *tech)
704 struct chanlist *chan;
706 AST_RWLIST_WRLOCK(&backends);
708 AST_RWLIST_TRAVERSE(&backends, chan, list) {
709 if (!strcasecmp(tech->type, chan->tech->type)) {
710 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
711 AST_RWLIST_UNLOCK(&backends);
716 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
717 AST_RWLIST_UNLOCK(&backends);
721 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
723 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
725 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
727 AST_RWLIST_UNLOCK(&backends);
732 /*! \brief Unregister channel driver */
733 void ast_channel_unregister(const struct ast_channel_tech *tech)
735 struct chanlist *chan;
737 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
739 AST_RWLIST_WRLOCK(&backends);
741 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
742 if (chan->tech == tech) {
743 AST_LIST_REMOVE_CURRENT(list);
745 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
749 AST_LIST_TRAVERSE_SAFE_END;
751 AST_RWLIST_UNLOCK(&backends);
754 /*! \brief Get handle to channel driver based on name */
755 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
757 struct chanlist *chanls;
758 const struct ast_channel_tech *ret = NULL;
760 AST_RWLIST_RDLOCK(&backends);
762 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
763 if (!strcasecmp(name, chanls->tech->type)) {
769 AST_RWLIST_UNLOCK(&backends);
774 /*! \brief Gives the string form of a given hangup cause */
775 const char *ast_cause2str(int cause)
779 for (x = 0; x < ARRAY_LEN(causes); x++) {
780 if (causes[x].cause == cause)
781 return causes[x].desc;
787 /*! \brief Convert a symbolic hangup cause to number */
788 int ast_str2cause(const char *name)
792 for (x = 0; x < ARRAY_LEN(causes); x++)
793 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
794 return causes[x].cause;
799 /*! \brief Gives the string form of a given channel state.
800 \note This function is not reentrant.
802 const char *ast_state2str(enum ast_channel_state state)
809 case AST_STATE_RESERVED:
811 case AST_STATE_OFFHOOK:
813 case AST_STATE_DIALING:
817 case AST_STATE_RINGING:
823 case AST_STATE_DIALING_OFFHOOK:
824 return "Dialing Offhook";
825 case AST_STATE_PRERING:
828 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
830 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
835 /*! \brief Gives the string form of a given transfer capability */
836 char *ast_transfercapability2str(int transfercapability)
838 switch (transfercapability) {
839 case AST_TRANS_CAP_SPEECH:
841 case AST_TRANS_CAP_DIGITAL:
843 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
844 return "RESTRICTED_DIGITAL";
845 case AST_TRANS_CAP_3_1K_AUDIO:
847 case AST_TRANS_CAP_DIGITAL_W_TONES:
848 return "DIGITAL_W_TONES";
849 case AST_TRANS_CAP_VIDEO:
856 /*! \brief Pick the best audio codec */
857 struct ast_format *ast_best_codec(struct ast_format_cap *cap, struct ast_format *result)
859 /* This just our opinion, expressed in code. We are asked to choose
860 the best codec to use, given no information */
861 static const enum ast_format_id prefs[] =
863 /*! Okay, ulaw is used by all telephony equipment, so start with it */
865 /*! Unless of course, you're a silly European, so then prefer ALAW */
871 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
873 /*! Okay, well, signed linear is easy to translate into other stuff */
874 AST_FORMAT_SLINEAR192,
875 AST_FORMAT_SLINEAR96,
876 AST_FORMAT_SLINEAR48,
877 AST_FORMAT_SLINEAR44,
878 AST_FORMAT_SLINEAR32,
879 AST_FORMAT_SLINEAR24,
880 AST_FORMAT_SLINEAR16,
881 AST_FORMAT_SLINEAR12,
883 /*! G.726 is standard ADPCM, in RFC3551 packing order */
885 /*! G.726 is standard ADPCM, in AAL2 packing order */
886 AST_FORMAT_G726_AAL2,
887 /*! ADPCM has great sound quality and is still pretty easy to translate */
889 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
890 translate and sounds pretty good */
892 /*! iLBC is not too bad */
894 /*! Speex is free, but computationally more expensive than GSM */
898 /*! SILK is pretty awesome. */
900 /*! CELT supports crazy high sample rates */
902 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
905 /*! G.729a is faster than 723 and slightly less expensive */
907 /*! Down to G.723.1 which is proprietary but at least designed for voice */
913 /* Find the first preferred codec in the format given */
914 for (x = 0; x < ARRAY_LEN(prefs); x++) {
915 if (ast_format_cap_best_byid(cap, prefs[x], result)) {
920 ast_format_clear(result);
921 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
926 static const struct ast_channel_tech null_tech = {
928 .description = "Null channel (should not see this)",
931 static void ast_channel_destructor(void *obj);
932 static void ast_dummy_channel_destructor(void *obj);
934 /*! \brief Create a new channel structure */
935 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
936 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
937 const char *acctcode, const char *exten, const char *context,
938 const char *linkedid, const int amaflag, const char *file, int line,
939 const char *function, const char *name_fmt, va_list ap)
941 struct ast_channel *tmp;
942 struct varshead *headp;
943 char *tech = "", *tech2 = NULL;
944 struct ast_format_cap *nativeformats;
945 struct ast_sched_context *schedctx;
946 struct ast_timer *timer;
948 /* If shutting down, don't allocate any new channels */
949 if (ast_shutting_down()) {
950 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
954 if (!(tmp = ast_channel_internal_alloc(ast_channel_destructor))) {
955 /* Channel structure allocation failure. */
958 if (!(nativeformats = ast_format_cap_alloc())) {
960 /* format capabilities structure allocation failure */
963 ast_channel_nativeformats_set(tmp, nativeformats);
966 * Init file descriptors to unopened state so
967 * the destructor can know not to close them.
969 ast_channel_timingfd_set(tmp, -1);
970 ast_channel_internal_alertpipe_clear(tmp);
971 ast_channel_internal_fd_clear_all(tmp);
974 ast_channel_epfd(tmp) = epoll_create(25);
977 if (!(schedctx = ast_sched_context_create())) {
978 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
979 return ast_channel_unref(tmp);
981 ast_channel_sched_set(tmp, schedctx);
983 ast_party_dialed_init(ast_channel_dialed(tmp));
984 ast_party_caller_init(ast_channel_caller(tmp));
985 ast_party_connected_line_init(ast_channel_connected(tmp));
986 ast_party_redirecting_init(ast_channel_redirecting(tmp));
989 ast_channel_caller(tmp)->id.name.valid = 1;
990 ast_channel_caller(tmp)->id.name.str = ast_strdup(cid_name);
991 if (!ast_channel_caller(tmp)->id.name.str) {
992 return ast_channel_unref(tmp);
996 ast_channel_caller(tmp)->id.number.valid = 1;
997 ast_channel_caller(tmp)->id.number.str = ast_strdup(cid_num);
998 if (!ast_channel_caller(tmp)->id.number.str) {
999 return ast_channel_unref(tmp);
1003 if ((timer = ast_timer_open())) {
1004 ast_channel_timer_set(tmp, timer);
1005 if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
1008 ast_channel_timingfd_set(tmp, ast_timer_fd(ast_channel_timer(tmp)));
1012 * This is the last place the channel constructor can fail.
1014 * The destructor takes advantage of this fact to ensure that the
1015 * AST_CEL_CHANNEL_END is not posted if we have not posted the
1016 * AST_CEL_CHANNEL_START yet.
1019 if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
1020 return ast_channel_unref(tmp);
1023 /* Always watch the alertpipe */
1024 ast_channel_set_fd(tmp, AST_ALERT_FD, ast_channel_internal_alert_readfd(tmp));
1025 /* And timing pipe */
1026 ast_channel_set_fd(tmp, AST_TIMING_FD, ast_channel_timingfd(tmp));
1029 ast_channel_state_set(tmp, state);
1031 ast_channel_streamid_set(tmp, -1);
1033 ast_channel_fin_set(tmp, global_fin);
1034 ast_channel_fout_set(tmp, global_fout);
1036 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1037 ast_channel_uniqueid_build(tmp, "%li.%d", (long) time(NULL),
1038 ast_atomic_fetchadd_int(&uniqueint, 1));
1040 ast_channel_uniqueid_build(tmp, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
1041 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1044 if (!ast_strlen_zero(linkedid)) {
1045 ast_channel_linkedid_set(tmp, linkedid);
1047 ast_channel_linkedid_set(tmp, ast_channel_uniqueid(tmp));
1050 if (!ast_strlen_zero(name_fmt)) {
1051 char *slash, *slash2;
1052 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1053 * And they all use slightly different formats for their name string.
1054 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1055 * This means, that the stringfields must have a routine that takes the va_lists directly, and
1056 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1057 * This new function was written so this can be accomplished.
1059 ast_channel_name_build_va(tmp, name_fmt, ap);
1060 tech = ast_strdupa(ast_channel_name(tmp));
1061 if ((slash = strchr(tech, '/'))) {
1062 if ((slash2 = strchr(slash + 1, '/'))) {
1070 * Start the string with '-' so it becomes an empty string
1071 * in the destructor.
1073 ast_channel_name_set(tmp, "-**Unknown**");
1076 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1078 /* These 4 variables need to be set up for the cdr_init() to work right */
1080 ast_channel_amaflags_set(tmp, amaflag);
1082 ast_channel_amaflags_set(tmp, ast_default_amaflags);
1085 if (!ast_strlen_zero(acctcode))
1086 ast_channel_accountcode_set(tmp, acctcode);
1088 ast_channel_accountcode_set(tmp, ast_default_accountcode);
1090 ast_channel_context_set(tmp, S_OR(context, "default"));
1091 ast_channel_exten_set(tmp, S_OR(exten, "s"));
1092 ast_channel_priority_set(tmp, 1);
1094 ast_channel_cdr_set(tmp, ast_cdr_alloc());
1095 ast_cdr_init(ast_channel_cdr(tmp), tmp);
1096 ast_cdr_start(ast_channel_cdr(tmp));
1098 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1100 headp = ast_channel_varshead(tmp);
1101 AST_LIST_HEAD_INIT_NOLOCK(headp);
1103 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1105 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_autochans(tmp));
1107 ast_channel_language_set(tmp, defaultlanguage);
1109 ast_channel_tech_set(tmp, &null_tech);
1111 ao2_link(channels, tmp);
1114 * And now, since the channel structure is built, and has its name, let's
1115 * call the manager event generator with this Newchannel event. This is the
1116 * proper and correct place to make this call, but you sure do have to pass
1117 * a lot of data into this func to do it here!
1119 if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1120 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1122 "ChannelState: %d\r\n"
1123 "ChannelStateDesc: %s\r\n"
1124 "CallerIDNum: %s\r\n"
1125 "CallerIDName: %s\r\n"
1126 "AccountCode: %s\r\n"
1130 ast_channel_name(tmp),
1132 ast_state2str(state),
1135 ast_channel_accountcode(tmp),
1138 ast_channel_uniqueid(tmp));
1141 ast_channel_internal_finalize(tmp);
1145 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1146 const char *cid_name, const char *acctcode,
1147 const char *exten, const char *context,
1148 const char *linkedid, const int amaflag,
1149 const char *file, int line, const char *function,
1150 const char *name_fmt, ...)
1153 struct ast_channel *result;
1155 va_start(ap, name_fmt);
1156 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1157 linkedid, amaflag, file, line, function, name_fmt, ap);
1163 /* only do the minimum amount of work needed here to make a channel
1164 * structure that can be used to expand channel vars */
1165 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1166 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1168 struct ast_channel *ast_dummy_channel_alloc(void)
1171 struct ast_channel *tmp;
1172 struct varshead *headp;
1174 if (!(tmp = ast_channel_internal_alloc(ast_dummy_channel_destructor))) {
1175 /* Dummy channel structure allocation failure. */
1179 headp = ast_channel_varshead(tmp);
1180 AST_LIST_HEAD_INIT_NOLOCK(headp);
1185 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1187 struct ast_frame *f;
1188 struct ast_frame *cur;
1189 unsigned int new_frames = 0;
1190 unsigned int new_voice_frames = 0;
1191 unsigned int queued_frames = 0;
1192 unsigned int queued_voice_frames = 0;
1193 AST_LIST_HEAD_NOLOCK(,ast_frame) frames;
1195 ast_channel_lock(chan);
1198 * Check the last frame on the queue if we are queuing the new
1201 cur = AST_LIST_LAST(ast_channel_readq(chan));
1202 if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1203 switch (cur->subclass.integer) {
1204 case AST_CONTROL_END_OF_Q:
1205 if (fin->frametype == AST_FRAME_CONTROL
1206 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1208 * Destroy the end-of-Q marker frame so we can queue the hangup
1209 * frame in its place.
1211 AST_LIST_REMOVE(ast_channel_readq(chan), cur, frame_list);
1215 * This has degenerated to a normal queue append anyway. Since
1216 * we just destroyed the last frame in the queue we must make
1217 * sure that "after" is NULL or bad things will happen.
1223 case AST_CONTROL_HANGUP:
1224 /* Don't queue anything. */
1225 ast_channel_unlock(chan);
1232 /* Build copies of all the new frames and count them */
1233 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1234 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1235 if (!(f = ast_frdup(cur))) {
1236 if (AST_LIST_FIRST(&frames)) {
1237 ast_frfree(AST_LIST_FIRST(&frames));
1239 ast_channel_unlock(chan);
1243 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1245 if (f->frametype == AST_FRAME_VOICE) {
1250 /* Count how many frames exist on the queue */
1251 AST_LIST_TRAVERSE(ast_channel_readq(chan), cur, frame_list) {
1253 if (cur->frametype == AST_FRAME_VOICE) {
1254 queued_voice_frames++;
1258 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1260 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1261 AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), cur, frame_list) {
1262 /* Save the most recent frame */
1263 if (!AST_LIST_NEXT(cur, frame_list)) {
1265 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1269 AST_LIST_REMOVE_CURRENT(frame_list);
1273 AST_LIST_TRAVERSE_SAFE_END;
1277 AST_LIST_INSERT_LIST_AFTER(ast_channel_readq(chan), &frames, after, frame_list);
1280 AST_LIST_APPEND_LIST(&frames, ast_channel_readq(chan), frame_list);
1281 AST_LIST_HEAD_INIT_NOLOCK(ast_channel_readq(chan));
1283 AST_LIST_APPEND_LIST(ast_channel_readq(chan), &frames, frame_list);
1286 if (ast_channel_alert_writable(chan)) {
1287 if (ast_channel_alert_write(chan)) {
1288 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1289 ast_channel_name(chan), queued_frames, strerror(errno));
1291 } else if (ast_channel_timingfd(chan) > -1) {
1292 ast_timer_enable_continuous(ast_channel_timer(chan));
1293 } else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
1294 pthread_kill(ast_channel_blocker(chan), SIGURG);
1297 ast_channel_unlock(chan);
1302 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1304 return __ast_queue_frame(chan, fin, 0, NULL);
1307 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1309 return __ast_queue_frame(chan, fin, 1, NULL);
1312 /*! \brief Queue a hangup frame for channel */
1313 int ast_queue_hangup(struct ast_channel *chan)
1315 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1316 /* Yeah, let's not change a lock-critical value without locking */
1317 if (!ast_channel_trylock(chan)) {
1318 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1319 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1322 ast_channel_name(chan),
1323 ast_channel_uniqueid(chan));
1324 ast_channel_unlock(chan);
1326 return ast_queue_frame(chan, &f);
1329 /*! \brief Queue a hangup frame for channel */
1330 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1332 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1335 f.data.uint32 = cause;
1337 /* Yeah, let's not change a lock-critical value without locking */
1338 if (!ast_channel_trylock(chan)) {
1339 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1341 f.data.uint32 = ast_channel_hangupcause(chan);
1343 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1347 ast_channel_name(chan),
1348 ast_channel_uniqueid(chan),
1350 ast_channel_unlock(chan);
1353 return ast_queue_frame(chan, &f);
1356 /*! \brief Queue a control frame */
1357 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1359 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1360 return ast_queue_frame(chan, &f);
1363 /*! \brief Queue a control frame with payload */
1364 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1365 const void *data, size_t datalen)
1367 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1368 return ast_queue_frame(chan, &f);
1371 /*! \brief Set defer DTMF flag on channel */
1372 int ast_channel_defer_dtmf(struct ast_channel *chan)
1377 pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1378 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1383 /*! \brief Unset defer DTMF flag on channel */
1384 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1387 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1390 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1391 void *data, int ao2_flags)
1393 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1396 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1398 struct ast_channel *chan = obj;
1399 const char *name = arg;
1400 size_t name_len = *(size_t *) data;
1401 int ret = CMP_MATCH;
1403 if (ast_strlen_zero(name)) {
1404 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1408 ast_channel_lock(chan);
1409 if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1410 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1411 ret = 0; /* name match failed, keep looking */
1413 ast_channel_unlock(chan);
1418 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1420 struct ast_channel *chan = obj;
1421 char *context = arg;
1423 int ret = CMP_MATCH;
1425 if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1426 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1430 ast_channel_lock(chan);
1431 if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1432 ret = 0; /* Context match failed, continue */
1433 } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1434 ret = 0; /* Extension match failed, continue */
1436 ast_channel_unlock(chan);
1441 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1443 struct ast_channel *chan = obj;
1444 char *uniqueid = arg;
1445 size_t id_len = *(size_t *) data;
1446 int ret = CMP_MATCH;
1448 if (ast_strlen_zero(uniqueid)) {
1449 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1453 ast_channel_lock(chan);
1454 if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1455 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1456 ret = 0; /* uniqueid match failed, keep looking */
1458 ast_channel_unlock(chan);
1463 struct ast_channel_iterator {
1464 /* storage for non-dynamically allocated iterator */
1465 struct ao2_iterator simple_iterator;
1466 /* pointer to the actual iterator (simple_iterator or a dynamically
1467 * allocated iterator)
1469 struct ao2_iterator *active_iterator;
1472 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1474 ao2_iterator_destroy(i->active_iterator);
1480 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1482 struct ast_channel_iterator *i;
1483 char *l_exten = (char *) exten;
1484 char *l_context = (char *) context;
1486 if (!(i = ast_calloc(1, sizeof(*i)))) {
1490 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1491 l_context, l_exten, OBJ_MULTIPLE);
1492 if (!i->active_iterator) {
1500 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1502 struct ast_channel_iterator *i;
1503 char *l_name = (char *) name;
1505 if (!(i = ast_calloc(1, sizeof(*i)))) {
1509 i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1511 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1512 if (!i->active_iterator) {
1520 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1522 struct ast_channel_iterator *i;
1524 if (!(i = ast_calloc(1, sizeof(*i)))) {
1528 i->simple_iterator = ao2_iterator_init(channels, 0);
1529 i->active_iterator = &i->simple_iterator;
1534 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1536 return ao2_iterator_next(i->active_iterator);
1539 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1540 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1542 ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1546 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1548 struct ast_channel *chan;
1549 char *l_name = (char *) name;
1551 chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1552 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1557 if (ast_strlen_zero(l_name)) {
1558 /* We didn't have a name to search for so quit. */
1562 /* Now try a search for uniqueid. */
1563 return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1566 struct ast_channel *ast_channel_get_by_name(const char *name)
1568 return ast_channel_get_by_name_prefix(name, 0);
1571 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1573 char *l_exten = (char *) exten;
1574 char *l_context = (char *) context;
1576 return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1579 int ast_is_deferrable_frame(const struct ast_frame *frame)
1581 /* Do not add a default entry in this switch statement. Each new
1582 * frame type should be addressed directly as to whether it should
1583 * be queued up or not.
1585 switch (frame->frametype) {
1586 case AST_FRAME_CONTROL:
1587 case AST_FRAME_TEXT:
1588 case AST_FRAME_IMAGE:
1589 case AST_FRAME_HTML:
1592 case AST_FRAME_DTMF_END:
1593 case AST_FRAME_DTMF_BEGIN:
1594 case AST_FRAME_VOICE:
1595 case AST_FRAME_VIDEO:
1596 case AST_FRAME_NULL:
1599 case AST_FRAME_MODEM:
1605 /*! \brief Wait, look for hangups and condition arg */
1606 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1608 struct ast_frame *f;
1609 struct ast_silence_generator *silgen = NULL;
1611 AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1613 AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1615 /* If no other generator is present, start silencegen while waiting */
1616 if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1617 silgen = ast_channel_start_silence_generator(chan);
1621 struct ast_frame *dup_f = NULL;
1622 if (cond && ((*cond)(data) == 0)) {
1625 ms = ast_waitfor(chan, ms);
1637 if (!ast_is_deferrable_frame(f)) {
1642 if ((dup_f = ast_frisolate(f))) {
1646 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1651 /* stop silgen if present */
1653 ast_channel_stop_silence_generator(chan, silgen);
1656 /* We need to free all the deferred frames, but we only need to
1657 * queue the deferred frames if there was no error and no
1658 * hangup was received
1660 ast_channel_lock(chan);
1661 while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1663 ast_queue_frame_head(chan, f);
1667 ast_channel_unlock(chan);
1672 /*! \brief Wait, look for hangups */
1673 int ast_safe_sleep(struct ast_channel *chan, int ms)
1675 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1678 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1680 /* Safe, even if already unlinked. */
1681 ao2_unlink(channels, chan);
1682 return ast_channel_unref(chan);
1685 void ast_party_name_init(struct ast_party_name *init)
1688 init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1689 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1693 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1696 /* Don't copy to self */
1700 ast_free(dest->str);
1701 dest->str = ast_strdup(src->str);
1702 dest->char_set = src->char_set;
1703 dest->presentation = src->presentation;
1704 dest->valid = src->valid;
1707 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1710 init->char_set = guide->char_set;
1711 init->presentation = guide->presentation;
1712 init->valid = guide->valid;
1715 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1718 /* Don't set to self */
1722 if (src->str && src->str != dest->str) {
1723 ast_free(dest->str);
1724 dest->str = ast_strdup(src->str);
1727 dest->char_set = src->char_set;
1728 dest->presentation = src->presentation;
1729 dest->valid = src->valid;
1732 void ast_party_name_free(struct ast_party_name *doomed)
1734 ast_free(doomed->str);
1738 void ast_party_number_init(struct ast_party_number *init)
1741 init->plan = 0;/* Unknown */
1742 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1746 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1749 /* Don't copy to self */
1753 ast_free(dest->str);
1754 dest->str = ast_strdup(src->str);
1755 dest->plan = src->plan;
1756 dest->presentation = src->presentation;
1757 dest->valid = src->valid;
1760 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1763 init->plan = guide->plan;
1764 init->presentation = guide->presentation;
1765 init->valid = guide->valid;
1768 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1771 /* Don't set to self */
1775 if (src->str && src->str != dest->str) {
1776 ast_free(dest->str);
1777 dest->str = ast_strdup(src->str);
1780 dest->plan = src->plan;
1781 dest->presentation = src->presentation;
1782 dest->valid = src->valid;
1785 void ast_party_number_free(struct ast_party_number *doomed)
1787 ast_free(doomed->str);
1791 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1795 init->odd_even_indicator = 0;
1799 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1802 /* Don't copy to self */
1806 ast_free(dest->str);
1807 dest->str = ast_strdup(src->str);
1808 dest->type = src->type;
1809 dest->odd_even_indicator = src->odd_even_indicator;
1810 dest->valid = src->valid;
1813 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1816 init->type = guide->type;
1817 init->odd_even_indicator = guide->odd_even_indicator;
1818 init->valid = guide->valid;
1821 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1824 /* Don't set to self */
1828 if (src->str && src->str != dest->str) {
1829 ast_free(dest->str);
1830 dest->str = ast_strdup(src->str);
1833 dest->type = src->type;
1834 dest->odd_even_indicator = src->odd_even_indicator;
1835 dest->valid = src->valid;
1838 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1840 ast_free(doomed->str);
1844 void ast_party_id_init(struct ast_party_id *init)
1846 ast_party_name_init(&init->name);
1847 ast_party_number_init(&init->number);
1848 ast_party_subaddress_init(&init->subaddress);
1852 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1855 /* Don't copy to self */
1859 ast_party_name_copy(&dest->name, &src->name);
1860 ast_party_number_copy(&dest->number, &src->number);
1861 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1863 ast_free(dest->tag);
1864 dest->tag = ast_strdup(src->tag);
1867 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1869 ast_party_name_set_init(&init->name, &guide->name);
1870 ast_party_number_set_init(&init->number, &guide->number);
1871 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1875 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1878 /* Don't set to self */
1882 if (!update || update->name) {
1883 ast_party_name_set(&dest->name, &src->name);
1885 if (!update || update->number) {
1886 ast_party_number_set(&dest->number, &src->number);
1888 if (!update || update->subaddress) {
1889 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1892 if (src->tag && src->tag != dest->tag) {
1893 ast_free(dest->tag);
1894 dest->tag = ast_strdup(src->tag);
1898 void ast_party_id_free(struct ast_party_id *doomed)
1900 ast_party_name_free(&doomed->name);
1901 ast_party_number_free(&doomed->number);
1902 ast_party_subaddress_free(&doomed->subaddress);
1904 ast_free(doomed->tag);
1908 int ast_party_id_presentation(const struct ast_party_id *id)
1910 int number_priority;
1912 int number_screening;
1916 /* Determine name presentation priority. */
1917 if (!id->name.valid) {
1918 name_value = AST_PRES_UNAVAILABLE;
1921 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1922 switch (name_value) {
1923 case AST_PRES_RESTRICTED:
1926 case AST_PRES_ALLOWED:
1929 case AST_PRES_UNAVAILABLE:
1933 name_value = AST_PRES_UNAVAILABLE;
1939 /* Determine number presentation priority. */
1940 if (!id->number.valid) {
1941 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1942 number_value = AST_PRES_UNAVAILABLE;
1943 number_priority = 3;
1945 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1946 number_value = id->number.presentation & AST_PRES_RESTRICTION;
1947 switch (number_value) {
1948 case AST_PRES_RESTRICTED:
1949 number_priority = 0;
1951 case AST_PRES_ALLOWED:
1952 number_priority = 1;
1954 case AST_PRES_UNAVAILABLE:
1955 number_priority = 2;
1958 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1959 number_value = AST_PRES_UNAVAILABLE;
1960 number_priority = 3;
1965 /* Select the wining presentation value. */
1966 if (name_priority < number_priority) {
1967 number_value = name_value;
1969 if (number_value == AST_PRES_UNAVAILABLE) {
1970 return AST_PRES_NUMBER_NOT_AVAILABLE;
1973 return number_value | number_screening;
1976 void ast_party_dialed_init(struct ast_party_dialed *init)
1978 init->number.str = NULL;
1979 init->number.plan = 0;/* Unknown */
1980 ast_party_subaddress_init(&init->subaddress);
1981 init->transit_network_select = 0;
1984 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1987 /* Don't copy to self */
1991 ast_free(dest->number.str);
1992 dest->number.str = ast_strdup(src->number.str);
1993 dest->number.plan = src->number.plan;
1994 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1995 dest->transit_network_select = src->transit_network_select;
1998 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2000 init->number.str = NULL;
2001 init->number.plan = guide->number.plan;
2002 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2003 init->transit_network_select = guide->transit_network_select;
2006 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2008 if (src->number.str && src->number.str != dest->number.str) {
2009 ast_free(dest->number.str);
2010 dest->number.str = ast_strdup(src->number.str);
2012 dest->number.plan = src->number.plan;
2014 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2016 dest->transit_network_select = src->transit_network_select;
2019 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2021 ast_free(doomed->number.str);
2022 doomed->number.str = NULL;
2023 ast_party_subaddress_free(&doomed->subaddress);
2026 void ast_party_caller_init(struct ast_party_caller *init)
2028 ast_party_id_init(&init->id);
2029 ast_party_id_init(&init->ani);
2033 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2036 /* Don't copy to self */
2040 ast_party_id_copy(&dest->id, &src->id);
2041 ast_party_id_copy(&dest->ani, &src->ani);
2042 dest->ani2 = src->ani2;
2045 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2047 ast_party_id_set_init(&init->id, &guide->id);
2048 ast_party_id_set_init(&init->ani, &guide->ani);
2049 init->ani2 = guide->ani2;
2052 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2054 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2055 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2056 dest->ani2 = src->ani2;
2059 void ast_party_caller_free(struct ast_party_caller *doomed)
2061 ast_party_id_free(&doomed->id);
2062 ast_party_id_free(&doomed->ani);
2065 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2067 ast_party_id_init(&init->id);
2068 ast_party_id_init(&init->ani);
2070 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2073 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2076 /* Don't copy to self */
2080 ast_party_id_copy(&dest->id, &src->id);
2081 ast_party_id_copy(&dest->ani, &src->ani);
2082 dest->ani2 = src->ani2;
2083 dest->source = src->source;
2086 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2088 ast_party_id_set_init(&init->id, &guide->id);
2089 ast_party_id_set_init(&init->ani, &guide->ani);
2090 init->ani2 = guide->ani2;
2091 init->source = guide->source;
2094 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)
2096 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2097 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2098 dest->ani2 = src->ani2;
2099 dest->source = src->source;
2102 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2104 connected->id = caller->id;
2105 connected->ani = caller->ani;
2106 connected->ani2 = caller->ani2;
2107 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2110 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2112 ast_party_id_free(&doomed->id);
2113 ast_party_id_free(&doomed->ani);
2116 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2118 ast_party_id_init(&init->orig);
2119 ast_party_id_init(&init->from);
2120 ast_party_id_init(&init->to);
2122 init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2123 init->orig_reason = AST_REDIRECTING_REASON_UNKNOWN;
2126 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2129 /* Don't copy to self */
2133 ast_party_id_copy(&dest->orig, &src->orig);
2134 ast_party_id_copy(&dest->from, &src->from);
2135 ast_party_id_copy(&dest->to, &src->to);
2136 dest->count = src->count;
2137 dest->reason = src->reason;
2138 dest->orig_reason = src->orig_reason;
2141 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2143 ast_party_id_set_init(&init->orig, &guide->orig);
2144 ast_party_id_set_init(&init->from, &guide->from);
2145 ast_party_id_set_init(&init->to, &guide->to);
2146 init->count = guide->count;
2147 init->reason = guide->reason;
2148 init->orig_reason = guide->orig_reason;
2151 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2153 ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2154 ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2155 ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2156 dest->count = src->count;
2157 dest->reason = src->reason;
2158 dest->orig_reason = src->orig_reason;
2161 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2163 ast_party_id_free(&doomed->orig);
2164 ast_party_id_free(&doomed->from);
2165 ast_party_id_free(&doomed->to);
2168 /*! \brief Free a channel structure */
2169 static void ast_channel_destructor(void *obj)
2171 struct ast_channel *chan = obj;
2175 struct ast_var_t *vardata;
2176 struct ast_frame *f;
2177 struct varshead *headp;
2178 struct ast_datastore *datastore;
2179 char device_name[AST_CHANNEL_NAME];
2181 if (ast_channel_internal_is_finalized(chan)) {
2182 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2183 ast_cel_check_retire_linkedid(chan);
2186 /* Get rid of each of the data stores on the channel */
2187 ast_channel_lock(chan);
2188 while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2189 /* Free the data store */
2190 ast_datastore_free(datastore);
2191 ast_channel_unlock(chan);
2193 /* Lock and unlock the channel just to be sure nobody has it locked still
2194 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2195 ast_channel_lock(chan);
2196 ast_channel_unlock(chan);
2198 if (ast_channel_tech_pvt(chan)) {
2199 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2200 ast_free(ast_channel_tech_pvt(chan));
2203 if (ast_channel_sched(chan)) {
2204 ast_sched_context_destroy(ast_channel_sched(chan));
2207 if (ast_channel_internal_is_finalized(chan)) {
2210 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2211 if ((dashptr = strrchr(device_name, '-'))) {
2215 device_name[0] = '\0';
2218 /* Stop monitoring */
2219 if (ast_channel_monitor(chan))
2220 ast_channel_monitor(chan)->stop( chan, 0 );
2222 /* If there is native format music-on-hold state, free it */
2223 if (ast_channel_music_state(chan))
2224 ast_moh_cleanup(chan);
2226 /* Free translators */
2227 if (ast_channel_readtrans(chan))
2228 ast_translator_free_path(ast_channel_readtrans(chan));
2229 if (ast_channel_writetrans(chan))
2230 ast_translator_free_path(ast_channel_writetrans(chan));
2231 if (ast_channel_pbx(chan))
2232 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2234 ast_party_dialed_free(ast_channel_dialed(chan));
2235 ast_party_caller_free(ast_channel_caller(chan));
2236 ast_party_connected_line_free(ast_channel_connected(chan));
2237 ast_party_redirecting_free(ast_channel_redirecting(chan));
2239 /* Close pipes if appropriate */
2240 ast_channel_internal_alertpipe_close(chan);
2241 if (ast_channel_timer(chan)) {
2242 ast_timer_close(ast_channel_timer(chan));
2245 for (i = 0; i < AST_MAX_FDS; i++) {
2246 if (ast_channel_internal_epfd_data(chan, i)) {
2247 ast_free(ast_channel_internal_epfd_data(chan, i));
2250 close(ast_channel_epfd(chan));
2252 while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2255 /* loop over the variables list, freeing all data and deleting list items */
2256 /* no need to lock the list, as the channel is already locked */
2257 headp = ast_channel_varshead(chan);
2258 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2259 ast_var_delete(vardata);
2261 ast_app_group_discard(chan);
2263 /* Destroy the jitterbuffer */
2264 ast_jb_destroy(chan);
2266 if (ast_channel_cdr(chan)) {
2267 ast_cdr_discard(ast_channel_cdr(chan));
2268 ast_channel_cdr_set(chan, NULL);
2271 if (ast_channel_zone(chan)) {
2272 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2275 ast_channel_internal_cleanup(chan);
2277 if (device_name[0]) {
2279 * We have a device name to notify of a new state.
2281 * Queue an unknown state, because, while we know that this particular
2282 * instance is dead, we don't know the state of all other possible
2285 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2288 ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2291 /*! \brief Free a dummy channel structure */
2292 static void ast_dummy_channel_destructor(void *obj)
2294 struct ast_channel *chan = obj;
2295 struct ast_var_t *vardata;
2296 struct varshead *headp;
2298 headp = ast_channel_varshead(chan);
2300 ast_party_dialed_free(ast_channel_dialed(chan));
2301 ast_party_caller_free(ast_channel_caller(chan));
2302 ast_party_connected_line_free(ast_channel_connected(chan));
2303 ast_party_redirecting_free(ast_channel_redirecting(chan));
2305 /* loop over the variables list, freeing all data and deleting list items */
2306 /* no need to lock the list, as the channel is already locked */
2307 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2308 ast_var_delete(vardata);
2310 if (ast_channel_cdr(chan)) {
2311 ast_cdr_discard(ast_channel_cdr(chan));
2312 ast_channel_cdr_set(chan, NULL);
2315 ast_channel_internal_cleanup(chan);
2318 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2320 return ast_datastore_alloc(info, uid);
2323 int ast_channel_datastore_free(struct ast_datastore *datastore)
2325 return ast_datastore_free(datastore);
2328 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2330 struct ast_datastore *datastore = NULL, *datastore2;
2332 AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2333 if (datastore->inheritance > 0) {
2334 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2336 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2337 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2338 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2345 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2349 AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2354 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2356 return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2359 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2361 struct ast_datastore *datastore = NULL;
2366 AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2367 if (datastore->info != info) {
2372 /* matched by type only */
2376 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2377 /* Matched by type AND uid */
2385 /*! Set the file descriptor on the channel */
2386 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2389 struct epoll_event ev;
2390 struct ast_epoll_data *aed = NULL;
2392 if (ast_channel_fd_isset(chan, which)) {
2393 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2394 aed = ast_channel_internal_epfd_data(chan, which);
2397 /* If this new fd is valid, add it to the epoll */
2399 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2402 ast_channel_internal_epfd_data_set(chan, which, aed);
2406 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2408 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2410 /* We don't have to keep around this epoll data structure now */
2412 ast_channel_epfd_data_set(chan, which, NULL);
2415 ast_channel_internal_fd_set(chan, which, fd);
2419 /*! Add a channel to an optimized waitfor */
2420 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2423 struct epoll_event ev;
2426 if (ast_channel_epfd(chan0) == -1)
2429 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2430 for (i = 0; i < AST_MAX_FDS; i++) {
2431 if (!ast_channel_fd_isset(chan1, i)) {
2434 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2435 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2436 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2443 /*! Delete a channel from an optimized waitfor */
2444 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2447 struct epoll_event ev;
2450 if (ast_channel_epfd(chan0) == -1)
2453 for (i = 0; i < AST_MAX_FDS; i++) {
2454 if (!ast_channel_fd_isset(chan1, i)) {
2457 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2464 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2466 ast_channel_lock(chan);
2468 ast_channel_softhangup_internal_flag_clear(chan, flag);
2470 if (!ast_channel_softhangup_internal_flag(chan)) {
2471 struct ast_frame *fr;
2473 /* If we have completely cleared the softhangup flag,
2474 * then we need to fully abort the hangup process. This requires
2475 * pulling the END_OF_Q frame out of the channel frame queue if it
2476 * still happens to be there. */
2478 fr = AST_LIST_LAST(ast_channel_readq(chan));
2479 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2480 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2481 AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2486 ast_channel_unlock(chan);
2489 /*! \brief Softly hangup a channel, don't lock */
2490 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2492 ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2493 /* Inform channel driver that we need to be hung up, if it cares */
2494 ast_channel_softhangup_internal_flag_add(chan, cause);
2495 ast_queue_frame(chan, &ast_null_frame);
2496 /* Interrupt any poll call or such */
2497 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2498 pthread_kill(ast_channel_blocker(chan), SIGURG);
2502 /*! \brief Softly hangup a channel, lock */
2503 int ast_softhangup(struct ast_channel *chan, int cause)
2507 ast_channel_lock(chan);
2508 res = ast_softhangup_nolock(chan, cause);
2509 manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2513 ast_channel_name(chan),
2514 ast_channel_uniqueid(chan),
2516 ast_channel_unlock(chan);
2521 static void free_translation(struct ast_channel *clonechan)
2523 if (ast_channel_writetrans(clonechan))
2524 ast_translator_free_path(ast_channel_writetrans(clonechan));
2525 if (ast_channel_readtrans(clonechan))
2526 ast_translator_free_path(ast_channel_readtrans(clonechan));
2527 ast_channel_writetrans_set(clonechan, NULL);
2528 ast_channel_readtrans_set(clonechan, NULL);
2529 if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2530 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2531 ast_format_clear(ast_channel_rawreadformat(clonechan));
2533 struct ast_format tmpfmt;
2534 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2535 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2536 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2540 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2542 struct ast_channel *bridge;
2544 ast_channel_lock(chan);
2545 if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2546 ast_channel_hangupsource_set(chan, source);
2548 bridge = ast_bridged_channel(chan);
2549 ast_channel_unlock(chan);
2551 if (bridge && (force || ast_strlen_zero(ast_channel_hangupsource(bridge)))) {
2552 ast_channel_lock(bridge);
2553 ast_channel_hangupsource_set(chan, source);
2554 ast_channel_unlock(bridge);
2558 static void destroy_hooks(struct ast_channel *chan)
2560 if (ast_channel_audiohooks(chan)) {
2561 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2562 ast_channel_audiohooks_set(chan, NULL);
2565 ast_framehook_list_destroy(chan);
2568 /*! \brief Hangup a channel */
2569 int ast_hangup(struct ast_channel *chan)
2571 char extra_str[64]; /* used for cel logging below */
2574 ast_autoservice_stop(chan);
2576 ast_channel_lock(chan);
2579 * Do the masquerade if someone is setup to masquerade into us.
2581 * NOTE: We must hold the channel lock after testing for a
2582 * pending masquerade and setting the channel as a zombie to
2583 * prevent __ast_channel_masquerade() from setting up a
2584 * masquerade with a dead channel.
2586 while (ast_channel_masq(chan)) {
2587 ast_channel_unlock(chan);
2588 if (ast_do_masquerade(chan)) {
2589 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2591 /* Abort the loop or we might never leave. */
2592 ast_channel_lock(chan);
2595 ast_channel_lock(chan);
2598 if (ast_channel_masqr(chan)) {
2600 * This channel is one which will be masqueraded into something.
2601 * Mark it as a zombie already so ast_do_masquerade() will know
2604 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2605 destroy_hooks(chan);
2606 ast_channel_unlock(chan);
2610 if (!(was_zombie = ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE))) {
2611 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2614 ast_channel_unlock(chan);
2615 ao2_unlink(channels, chan);
2616 ast_channel_lock(chan);
2618 destroy_hooks(chan);
2620 free_translation(chan);
2621 /* Close audio stream */
2622 if (ast_channel_stream(chan)) {
2623 ast_closestream(ast_channel_stream(chan));
2624 ast_channel_stream_set(chan, NULL);
2626 /* Close video stream */
2627 if (ast_channel_vstream(chan)) {
2628 ast_closestream(ast_channel_vstream(chan));
2629 ast_channel_vstream_set(chan, NULL);
2631 if (ast_channel_sched(chan)) {
2632 ast_sched_context_destroy(ast_channel_sched(chan));
2633 ast_channel_sched_set(chan, NULL);
2636 if (ast_channel_generatordata(chan)) { /* Clear any tone stuff remaining */
2637 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2638 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2641 ast_channel_generatordata_set(chan, NULL);
2642 ast_channel_generator_set(chan, NULL);
2644 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"), ""));
2645 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2647 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2648 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2649 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2650 (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2651 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2654 ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2656 if (ast_channel_tech(chan)->hangup) {
2657 ast_channel_tech(chan)->hangup(chan);
2660 ast_debug(1, "Hanging up zombie '%s'\n", ast_channel_name(chan));
2663 ast_channel_unlock(chan);
2666 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2669 "CallerIDNum: %s\r\n"
2670 "CallerIDName: %s\r\n"
2671 "ConnectedLineNum: %s\r\n"
2672 "ConnectedLineName: %s\r\n"
2674 "Cause-txt: %s\r\n",
2675 ast_channel_name(chan),
2676 ast_channel_uniqueid(chan),
2677 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
2678 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
2679 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
2680 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
2681 ast_channel_hangupcause(chan),
2682 ast_cause2str(ast_channel_hangupcause(chan))
2685 if (ast_channel_cdr(chan) && !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_BRIDGED) &&
2686 !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_POST_DISABLED) &&
2687 (ast_channel_cdr(chan)->disposition != AST_CDR_NULL || ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_DIALED))) {
2688 ast_channel_lock(chan);
2689 ast_cdr_end(ast_channel_cdr(chan));
2690 ast_cdr_detach(ast_channel_cdr(chan));
2691 ast_channel_cdr_set(chan, NULL);
2692 ast_channel_unlock(chan);
2695 ast_channel_unref(chan);
2700 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2704 ast_channel_lock(chan);
2706 /* You can't answer an outbound call */
2707 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2708 ast_channel_unlock(chan);
2712 /* Stop if we're a zombie or need a soft hangup */
2713 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2714 ast_channel_unlock(chan);
2718 ast_channel_unlock(chan);
2720 switch (ast_channel_state(chan)) {
2721 case AST_STATE_RINGING:
2722 case AST_STATE_RING:
2723 ast_channel_lock(chan);
2724 if (ast_channel_tech(chan)->answer) {
2725 res = ast_channel_tech(chan)->answer(chan);
2727 ast_setstate(chan, AST_STATE_UP);
2729 ast_cdr_answer(ast_channel_cdr(chan));
2731 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2732 ast_channel_unlock(chan);
2735 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2736 /* Calling ast_cdr_answer when it it has previously been called
2737 * is essentially a no-op, so it is safe.
2740 ast_cdr_answer(ast_channel_cdr(chan));
2747 ast_indicate(chan, -1);
2752 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2755 enum ast_channel_state old_state;
2757 old_state = ast_channel_state(chan);
2758 if ((res = ast_raw_answer(chan, cdr_answer))) {
2762 switch (old_state) {
2763 case AST_STATE_RINGING:
2764 case AST_STATE_RING:
2765 /* wait for media to start flowing, but don't wait any longer
2766 * than 'delay' or 500 milliseconds, whichever is longer
2769 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2770 struct ast_frame *cur, *new;
2771 int ms = MAX(delay, 500);
2772 unsigned int done = 0;
2774 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2777 ms = ast_waitfor(chan, ms);
2779 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2784 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));
2787 cur = ast_read(chan);
2788 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2789 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2794 ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2798 if ((new = ast_frisolate(cur)) != cur) {
2802 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2804 /* if a specific delay period was requested, continue
2805 * until that delay has passed. don't stop just because
2806 * incoming media has arrived.
2812 switch (new->frametype) {
2813 /* all of these frametypes qualify as 'media' */
2814 case AST_FRAME_VOICE:
2815 case AST_FRAME_VIDEO:
2816 case AST_FRAME_TEXT:
2817 case AST_FRAME_DTMF_BEGIN:
2818 case AST_FRAME_DTMF_END:
2819 case AST_FRAME_IMAGE:
2820 case AST_FRAME_HTML:
2821 case AST_FRAME_MODEM:
2824 case AST_FRAME_CONTROL:
2826 case AST_FRAME_NULL:
2837 ast_channel_lock(chan);
2838 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2839 ast_queue_frame_head(chan, cur);
2842 ast_channel_unlock(chan);
2853 int ast_answer(struct ast_channel *chan)
2855 return __ast_answer(chan, 0, 1);
2858 void ast_deactivate_generator(struct ast_channel *chan)
2860 ast_channel_lock(chan);
2861 if (ast_channel_generatordata(chan)) {
2862 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2863 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2865 ast_channel_generatordata_set(chan, NULL);
2866 ast_channel_generator_set(chan, NULL);
2867 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2868 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
2869 ast_settimeout(chan, 0, NULL, NULL);
2871 ast_channel_unlock(chan);
2874 static void generator_write_format_change(struct ast_channel *chan)
2876 ast_channel_lock(chan);
2877 if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
2878 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
2880 ast_channel_unlock(chan);
2883 static int generator_force(const void *data)
2885 /* Called if generator doesn't have data */
2888 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2889 struct ast_channel *chan = (struct ast_channel *)data;
2891 ast_channel_lock(chan);
2892 tmp = ast_channel_generatordata(chan);
2893 ast_channel_generatordata_set(chan, NULL);
2894 if (ast_channel_generator(chan))
2895 generate = ast_channel_generator(chan)->generate;
2896 ast_channel_unlock(chan);
2898 if (!tmp || !generate)
2901 res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
2903 ast_channel_generatordata_set(chan, tmp);
2906 ast_debug(1, "Auto-deactivating generator\n");
2907 ast_deactivate_generator(chan);
2913 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2916 void *generatordata = NULL;
2918 ast_channel_lock(chan);
2919 if (ast_channel_generatordata(chan)) {
2920 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2921 ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2924 if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
2927 ast_channel_generatordata_set(chan, generatordata);
2929 ast_settimeout(chan, 50, generator_force, chan);
2930 ast_channel_generator_set(chan, gen);
2932 ast_channel_unlock(chan);
2939 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2940 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2943 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2947 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2949 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2950 int *exception, int *outfd, int *ms)
2952 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2953 int *exception, int *outfd, int *ms)
2956 struct timeval start = { 0 , 0 };
2957 struct pollfd *pfds = NULL;
2962 struct timeval now = { 0, 0 };
2963 struct timeval whentohangup = { 0, 0 }, diff;
2964 struct ast_channel *winner = NULL;
2977 if ((sz = n * AST_MAX_FDS + nfds)) {
2978 pfds = alloca(sizeof(*pfds) * sz);
2979 fdmap = alloca(sizeof(*fdmap) * sz);
2981 /* nothing to allocate and no FDs to check */
2985 /* Perform any pending masquerades */
2986 for (x = 0; x < n; x++) {
2987 if (ast_channel_masq(c[x]) && ast_do_masquerade(c[x])) {
2988 ast_log(LOG_WARNING, "Masquerade failed\n");
2993 ast_channel_lock(c[x]);
2994 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
2995 if (ast_tvzero(whentohangup))
2997 diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
2998 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
2999 /* Should already be hungup */
3000 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3001 ast_channel_unlock(c[x]);
3004 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3005 whentohangup = diff;
3007 ast_channel_unlock(c[x]);
3009 /* Wait full interval */
3011 /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3012 if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3013 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
3014 if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
3017 } else if (!ast_tvzero(whentohangup) && rms < 0) {
3018 /* Tiny corner case... call would need to last >24 days */
3022 * Build the pollfd array, putting the channels' fds first,
3023 * followed by individual fds. Order is important because
3024 * individual fd's must have priority over channel fds.
3027 for (x = 0; x < n; x++) {
3028 for (y = 0; y < AST_MAX_FDS; y++) {
3029 fdmap[max].fdno = y; /* fd y is linked to this pfds */
3030 fdmap[max].chan = x; /* channel x is linked to this pfds */
3031 max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3033 CHECK_BLOCKING(c[x]);
3035 /* Add the individual fds */
3036 for (x = 0; x < nfds; x++) {
3037 fdmap[max].chan = -1;
3038 max += ast_add_fd(&pfds[max], fds[x]);
3042 start = ast_tvnow();
3045 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3048 if (kbrms > 600000) {
3051 res = ast_poll(pfds, max, kbrms);
3055 } while (!res && (rms > 0));
3057 res = ast_poll(pfds, max, rms);
3059 for (x = 0; x < n; x++) {
3060 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3062 if (res < 0) { /* Simulate a timeout if we were interrupted */
3063 if (errno != EINTR) {
3068 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
3070 for (x = 0; x < n; x++) {
3071 if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3072 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3073 if (winner == NULL) {
3079 if (res == 0) { /* no fd ready, reset timeout and done */
3080 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
3084 * Then check if any channel or fd has a pending event.
3085 * Remember to check channels first and fds last, as they
3086 * must have priority on setting 'winner'
3088 for (x = 0; x < max; x++) {
3089 res = pfds[x].revents;
3093 if (fdmap[x].chan >= 0) { /* this is a channel */
3094 winner = c[fdmap[x].chan]; /* override previous winners */
3095 if (res & POLLPRI) {
3096 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3098 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3100 ast_channel_fdno_set(winner, fdmap[x].fdno);
3101 } else { /* this is an fd */
3103 *outfd = pfds[x].fd;
3106 *exception = (res & POLLPRI) ? -1 : 0;
3112 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3121 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3123 struct timeval start = { 0 , 0 };
3125 struct epoll_event ev[1];
3126 long diff, rms = *ms;
3127 struct ast_channel *winner = NULL;
3128 struct ast_epoll_data *aed = NULL;
3131 /* See if this channel needs to be masqueraded */
3132 if (ast_channel_masq(chan) && ast_do_masquerade(chan)) {
3133 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", ast_channel_name(chan));
3138 ast_channel_lock(chan);
3139 /* Figure out their timeout */
3140 if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3141 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow())) < 0) {
3142 /* They should already be hungup! */
3143 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3144 ast_channel_unlock(chan);
3147 /* If this value is smaller then the current one... make it priority */
3153 ast_channel_unlock(chan);
3155 /* Time to make this channel block... */
3156 CHECK_BLOCKING(chan);
3159 start = ast_tvnow();
3162 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3163 res = epoll_wait(ast_channel_epfd(chan), ev, 1, rms);
3166 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
3168 /* Simulate a timeout if we were interrupted */
3170 if (errno != EINTR) {
3176 /* If this channel has a timeout see if it expired */
3177 if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3178 if (ast_tvdiff_ms(ast_tvnow(), *ast_channel_whentohangup(chan)) >= 0) {
3179 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3184 /* No fd ready, reset timeout and be done for now */
3190 /* See what events are pending */
3191 aed = ev[0].data.ptr;
3192 ast_channel_fdno_set(chan, aed->which);
3193 if (ev[0].events & EPOLLPRI) {
3194 ast_set_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3196 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3200 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3209 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3211 struct timeval start = { 0 , 0 };
3213 struct epoll_event ev[25] = { { 0, } };
3214 struct timeval now = { 0, 0 };
3215 long whentohangup = 0, diff = 0, rms = *ms;
3216 struct ast_channel *winner = NULL;
3218 for (i = 0; i < n; i++) {
3219 if (ast_channel_masq(c[i]) && ast_do_masquerade(c[i])) {
3220 ast_log(LOG_WARNING, "Masquerade failed\n");
3225 ast_channel_lock(c[i]);
3226 if (!ast_tvzero(*ast_channel_whentohangup(c[i]))) {
3227 if (whentohangup == 0) {
3230 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(c[i]), now)) < 0) {
3231 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3232 ast_channel_unlock(c[i]);
3235 if (!whentohangup || whentohangup > diff) {
3236 whentohangup = diff;
3239 ast_channel_unlock(c[i]);
3240 CHECK_BLOCKING(c[i]);
3246 if (*ms >= 0 && *ms < rms) {
3252 start = ast_tvnow();
3255 res = epoll_wait(ast_channel_epfd(c[0]), ev, 25, rms);
3257 for (i = 0; i < n; i++) {
3258 ast_clear_flag(ast_channel_flags(c[i]), AST_FLAG_BLOCKING);
3262 if (errno != EINTR) {
3270 for (i = 0; i < n; i++) {
3271 if (!ast_tvzero(*ast_channel_whentohangup(c[i])) && ast_tvdiff_ms(now, *ast_channel_whentohangup(c[i])) >= 0) {
3272 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3285 for (i = 0; i < res; i++) {
3286 struct ast_epoll_data *aed = ev[i].data.ptr;
3288 if (!ev[i].events || !aed) {
3293 if (ev[i].events & EPOLLPRI) {
3294 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3296 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3298 ast_channel_fdno_set(winner, aed->which);
3302 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3311 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3312 int *exception, int *outfd, int *ms)
3314 /* Clear all provided values in one place. */
3322 /* If no epoll file descriptor is available resort to classic nandfds */
3323 if (!n || nfds || ast_channel_epfd(c[0]) == -1) {
3324 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3325 } else if (!nfds && n == 1) {
3326 return ast_waitfor_nandfds_simple(c[0], ms);
3328 return ast_waitfor_nandfds_complex(c, n, ms);
3333 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3335 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3338 int ast_waitfor(struct ast_channel *c, int ms)
3340 int oldms = ms; /* -1 if no timeout */
3342 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3343 if ((ms < 0) && (oldms < 0)) {
3349 /* XXX never to be called with ms = -1 */
3350 int ast_waitfordigit(struct ast_channel *c, int ms)
3352 return ast_waitfordigit_full(c, ms, -1, -1);