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"
72 #include <sys/epoll.h>
75 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
78 #endif /* defined(HAVE_PRI) */
79 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
81 struct ast_epoll_data {
82 struct ast_channel *chan;
86 /* uncomment if you have problems with 'monitoring' synchronized files */
88 #define MONITOR_CONSTANT_DELAY
89 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
92 /*! \brief Prevent new channel allocation if shutting down. */
93 static int shutting_down;
97 unsigned long global_fin, global_fout;
99 AST_THREADSTORAGE(state2str_threadbuf);
100 #define STATE2STR_BUFSIZE 32
102 /*! Default amount of time to use when emulating a digit as a begin and end
104 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
106 /*! Minimum allowed digit length - 80ms */
107 #define AST_MIN_DTMF_DURATION 80
109 /*! Minimum amount of time between the end of the last digit and the beginning
110 * of a new one - 45ms */
111 #define AST_MIN_DTMF_GAP 45
113 /*! \brief List of channel drivers */
115 const struct ast_channel_tech *tech;
116 AST_LIST_ENTRY(chanlist) list;
120 /*! \brief Structure to hold channel context backtrace data */
121 struct ast_chan_trace_data {
123 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
126 /*! \brief Structure to save contexts where an ast_chan has been into */
127 struct ast_chan_trace {
128 char context[AST_MAX_CONTEXT];
129 char exten[AST_MAX_EXTENSION];
131 AST_LIST_ENTRY(ast_chan_trace) entry;
135 /*! \brief the list of registered channel types */
136 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
139 #define NUM_CHANNEL_BUCKETS 61
141 #define NUM_CHANNEL_BUCKETS 1567
144 /*! \brief All active channels on the system */
145 static struct ao2_container *channels;
147 /*! \brief map AST_CAUSE's to readable string representations
151 static const struct {
156 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
157 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
158 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
159 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
160 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
161 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
162 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
163 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
164 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
165 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
166 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
167 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
168 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
169 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
170 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
171 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
172 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
173 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
174 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
175 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
176 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
177 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
178 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
179 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
180 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
181 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
182 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
183 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
184 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
185 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
186 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
187 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
188 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
189 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
190 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
191 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
192 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
193 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
194 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
195 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
196 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
197 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
198 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
199 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
202 struct ast_variable *ast_channeltype_list(void)
205 struct ast_variable *var = NULL, *prev = NULL;
207 AST_RWLIST_RDLOCK(&backends);
208 AST_RWLIST_TRAVERSE(&backends, cl, list) {
210 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
213 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
217 AST_RWLIST_UNLOCK(&backends);
222 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
223 static const char *party_number_ton2str(int ton)
225 #if defined(HAVE_PRI)
226 switch ((ton >> 4) & 0x07) {
227 case PRI_TON_INTERNATIONAL:
228 return "International";
229 case PRI_TON_NATIONAL:
231 case PRI_TON_NET_SPECIFIC:
232 return "Network Specific";
233 case PRI_TON_SUBSCRIBER:
235 case PRI_TON_ABBREVIATED:
236 return "Abbreviated";
237 case PRI_TON_RESERVED:
239 case PRI_TON_UNKNOWN:
243 #endif /* defined(HAVE_PRI) */
246 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
248 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
249 static const char *party_number_plan2str(int plan)
251 #if defined(HAVE_PRI)
252 switch (plan & 0x0F) {
254 case PRI_NPI_UNKNOWN:
256 case PRI_NPI_E163_E164:
257 return "Public (E.163/E.164)";
259 return "Data (X.121)";
261 return "Telex (F.69)";
262 case PRI_NPI_NATIONAL:
263 return "National Standard";
264 case PRI_NPI_PRIVATE:
266 case PRI_NPI_RESERVED:
269 #endif /* defined(HAVE_PRI) */
272 #endif /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
274 /*! \brief Show channel types - CLI command */
275 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
277 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
283 e->command = "core show channeltypes";
285 "Usage: core show channeltypes\n"
286 " Lists available channel types registered in your\n"
287 " Asterisk server.\n";
294 return CLI_SHOWUSAGE;
296 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
297 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
299 AST_RWLIST_RDLOCK(&backends);
300 AST_RWLIST_TRAVERSE(&backends, cl, list) {
301 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
302 (cl->tech->devicestate) ? "yes" : "no",
303 (cl->tech->indicate) ? "yes" : "no",
304 (cl->tech->transfer) ? "yes" : "no");
307 AST_RWLIST_UNLOCK(&backends);
309 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
316 static char *complete_channeltypes(struct ast_cli_args *a)
326 wordlen = strlen(a->word);
328 AST_RWLIST_RDLOCK(&backends);
329 AST_RWLIST_TRAVERSE(&backends, cl, list) {
330 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
331 ret = ast_strdup(cl->tech->type);
335 AST_RWLIST_UNLOCK(&backends);
340 /*! \brief Show details about a channel driver - CLI command */
341 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
343 struct chanlist *cl = NULL;
348 e->command = "core show channeltype";
350 "Usage: core show channeltype <name>\n"
351 " Show details about the specified channel type, <name>.\n";
354 return complete_channeltypes(a);
358 return CLI_SHOWUSAGE;
360 AST_RWLIST_RDLOCK(&backends);
362 AST_RWLIST_TRAVERSE(&backends, cl, list) {
363 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
369 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
370 AST_RWLIST_UNLOCK(&backends);
375 "-- Info about channel driver: %s --\n"
376 " Device State: %s\n"
379 " Capabilities: %s\n"
383 " Image Support: %s\n"
384 " Text Support: %s\n",
386 (cl->tech->devicestate) ? "yes" : "no",
387 (cl->tech->indicate) ? "yes" : "no",
388 (cl->tech->transfer) ? "yes" : "no",
389 ast_getformatname_multiple(buf, sizeof(buf), cl->tech->capabilities),
390 (cl->tech->send_digit_begin) ? "yes" : "no",
391 (cl->tech->send_digit_end) ? "yes" : "no",
392 (cl->tech->send_html) ? "yes" : "no",
393 (cl->tech->send_image) ? "yes" : "no",
394 (cl->tech->send_text) ? "yes" : "no"
398 AST_RWLIST_UNLOCK(&backends);
403 static struct ast_cli_entry cli_channel[] = {
404 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
405 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
408 static struct ast_frame *kill_read(struct ast_channel *chan)
410 /* Hangup channel. */
414 static struct ast_frame *kill_exception(struct ast_channel *chan)
416 /* Hangup channel. */
420 static int kill_write(struct ast_channel *chan, struct ast_frame *frame)
422 /* Hangup channel. */
426 static int kill_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
428 /* No problem fixing up the channel. */
432 static int kill_hangup(struct ast_channel *chan)
434 chan->tech_pvt = NULL;
439 * \brief Kill the channel channel driver technology descriptor.
442 * The purpose of this channel technology is to encourage the
443 * channel to hangup as quickly as possible.
445 * \note Used by DTMF atxfer and zombie channels.
447 const struct ast_channel_tech ast_kill_tech = {
449 .description = "Kill channel (should not see this)",
451 .exception = kill_exception,
454 .hangup = kill_hangup,
458 /*! \brief Destructor for the channel trace datastore */
459 static void ast_chan_trace_destroy_cb(void *data)
461 struct ast_chan_trace *trace;
462 struct ast_chan_trace_data *traced = data;
463 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
469 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
470 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
472 .destroy = ast_chan_trace_destroy_cb
475 /*! \brief Put the channel backtrace in a string */
476 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
479 struct ast_chan_trace *trace;
480 struct ast_chan_trace_data *traced;
481 struct ast_datastore *store;
483 ast_channel_lock(chan);
484 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
486 ast_channel_unlock(chan);
489 traced = store->data;
491 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
492 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
493 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
499 ast_channel_unlock(chan);
503 /* !\brief Whether or not context tracing is enabled */
504 int ast_channel_trace_is_enabled(struct ast_channel *chan)
506 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
509 return ((struct ast_chan_trace_data *)store->data)->enabled;
512 /*! \brief Update the context backtrace data if tracing is enabled */
513 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
515 struct ast_chan_trace *trace;
516 if (!traced->enabled)
518 /* If the last saved context does not match the current one
519 OR we have not saved any context so far, then save the current context */
520 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) ||
521 (AST_LIST_EMPTY(&traced->trace))) {
522 /* Just do some debug logging */
523 if (AST_LIST_EMPTY(&traced->trace))
524 ast_debug(1, "Setting initial trace context to %s\n", chan->context);
526 ast_debug(1, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
527 /* alloc or bail out */
528 trace = ast_malloc(sizeof(*trace));
531 /* save the current location and store it in the trace list */
532 ast_copy_string(trace->context, chan->context, sizeof(trace->context));
533 ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
534 trace->priority = chan->priority;
535 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
540 /*! \brief Update the context backtrace if tracing is enabled */
541 int ast_channel_trace_update(struct ast_channel *chan)
543 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
546 return ast_channel_trace_data_update(chan, store->data);
549 /*! \brief Enable context tracing in the channel */
550 int ast_channel_trace_enable(struct ast_channel *chan)
552 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
553 struct ast_chan_trace_data *traced;
555 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
558 traced = ast_calloc(1, sizeof(*traced));
560 ast_datastore_free(store);
563 store->data = traced;
564 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
565 ast_channel_datastore_add(chan, store);
567 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
568 ast_channel_trace_data_update(chan, store->data);
572 /*! \brief Disable context tracing in the channel */
573 int ast_channel_trace_disable(struct ast_channel *chan)
575 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
578 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
581 #endif /* CHANNEL_TRACE */
583 /*! \brief Checks to see if a channel is needing hang up */
584 int ast_check_hangup(struct ast_channel *chan)
586 if (chan->_softhangup) /* yes if soft hangup flag set */
588 if (ast_tvzero(chan->whentohangup)) /* no if no hangup scheduled */
590 if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0) /* no if hangup time has not come yet. */
592 ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(chan->whentohangup, ast_tvnow()));
593 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
597 int ast_check_hangup_locked(struct ast_channel *chan)
600 ast_channel_lock(chan);
601 res = ast_check_hangup(chan);
602 ast_channel_unlock(chan);
606 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
608 struct ast_channel *chan = obj;
610 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
615 void ast_begin_shutdown(int hangup)
620 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
624 /*! \brief returns number of active/allocated channels */
625 int ast_active_channels(void)
627 return channels ? ao2_container_count(channels) : 0;
630 /*! \brief Cancel a shutdown in progress */
631 void ast_cancel_shutdown(void)
636 /*! \brief Returns non-zero if Asterisk is being shut down */
637 int ast_shutting_down(void)
639 return shutting_down;
642 /*! \brief Set when to hangup channel */
643 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
645 chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
646 ast_queue_frame(chan, &ast_null_frame);
650 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
652 struct timeval when = { offset, };
653 ast_channel_setwhentohangup_tv(chan, when);
656 /*! \brief Compare a offset with when to hangup channel */
657 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
659 struct timeval whentohangup;
661 if (ast_tvzero(chan->whentohangup))
662 return ast_tvzero(offset) ? 0 : -1;
664 if (ast_tvzero(offset))
667 whentohangup = ast_tvadd(offset, ast_tvnow());
669 return ast_tvdiff_ms(whentohangup, chan->whentohangup);
672 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
674 struct timeval when = { offset, };
675 return ast_channel_cmpwhentohangup_tv(chan, when);
678 /*! \brief Register a new telephony channel in Asterisk */
679 int ast_channel_register(const struct ast_channel_tech *tech)
681 struct chanlist *chan;
683 AST_RWLIST_WRLOCK(&backends);
685 AST_RWLIST_TRAVERSE(&backends, chan, list) {
686 if (!strcasecmp(tech->type, chan->tech->type)) {
687 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
688 AST_RWLIST_UNLOCK(&backends);
693 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
694 AST_RWLIST_UNLOCK(&backends);
698 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
700 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
702 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
704 AST_RWLIST_UNLOCK(&backends);
709 /*! \brief Unregister channel driver */
710 void ast_channel_unregister(const struct ast_channel_tech *tech)
712 struct chanlist *chan;
714 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
716 AST_RWLIST_WRLOCK(&backends);
718 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
719 if (chan->tech == tech) {
720 AST_LIST_REMOVE_CURRENT(list);
722 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
726 AST_LIST_TRAVERSE_SAFE_END;
728 AST_RWLIST_UNLOCK(&backends);
731 /*! \brief Get handle to channel driver based on name */
732 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
734 struct chanlist *chanls;
735 const struct ast_channel_tech *ret = NULL;
737 AST_RWLIST_RDLOCK(&backends);
739 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
740 if (!strcasecmp(name, chanls->tech->type)) {
746 AST_RWLIST_UNLOCK(&backends);
751 /*! \brief Gives the string form of a given hangup cause */
752 const char *ast_cause2str(int cause)
756 for (x = 0; x < ARRAY_LEN(causes); x++) {
757 if (causes[x].cause == cause)
758 return causes[x].desc;
764 /*! \brief Convert a symbolic hangup cause to number */
765 int ast_str2cause(const char *name)
769 for (x = 0; x < ARRAY_LEN(causes); x++)
770 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
771 return causes[x].cause;
776 /*! \brief Gives the string form of a given channel state.
777 \note This function is not reentrant.
779 const char *ast_state2str(enum ast_channel_state state)
786 case AST_STATE_RESERVED:
788 case AST_STATE_OFFHOOK:
790 case AST_STATE_DIALING:
794 case AST_STATE_RINGING:
800 case AST_STATE_DIALING_OFFHOOK:
801 return "Dialing Offhook";
802 case AST_STATE_PRERING:
805 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
807 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
812 /*! \brief Gives the string form of a given transfer capability */
813 char *ast_transfercapability2str(int transfercapability)
815 switch (transfercapability) {
816 case AST_TRANS_CAP_SPEECH:
818 case AST_TRANS_CAP_DIGITAL:
820 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
821 return "RESTRICTED_DIGITAL";
822 case AST_TRANS_CAP_3_1K_AUDIO:
824 case AST_TRANS_CAP_DIGITAL_W_TONES:
825 return "DIGITAL_W_TONES";
826 case AST_TRANS_CAP_VIDEO:
833 /*! \brief Pick the best audio codec */
834 struct ast_format *ast_best_codec(struct ast_format_cap *cap, struct ast_format *result)
836 /* This just our opinion, expressed in code. We are asked to choose
837 the best codec to use, given no information */
838 static const enum ast_format_id prefs[] =
840 /*! Okay, ulaw is used by all telephony equipment, so start with it */
842 /*! Unless of course, you're a silly European, so then prefer ALAW */
848 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
850 /*! Okay, well, signed linear is easy to translate into other stuff */
851 AST_FORMAT_SLINEAR192,
852 AST_FORMAT_SLINEAR96,
853 AST_FORMAT_SLINEAR48,
854 AST_FORMAT_SLINEAR44,
855 AST_FORMAT_SLINEAR32,
856 AST_FORMAT_SLINEAR24,
857 AST_FORMAT_SLINEAR16,
858 AST_FORMAT_SLINEAR12,
860 /*! G.726 is standard ADPCM, in RFC3551 packing order */
862 /*! G.726 is standard ADPCM, in AAL2 packing order */
863 AST_FORMAT_G726_AAL2,
864 /*! ADPCM has great sound quality and is still pretty easy to translate */
866 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
867 translate and sounds pretty good */
869 /*! iLBC is not too bad */
871 /*! Speex is free, but computationally more expensive than GSM */
875 /*! SILK is pretty awesome. */
877 /*! CELT supports crazy high sample rates */
879 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
882 /*! G.729a is faster than 723 and slightly less expensive */
884 /*! Down to G.723.1 which is proprietary but at least designed for voice */
890 /* Find the first preferred codec in the format given */
891 for (x = 0; x < ARRAY_LEN(prefs); x++) {
892 if (ast_format_cap_best_byid(cap, prefs[x], result)) {
897 ast_format_clear(result);
898 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
903 static const struct ast_channel_tech null_tech = {
905 .description = "Null channel (should not see this)",
908 static void ast_channel_destructor(void *obj);
909 static void ast_dummy_channel_destructor(void *obj);
911 /*! \brief Create a new channel structure */
912 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
913 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
914 const char *acctcode, const char *exten, const char *context,
915 const char *linkedid, const int amaflag, const char *file, int line,
916 const char *function, const char *name_fmt, va_list ap)
918 struct ast_channel *tmp;
921 struct varshead *headp;
922 char *tech = "", *tech2 = NULL;
924 /* If shutting down, don't allocate any new channels */
926 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
930 #if defined(REF_DEBUG)
931 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
933 #elif defined(__AST_DEBUG_MALLOC)
934 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
937 tmp = ao2_alloc(sizeof(*tmp), ast_channel_destructor);
940 /* Channel structure allocation failure. */
943 if (!(tmp->nativeformats = ast_format_cap_alloc())) {
945 /* format capabilities structure allocation failure */
950 * Init file descriptors to unopened state so
951 * the destructor can know not to close them.
954 for (x = 0; x < ARRAY_LEN(tmp->alertpipe); ++x) {
955 tmp->alertpipe[x] = -1;
957 for (x = 0; x < ARRAY_LEN(tmp->fds); ++x) {
961 tmp->epfd = epoll_create(25);
964 if (!(tmp->sched = ast_sched_context_create())) {
965 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
966 return ast_channel_unref(tmp);
969 ast_party_dialed_init(&tmp->dialed);
970 ast_party_caller_init(&tmp->caller);
971 ast_party_connected_line_init(&tmp->connected);
972 ast_party_redirecting_init(&tmp->redirecting);
975 tmp->caller.id.name.valid = 1;
976 tmp->caller.id.name.str = ast_strdup(cid_name);
977 if (!tmp->caller.id.name.str) {
978 return ast_channel_unref(tmp);
982 tmp->caller.id.number.valid = 1;
983 tmp->caller.id.number.str = ast_strdup(cid_num);
984 if (!tmp->caller.id.number.str) {
985 return ast_channel_unref(tmp);
989 if ((tmp->timer = ast_timer_open())) {
990 if (strcmp(ast_timer_get_name(tmp->timer), "timerfd")) {
993 tmp->timingfd = ast_timer_fd(tmp->timer);
997 if (pipe(tmp->alertpipe)) {
998 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
999 return ast_channel_unref(tmp);
1001 flags = fcntl(tmp->alertpipe[0], F_GETFL);
1002 if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
1003 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1004 return ast_channel_unref(tmp);
1006 flags = fcntl(tmp->alertpipe[1], F_GETFL);
1007 if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
1008 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1009 return ast_channel_unref(tmp);
1015 * This is the last place the channel constructor can fail.
1017 * The destructor takes advantage of this fact to ensure that the
1018 * AST_CEL_CHANNEL_END is not posted if we have not posted the
1019 * AST_CEL_CHANNEL_START yet.
1021 if ((ast_string_field_init(tmp, 128))) {
1022 return ast_channel_unref(tmp);
1025 /* Always watch the alertpipe */
1026 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
1027 /* And timing pipe */
1028 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
1031 tmp->_state = state;
1035 tmp->fin = global_fin;
1036 tmp->fout = global_fout;
1038 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1039 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
1040 ast_atomic_fetchadd_int(&uniqueint, 1));
1042 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
1043 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1046 if (!ast_strlen_zero(linkedid)) {
1047 ast_string_field_set(tmp, linkedid, linkedid);
1049 ast_string_field_set(tmp, linkedid, tmp->uniqueid);
1052 if (!ast_strlen_zero(name_fmt)) {
1053 char *slash, *slash2;
1054 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1055 * And they all use slightly different formats for their name string.
1056 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1057 * This means, that the stringfields must have a routine that takes the va_lists directly, and
1058 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1059 * This new function was written so this can be accomplished.
1061 ast_channel_name_set_va(tmp, name_fmt, ap);
1062 tech = ast_strdupa(ast_channel_name(tmp));
1063 if ((slash = strchr(tech, '/'))) {
1064 if ((slash2 = strchr(slash + 1, '/'))) {
1072 * Start the string with '-' so it becomes an empty string
1073 * in the destructor.
1075 ast_channel_name_set(tmp, "-**Unknown**");
1078 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1080 /* These 4 variables need to be set up for the cdr_init() to work right */
1082 tmp->amaflags = amaflag;
1084 tmp->amaflags = ast_default_amaflags;
1086 if (!ast_strlen_zero(acctcode))
1087 ast_string_field_set(tmp, accountcode, acctcode);
1089 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
1091 if (!ast_strlen_zero(context))
1092 ast_copy_string(tmp->context, context, sizeof(tmp->context));
1094 strcpy(tmp->context, "default");
1096 if (!ast_strlen_zero(exten))
1097 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
1099 strcpy(tmp->exten, "s");
1103 tmp->cdr = ast_cdr_alloc();
1104 ast_cdr_init(tmp->cdr, tmp);
1105 ast_cdr_start(tmp->cdr);
1107 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1109 headp = &tmp->varshead;
1110 AST_LIST_HEAD_INIT_NOLOCK(headp);
1112 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
1114 AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
1116 ast_string_field_set(tmp, language, defaultlanguage);
1118 tmp->tech = &null_tech;
1120 ao2_link(channels, tmp);
1123 * And now, since the channel structure is built, and has its name, let's
1124 * call the manager event generator with this Newchannel event. This is the
1125 * proper and correct place to make this call, but you sure do have to pass
1126 * a lot of data into this func to do it here!
1128 if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1129 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1131 "ChannelState: %d\r\n"
1132 "ChannelStateDesc: %s\r\n"
1133 "CallerIDNum: %s\r\n"
1134 "CallerIDName: %s\r\n"
1135 "AccountCode: %s\r\n"
1139 ast_channel_name(tmp),
1141 ast_state2str(state),
1153 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1154 const char *cid_name, const char *acctcode,
1155 const char *exten, const char *context,
1156 const char *linkedid, const int amaflag,
1157 const char *file, int line, const char *function,
1158 const char *name_fmt, ...)
1161 struct ast_channel *result;
1163 va_start(ap, name_fmt);
1164 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1165 linkedid, amaflag, file, line, function, name_fmt, ap);
1171 /* only do the minimum amount of work needed here to make a channel
1172 * structure that can be used to expand channel vars */
1173 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1174 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1176 struct ast_channel *ast_dummy_channel_alloc(void)
1179 struct ast_channel *tmp;
1180 struct varshead *headp;
1182 #if defined(REF_DEBUG)
1183 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1184 file, line, function, 1);
1185 #elif defined(__AST_DEBUG_MALLOC)
1186 tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1187 file, line, function, 0);
1189 tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor);
1192 /* Dummy channel structure allocation failure. */
1196 if ((ast_string_field_init(tmp, 128))) {
1197 return ast_channel_unref(tmp);
1200 headp = &tmp->varshead;
1201 AST_LIST_HEAD_INIT_NOLOCK(headp);
1206 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1208 struct ast_frame *f;
1209 struct ast_frame *cur;
1210 unsigned int new_frames = 0;
1211 unsigned int new_voice_frames = 0;
1212 unsigned int queued_frames = 0;
1213 unsigned int queued_voice_frames = 0;
1214 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1216 ast_channel_lock(chan);
1219 * Check the last frame on the queue if we are queuing the new
1222 cur = AST_LIST_LAST(&chan->readq);
1223 if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1224 switch (cur->subclass.integer) {
1225 case AST_CONTROL_END_OF_Q:
1226 if (fin->frametype == AST_FRAME_CONTROL
1227 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1229 * Destroy the end-of-Q marker frame so we can queue the hangup
1230 * frame in its place.
1232 AST_LIST_REMOVE(&chan->readq, cur, frame_list);
1236 * This has degenerated to a normal queue append anyway. Since
1237 * we just destroyed the last frame in the queue we must make
1238 * sure that "after" is NULL or bad things will happen.
1244 case AST_CONTROL_HANGUP:
1245 /* Don't queue anything. */
1246 ast_channel_unlock(chan);
1253 /* Build copies of all the new frames and count them */
1254 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1255 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1256 if (!(f = ast_frdup(cur))) {
1257 if (AST_LIST_FIRST(&frames)) {
1258 ast_frfree(AST_LIST_FIRST(&frames));
1260 ast_channel_unlock(chan);
1264 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1266 if (f->frametype == AST_FRAME_VOICE) {
1271 /* Count how many frames exist on the queue */
1272 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1274 if (cur->frametype == AST_FRAME_VOICE) {
1275 queued_voice_frames++;
1279 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1281 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1282 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
1283 /* Save the most recent frame */
1284 if (!AST_LIST_NEXT(cur, frame_list)) {
1286 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1290 AST_LIST_REMOVE_CURRENT(frame_list);
1294 AST_LIST_TRAVERSE_SAFE_END;
1298 AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1301 AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1302 AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1304 AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1307 if (chan->alertpipe[1] > -1) {
1308 int blah[new_frames];
1310 memset(blah, 1, sizeof(blah));
1311 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != (sizeof(blah))) {
1312 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1313 ast_channel_name(chan), queued_frames, strerror(errno));
1315 } else if (chan->timingfd > -1) {
1316 ast_timer_enable_continuous(chan->timer);
1317 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1318 pthread_kill(chan->blocker, SIGURG);
1321 ast_channel_unlock(chan);
1326 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1328 return __ast_queue_frame(chan, fin, 0, NULL);
1331 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1333 return __ast_queue_frame(chan, fin, 1, NULL);
1336 /*! \brief Queue a hangup frame for channel */
1337 int ast_queue_hangup(struct ast_channel *chan)
1339 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1340 /* Yeah, let's not change a lock-critical value without locking */
1341 if (!ast_channel_trylock(chan)) {
1342 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1343 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1346 ast_channel_name(chan),
1348 ast_channel_unlock(chan);
1350 return ast_queue_frame(chan, &f);
1353 /*! \brief Queue a hangup frame for channel */
1354 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1356 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1359 f.data.uint32 = cause;
1361 /* Yeah, let's not change a lock-critical value without locking */
1362 if (!ast_channel_trylock(chan)) {
1363 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1365 f.data.uint32 = chan->hangupcause;
1367 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1371 ast_channel_name(chan),
1374 ast_channel_unlock(chan);
1377 return ast_queue_frame(chan, &f);
1380 /*! \brief Queue a control frame */
1381 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1383 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1384 return ast_queue_frame(chan, &f);
1387 /*! \brief Queue a control frame with payload */
1388 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1389 const void *data, size_t datalen)
1391 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1392 return ast_queue_frame(chan, &f);
1395 /*! \brief Set defer DTMF flag on channel */
1396 int ast_channel_defer_dtmf(struct ast_channel *chan)
1401 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1402 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1407 /*! \brief Unset defer DTMF flag on channel */
1408 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1411 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1414 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1415 void *data, int ao2_flags)
1417 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1420 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1422 struct ast_channel *chan = obj;
1423 const char *name = (flags & OBJ_KEY) ? arg : ast_channel_name((struct ast_channel *)arg);
1424 size_t name_len = *(size_t *)data;
1425 int ret = CMP_MATCH;
1427 if (ast_strlen_zero(name)) {
1428 ast_log(LOG_ERROR, "BUG! Must supply a name, or a channel with a name to match on!\n");
1432 ast_channel_lock(chan);
1433 if (!name_len && (strcasecmp(ast_channel_name(chan), name) || (name_len && strncasecmp(ast_channel_name(chan), name, name_len)))) {
1434 ret = 0; /* name match failed, keep looking */
1436 ast_channel_unlock(chan);
1441 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1443 struct ast_channel *chan = obj;
1444 char *context = arg, *exten = data;
1445 int ret = CMP_MATCH;
1447 if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1448 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1452 ast_channel_lock(chan);
1453 if (strcasecmp(chan->context, context) && strcasecmp(chan->macrocontext, context)) {
1454 ret = 0; /* Context match failed, continue */
1455 } else if (strcasecmp(chan->exten, exten) && strcasecmp(chan->macroexten, exten)) {
1456 ret = 0; /* Extension match failed, continue */
1458 ast_channel_unlock(chan);
1463 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1465 struct ast_channel *chan = obj;
1466 char *uniqueid = arg;
1467 size_t name_len = *(size_t *) data;
1468 int ret = CMP_MATCH;
1470 if (ast_strlen_zero(uniqueid)) {
1471 ast_log(LOG_ERROR, "BUG! Must have a uniqueid to match!\n");
1475 ast_channel_lock(chan);
1476 if (!name_len && (strcasecmp(chan->uniqueid, uniqueid) ||
1477 (name_len && strncasecmp(chan->uniqueid, uniqueid, name_len)))) {
1480 ast_channel_unlock(chan);
1485 struct ast_channel_iterator {
1486 /* storage for non-dynamically allocated iterator */
1487 struct ao2_iterator simple_iterator;
1488 /* pointer to the actual iterator (simple_iterator or a dynamically
1489 * allocated iterator)
1491 struct ao2_iterator *active_iterator;
1494 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1496 ao2_iterator_destroy(i->active_iterator);
1502 static struct ast_channel_iterator *channel_iterator_search(const char *name,
1503 size_t name_len, const char *exten, const char *context)
1505 struct ast_channel_iterator *i;
1506 char *l_name = (char *) name;
1507 char *l_exten = (char *) exten;
1508 char *l_context = (char *) context;
1510 if (!(i = ast_calloc(1, sizeof(*i)))) {
1514 if (ast_strlen_zero(name)
1515 && !(i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1516 l_context, l_exten, OBJ_MULTIPLE))) {
1519 } else if (!(i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1521 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0)))) {
1529 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1531 return channel_iterator_search(NULL, 0, exten, context);
1534 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1536 return channel_iterator_search(name, name_len, NULL, NULL);
1539 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1541 struct ast_channel_iterator *i;
1543 if (!(i = ast_calloc(1, sizeof(*i)))) {
1547 i->simple_iterator = ao2_iterator_init(channels, 0);
1548 i->active_iterator = &i->simple_iterator;
1553 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1555 return ao2_iterator_next(i->active_iterator);
1558 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1559 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1561 struct ast_channel *cmp_args = arg;
1563 int ret = CMP_MATCH;
1565 /* This is sort of a hack. Basically, we're using an arbitrary field
1566 * in ast_channel to pass the name_len for a prefix match. If this
1567 * gets changed, then the uses of ao2_find() must be changed, too. */
1568 name_len = cmp_args->rings;
1570 if (!ast_strlen_zero(ast_channel_name(cmp_args))) { /* match by name */
1571 ret = ast_channel_by_name_cb(obj, arg, &name_len, flags);
1572 } else if (!ast_strlen_zero(cmp_args->exten)) {
1573 ret = ast_channel_by_exten_cb(obj, cmp_args->context, cmp_args->exten, flags);
1574 } else if (!ast_strlen_zero(cmp_args->uniqueid)) {
1575 ret = ast_channel_by_uniqueid_cb(obj, (void *) cmp_args->uniqueid, &name_len, flags);
1583 static struct ast_channel *ast_channel_get_full(const char *name, size_t name_len,
1584 const char *exten, const char *context)
1586 struct ast_channel *chan;
1587 char *l_name = (char *) name;
1588 char *l_exten = (char *) exten;
1589 char *l_context = (char *) context;
1591 if (ast_strlen_zero(name)
1592 && (chan = ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0))) {
1594 } else if ((chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1595 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0))) {
1599 /* If we haven't found by name or context yet and don't have a name, give up. */
1604 /* If name was specified, but the result was NULL,
1605 * try a search on uniqueid, instead. */
1606 return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1609 struct ast_channel *ast_channel_get_by_name(const char *name)
1611 return ast_channel_get_full(name, 0, NULL, NULL);
1614 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1616 return ast_channel_get_full(name, name_len, NULL, NULL);
1619 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1621 return ast_channel_get_full(NULL, 0, exten, context);
1624 int ast_is_deferrable_frame(const struct ast_frame *frame)
1626 /* Do not add a default entry in this switch statement. Each new
1627 * frame type should be addressed directly as to whether it should
1628 * be queued up or not.
1630 switch (frame->frametype) {
1631 case AST_FRAME_CONTROL:
1632 case AST_FRAME_TEXT:
1633 case AST_FRAME_IMAGE:
1634 case AST_FRAME_HTML:
1637 case AST_FRAME_DTMF_END:
1638 case AST_FRAME_DTMF_BEGIN:
1639 case AST_FRAME_VOICE:
1640 case AST_FRAME_VIDEO:
1641 case AST_FRAME_NULL:
1644 case AST_FRAME_MODEM:
1650 /*! \brief Wait, look for hangups and condition arg */
1651 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1653 struct ast_frame *f;
1654 struct ast_silence_generator *silgen = NULL;
1656 AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1658 AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1660 /* If no other generator is present, start silencegen while waiting */
1661 if (ast_opt_transmit_silence && !chan->generatordata) {
1662 silgen = ast_channel_start_silence_generator(chan);
1666 struct ast_frame *dup_f = NULL;
1667 if (cond && ((*cond)(data) == 0)) {
1670 ms = ast_waitfor(chan, ms);
1682 if (!ast_is_deferrable_frame(f)) {
1687 if ((dup_f = ast_frisolate(f))) {
1691 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1696 /* stop silgen if present */
1698 ast_channel_stop_silence_generator(chan, silgen);
1701 /* We need to free all the deferred frames, but we only need to
1702 * queue the deferred frames if there was no error and no
1703 * hangup was received
1705 ast_channel_lock(chan);
1706 while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1708 ast_queue_frame_head(chan, f);
1712 ast_channel_unlock(chan);
1717 /*! \brief Wait, look for hangups */
1718 int ast_safe_sleep(struct ast_channel *chan, int ms)
1720 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1723 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1725 /* Safe, even if already unlinked. */
1726 ao2_unlink(channels, chan);
1727 return ast_channel_unref(chan);
1730 void ast_party_name_init(struct ast_party_name *init)
1733 init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1734 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1738 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1741 /* Don't copy to self */
1745 ast_free(dest->str);
1746 dest->str = ast_strdup(src->str);
1747 dest->char_set = src->char_set;
1748 dest->presentation = src->presentation;
1749 dest->valid = src->valid;
1752 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1755 init->char_set = guide->char_set;
1756 init->presentation = guide->presentation;
1757 init->valid = guide->valid;
1760 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1763 /* Don't set to self */
1767 if (src->str && src->str != dest->str) {
1768 ast_free(dest->str);
1769 dest->str = ast_strdup(src->str);
1772 dest->char_set = src->char_set;
1773 dest->presentation = src->presentation;
1774 dest->valid = src->valid;
1777 void ast_party_name_free(struct ast_party_name *doomed)
1779 ast_free(doomed->str);
1783 void ast_party_number_init(struct ast_party_number *init)
1786 init->plan = 0;/* Unknown */
1787 init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1791 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1794 /* Don't copy to self */
1798 ast_free(dest->str);
1799 dest->str = ast_strdup(src->str);
1800 dest->plan = src->plan;
1801 dest->presentation = src->presentation;
1802 dest->valid = src->valid;
1805 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1808 init->plan = guide->plan;
1809 init->presentation = guide->presentation;
1810 init->valid = guide->valid;
1813 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1816 /* Don't set to self */
1820 if (src->str && src->str != dest->str) {
1821 ast_free(dest->str);
1822 dest->str = ast_strdup(src->str);
1825 dest->plan = src->plan;
1826 dest->presentation = src->presentation;
1827 dest->valid = src->valid;
1830 void ast_party_number_free(struct ast_party_number *doomed)
1832 ast_free(doomed->str);
1836 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1840 init->odd_even_indicator = 0;
1844 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1847 /* Don't copy to self */
1851 ast_free(dest->str);
1852 dest->str = ast_strdup(src->str);
1853 dest->type = src->type;
1854 dest->odd_even_indicator = src->odd_even_indicator;
1855 dest->valid = src->valid;
1858 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1861 init->type = guide->type;
1862 init->odd_even_indicator = guide->odd_even_indicator;
1863 init->valid = guide->valid;
1866 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1869 /* Don't set to self */
1873 if (src->str && src->str != dest->str) {
1874 ast_free(dest->str);
1875 dest->str = ast_strdup(src->str);
1878 dest->type = src->type;
1879 dest->odd_even_indicator = src->odd_even_indicator;
1880 dest->valid = src->valid;
1883 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1885 ast_free(doomed->str);
1889 void ast_party_id_init(struct ast_party_id *init)
1891 ast_party_name_init(&init->name);
1892 ast_party_number_init(&init->number);
1893 ast_party_subaddress_init(&init->subaddress);
1897 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1900 /* Don't copy to self */
1904 ast_party_name_copy(&dest->name, &src->name);
1905 ast_party_number_copy(&dest->number, &src->number);
1906 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1908 ast_free(dest->tag);
1909 dest->tag = ast_strdup(src->tag);
1912 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1914 ast_party_name_set_init(&init->name, &guide->name);
1915 ast_party_number_set_init(&init->number, &guide->number);
1916 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1920 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1923 /* Don't set to self */
1927 if (!update || update->name) {
1928 ast_party_name_set(&dest->name, &src->name);
1930 if (!update || update->number) {
1931 ast_party_number_set(&dest->number, &src->number);
1933 if (!update || update->subaddress) {
1934 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1937 if (src->tag && src->tag != dest->tag) {
1938 ast_free(dest->tag);
1939 dest->tag = ast_strdup(src->tag);
1943 void ast_party_id_free(struct ast_party_id *doomed)
1945 ast_party_name_free(&doomed->name);
1946 ast_party_number_free(&doomed->number);
1947 ast_party_subaddress_free(&doomed->subaddress);
1949 ast_free(doomed->tag);
1953 int ast_party_id_presentation(const struct ast_party_id *id)
1955 int number_priority;
1957 int number_screening;
1961 /* Determine name presentation priority. */
1962 if (!id->name.valid) {
1963 name_value = AST_PRES_UNAVAILABLE;
1966 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1967 switch (name_value) {
1968 case AST_PRES_RESTRICTED:
1971 case AST_PRES_ALLOWED:
1974 case AST_PRES_UNAVAILABLE:
1978 name_value = AST_PRES_UNAVAILABLE;
1984 /* Determine number presentation priority. */
1985 if (!id->number.valid) {
1986 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1987 number_value = AST_PRES_UNAVAILABLE;
1988 number_priority = 3;
1990 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1991 number_value = id->number.presentation & AST_PRES_RESTRICTION;
1992 switch (number_value) {
1993 case AST_PRES_RESTRICTED:
1994 number_priority = 0;
1996 case AST_PRES_ALLOWED:
1997 number_priority = 1;
1999 case AST_PRES_UNAVAILABLE:
2000 number_priority = 2;
2003 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2004 number_value = AST_PRES_UNAVAILABLE;
2005 number_priority = 3;
2010 /* Select the wining presentation value. */
2011 if (name_priority < number_priority) {
2012 number_value = name_value;
2015 return number_value | number_screening;
2018 void ast_party_dialed_init(struct ast_party_dialed *init)
2020 init->number.str = NULL;
2021 init->number.plan = 0;/* Unknown */
2022 ast_party_subaddress_init(&init->subaddress);
2023 init->transit_network_select = 0;
2026 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2029 /* Don't copy to self */
2033 ast_free(dest->number.str);
2034 dest->number.str = ast_strdup(src->number.str);
2035 dest->number.plan = src->number.plan;
2036 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2037 dest->transit_network_select = src->transit_network_select;
2040 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2042 init->number.str = NULL;
2043 init->number.plan = guide->number.plan;
2044 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2045 init->transit_network_select = guide->transit_network_select;
2048 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2050 if (src->number.str && src->number.str != dest->number.str) {
2051 ast_free(dest->number.str);
2052 dest->number.str = ast_strdup(src->number.str);
2054 dest->number.plan = src->number.plan;
2056 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2058 dest->transit_network_select = src->transit_network_select;
2061 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2063 ast_free(doomed->number.str);
2064 doomed->number.str = NULL;
2065 ast_party_subaddress_free(&doomed->subaddress);
2068 void ast_party_caller_init(struct ast_party_caller *init)
2070 ast_party_id_init(&init->id);
2071 ast_party_id_init(&init->ani);
2075 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2078 /* Don't copy to self */
2082 ast_party_id_copy(&dest->id, &src->id);
2083 ast_party_id_copy(&dest->ani, &src->ani);
2084 dest->ani2 = src->ani2;
2087 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2089 ast_party_id_set_init(&init->id, &guide->id);
2090 ast_party_id_set_init(&init->ani, &guide->ani);
2091 init->ani2 = guide->ani2;
2094 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *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;
2101 void ast_party_caller_free(struct ast_party_caller *doomed)
2103 ast_party_id_free(&doomed->id);
2104 ast_party_id_free(&doomed->ani);
2107 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2109 ast_party_id_init(&init->id);
2110 ast_party_id_init(&init->ani);
2112 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2115 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2118 /* Don't copy to self */
2122 ast_party_id_copy(&dest->id, &src->id);
2123 ast_party_id_copy(&dest->ani, &src->ani);
2124 dest->ani2 = src->ani2;
2125 dest->source = src->source;
2128 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2130 ast_party_id_set_init(&init->id, &guide->id);
2131 ast_party_id_set_init(&init->ani, &guide->ani);
2132 init->ani2 = guide->ani2;
2133 init->source = guide->source;
2136 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)
2138 ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2139 ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2140 dest->ani2 = src->ani2;
2141 dest->source = src->source;
2144 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2146 connected->id = caller->id;
2147 connected->ani = caller->ani;
2148 connected->ani2 = caller->ani2;
2149 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2152 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2154 ast_party_id_free(&doomed->id);
2155 ast_party_id_free(&doomed->ani);
2158 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2160 ast_party_id_init(&init->from);
2161 ast_party_id_init(&init->to);
2163 init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2166 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2169 /* Don't copy to self */
2173 ast_party_id_copy(&dest->from, &src->from);
2174 ast_party_id_copy(&dest->to, &src->to);
2175 dest->count = src->count;
2176 dest->reason = src->reason;
2179 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2181 ast_party_id_set_init(&init->from, &guide->from);
2182 ast_party_id_set_init(&init->to, &guide->to);
2183 init->count = guide->count;
2184 init->reason = guide->reason;
2187 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2189 ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2190 ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2191 dest->reason = src->reason;
2192 dest->count = src->count;
2195 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2197 ast_party_id_free(&doomed->from);
2198 ast_party_id_free(&doomed->to);
2201 /*! \brief Free a channel structure */
2202 static void ast_channel_destructor(void *obj)
2204 struct ast_channel *chan = obj;
2209 struct ast_var_t *vardata;
2210 struct ast_frame *f;
2211 struct varshead *headp;
2212 struct ast_datastore *datastore;
2213 char device_name[AST_CHANNEL_NAME];
2215 if (ast_channel_name(chan)) {
2216 /* The string fields were initialized. */
2217 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2218 ast_cel_check_retire_linkedid(chan);
2221 /* Get rid of each of the data stores on the channel */
2222 ast_channel_lock(chan);
2223 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
2224 /* Free the data store */
2225 ast_datastore_free(datastore);
2226 ast_channel_unlock(chan);
2228 /* Lock and unlock the channel just to be sure nobody has it locked still
2229 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2230 ast_channel_lock(chan);
2231 ast_channel_unlock(chan);
2233 if (chan->tech_pvt) {
2234 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2235 ast_free(chan->tech_pvt);
2239 ast_sched_context_destroy(chan->sched);
2242 if (ast_channel_name(chan)) {
2245 /* The string fields were initialized. */
2246 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2247 if ((dashptr = strrchr(device_name, '-'))) {
2251 device_name[0] = '\0';
2254 /* Stop monitoring */
2256 chan->monitor->stop( chan, 0 );
2258 /* If there is native format music-on-hold state, free it */
2259 if (chan->music_state)
2260 ast_moh_cleanup(chan);
2262 /* Free translators */
2263 if (chan->readtrans)
2264 ast_translator_free_path(chan->readtrans);
2265 if (chan->writetrans)
2266 ast_translator_free_path(chan->writetrans);
2268 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2270 ast_party_dialed_free(&chan->dialed);
2271 ast_party_caller_free(&chan->caller);
2272 ast_party_connected_line_free(&chan->connected);
2273 ast_party_redirecting_free(&chan->redirecting);
2275 /* Close pipes if appropriate */
2276 if ((fd = chan->alertpipe[0]) > -1)
2278 if ((fd = chan->alertpipe[1]) > -1)
2281 ast_timer_close(chan->timer);
2284 for (i = 0; i < AST_MAX_FDS; i++) {
2285 if (chan->epfd_data[i])
2286 free(chan->epfd_data[i]);
2290 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
2293 /* loop over the variables list, freeing all data and deleting list items */
2294 /* no need to lock the list, as the channel is already locked */
2295 headp = &chan->varshead;
2296 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2297 ast_var_delete(vardata);
2299 ast_app_group_discard(chan);
2301 /* Destroy the jitterbuffer */
2302 ast_jb_destroy(chan);
2305 ast_cdr_discard(chan->cdr);
2310 chan->zone = ast_tone_zone_unref(chan->zone);
2313 ast_string_field_free_memory(chan);
2315 if (device_name[0]) {
2317 * We have a device name to notify of a new state.
2319 * Queue an unknown state, because, while we know that this particular
2320 * instance is dead, we don't know the state of all other possible
2323 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2326 chan->nativeformats = ast_format_cap_destroy(chan->nativeformats);
2329 /*! \brief Free a dummy channel structure */
2330 static void ast_dummy_channel_destructor(void *obj)
2332 struct ast_channel *chan = obj;
2333 struct ast_var_t *vardata;
2334 struct varshead *headp;
2336 headp = &chan->varshead;
2338 ast_party_dialed_free(&chan->dialed);
2339 ast_party_caller_free(&chan->caller);
2340 ast_party_connected_line_free(&chan->connected);
2341 ast_party_redirecting_free(&chan->redirecting);
2343 /* loop over the variables list, freeing all data and deleting list items */
2344 /* no need to lock the list, as the channel is already locked */
2345 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2346 ast_var_delete(vardata);
2349 ast_cdr_discard(chan->cdr);
2353 ast_string_field_free_memory(chan);
2356 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2358 return ast_datastore_alloc(info, uid);
2361 int ast_channel_datastore_free(struct ast_datastore *datastore)
2363 return ast_datastore_free(datastore);
2366 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2368 struct ast_datastore *datastore = NULL, *datastore2;
2370 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
2371 if (datastore->inheritance > 0) {
2372 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2374 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2375 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2376 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
2383 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2387 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
2392 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2394 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
2397 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2399 struct ast_datastore *datastore = NULL;
2404 AST_LIST_TRAVERSE(&chan->datastores, datastore, entry) {
2405 if (datastore->info != info) {
2410 /* matched by type only */
2414 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2415 /* Matched by type AND uid */
2423 /*! Set the file descriptor on the channel */
2424 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2427 struct epoll_event ev;
2428 struct ast_epoll_data *aed = NULL;
2430 if (chan->fds[which] > -1) {
2431 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2432 aed = chan->epfd_data[which];
2435 /* If this new fd is valid, add it to the epoll */
2437 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2440 chan->epfd_data[which] = aed;
2444 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2446 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2448 /* We don't have to keep around this epoll data structure now */
2450 chan->epfd_data[which] = NULL;
2453 chan->fds[which] = fd;
2457 /*! Add a channel to an optimized waitfor */
2458 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2461 struct epoll_event ev;
2464 if (chan0->epfd == -1)
2467 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2468 for (i = 0; i < AST_MAX_FDS; i++) {
2469 if (chan1->fds[i] == -1)
2471 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2472 ev.data.ptr = chan1->epfd_data[i];
2473 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2480 /*! Delete a channel from an optimized waitfor */
2481 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2484 struct epoll_event ev;
2487 if (chan0->epfd == -1)
2490 for (i = 0; i < AST_MAX_FDS; i++) {
2491 if (chan1->fds[i] == -1)
2493 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2500 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2502 ast_channel_lock(chan);
2504 chan->_softhangup &= ~flag;
2506 if (!chan->_softhangup) {
2507 struct ast_frame *fr;
2509 /* If we have completely cleared the softhangup flag,
2510 * then we need to fully abort the hangup process. This requires
2511 * pulling the END_OF_Q frame out of the channel frame queue if it
2512 * still happens to be there. */
2514 fr = AST_LIST_LAST(&chan->readq);
2515 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2516 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2517 AST_LIST_REMOVE(&chan->readq, fr, frame_list);
2522 ast_channel_unlock(chan);
2525 /*! \brief Softly hangup a channel, don't lock */
2526 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2528 ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2529 /* Inform channel driver that we need to be hung up, if it cares */
2530 chan->_softhangup |= cause;
2531 ast_queue_frame(chan, &ast_null_frame);
2532 /* Interrupt any poll call or such */
2533 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2534 pthread_kill(chan->blocker, SIGURG);
2538 /*! \brief Softly hangup a channel, lock */
2539 int ast_softhangup(struct ast_channel *chan, int cause)
2543 ast_channel_lock(chan);
2544 res = ast_softhangup_nolock(chan, cause);
2545 manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2549 ast_channel_name(chan),
2552 ast_channel_unlock(chan);
2557 static void free_translation(struct ast_channel *clonechan)
2559 if (clonechan->writetrans)
2560 ast_translator_free_path(clonechan->writetrans);
2561 if (clonechan->readtrans)
2562 ast_translator_free_path(clonechan->readtrans);
2563 clonechan->writetrans = NULL;
2564 clonechan->readtrans = NULL;
2565 if (ast_format_cap_is_empty(clonechan->nativeformats)) {
2566 ast_format_clear(&clonechan->rawwriteformat);
2567 ast_format_clear(&clonechan->rawreadformat);
2569 struct ast_format tmpfmt;
2570 ast_best_codec(clonechan->nativeformats, &tmpfmt);
2571 ast_format_copy(&clonechan->rawwriteformat, &tmpfmt);
2572 ast_format_copy(&clonechan->rawreadformat, &tmpfmt);
2576 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2578 struct ast_channel *bridge;
2580 ast_channel_lock(chan);
2581 if (force || ast_strlen_zero(chan->hangupsource)) {
2582 ast_string_field_set(chan, hangupsource, source);
2584 bridge = ast_bridged_channel(chan);
2585 ast_channel_unlock(chan);
2587 if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
2588 ast_channel_lock(bridge);
2589 ast_string_field_set(chan, hangupsource, source);
2590 ast_channel_unlock(bridge);
2594 /*! \brief Hangup a channel */
2595 int ast_hangup(struct ast_channel *chan)
2597 char extra_str[64]; /* used for cel logging below */
2599 ast_autoservice_stop(chan);
2602 ast_channel_lock(chan);
2604 if (chan->audiohooks) {
2605 ast_audiohook_detach_list(chan->audiohooks);
2606 chan->audiohooks = NULL;
2608 ast_framehook_list_destroy(chan);
2611 * Do the masquerade if someone is setup to masquerade into us.
2613 * NOTE: We must hold the channel lock after testing for a
2614 * pending masquerade and setting the channel as a zombie to
2615 * prevent __ast_channel_masquerade() from setting up a
2616 * masquerade with a dead channel.
2618 while (chan->masq) {
2619 ast_channel_unlock(chan);
2620 ao2_unlock(channels);
2621 if (ast_do_masquerade(chan)) {
2622 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2624 /* Abort the loop or we might never leave. */
2626 ast_channel_lock(chan);
2630 ast_channel_lock(chan);
2635 * This channel is one which will be masqueraded into something.
2636 * Mark it as a zombie already so ast_do_masquerade() will know
2639 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2640 ast_channel_unlock(chan);
2641 ao2_unlock(channels);
2645 ao2_unlink(channels, chan);
2646 ao2_unlock(channels);
2648 free_translation(chan);
2649 /* Close audio stream */
2651 ast_closestream(chan->stream);
2652 chan->stream = NULL;
2654 /* Close video stream */
2655 if (chan->vstream) {
2656 ast_closestream(chan->vstream);
2657 chan->vstream = NULL;
2660 ast_sched_context_destroy(chan->sched);
2664 if (chan->generatordata) { /* Clear any tone stuff remaining */
2665 if (chan->generator && chan->generator->release) {
2666 chan->generator->release(chan, chan->generatordata);
2669 chan->generatordata = NULL;
2670 chan->generator = NULL;
2672 snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2673 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2675 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2676 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2677 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2678 (long) pthread_self(), ast_channel_name(chan), (long)chan->blocker, chan->blockproc);
2679 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2681 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
2682 ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2685 * This channel is now dead so mark it as a zombie so anyone
2686 * left holding a reference to this channel will not use it.
2688 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2689 if (chan->tech->hangup) {
2690 chan->tech->hangup(chan);
2693 ast_debug(1, "Hanging up zombie '%s'\n", ast_channel_name(chan));
2696 ast_channel_unlock(chan);
2699 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2702 "CallerIDNum: %s\r\n"
2703 "CallerIDName: %s\r\n"
2704 "ConnectedLineNum: %s\r\n"
2705 "ConnectedLineName: %s\r\n"
2707 "Cause-txt: %s\r\n",
2708 ast_channel_name(chan),
2710 S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<unknown>"),
2711 S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, "<unknown>"),
2712 S_COR(chan->connected.id.number.valid, chan->connected.id.number.str, "<unknown>"),
2713 S_COR(chan->connected.id.name.valid, chan->connected.id.name.str, "<unknown>"),
2715 ast_cause2str(chan->hangupcause)
2718 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
2719 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
2720 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2721 ast_channel_lock(chan);
2722 ast_cdr_end(chan->cdr);
2723 ast_cdr_detach(chan->cdr);
2725 ast_channel_unlock(chan);
2728 ast_channel_unref(chan);
2733 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2737 ast_channel_lock(chan);
2739 /* You can't answer an outbound call */
2740 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2741 ast_channel_unlock(chan);
2745 /* Stop if we're a zombie or need a soft hangup */
2746 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2747 ast_channel_unlock(chan);
2751 ast_channel_unlock(chan);
2753 switch (chan->_state) {
2754 case AST_STATE_RINGING:
2755 case AST_STATE_RING:
2756 ast_channel_lock(chan);
2757 if (chan->tech->answer) {
2758 res = chan->tech->answer(chan);
2760 ast_setstate(chan, AST_STATE_UP);
2762 ast_cdr_answer(chan->cdr);
2764 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2765 ast_channel_unlock(chan);
2768 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2769 /* Calling ast_cdr_answer when it it has previously been called
2770 * is essentially a no-op, so it is safe.
2773 ast_cdr_answer(chan->cdr);
2780 ast_indicate(chan, -1);
2785 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2788 enum ast_channel_state old_state;
2790 old_state = chan->_state;
2791 if ((res = ast_raw_answer(chan, cdr_answer))) {
2795 switch (old_state) {
2796 case AST_STATE_RINGING:
2797 case AST_STATE_RING:
2798 /* wait for media to start flowing, but don't wait any longer
2799 * than 'delay' or 500 milliseconds, whichever is longer
2802 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2803 struct ast_frame *cur, *new;
2804 int ms = MAX(delay, 500);
2805 unsigned int done = 0;
2807 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2810 ms = ast_waitfor(chan, ms);
2812 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2817 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));
2820 cur = ast_read(chan);
2821 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2822 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2827 ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2831 if ((new = ast_frisolate(cur)) != cur) {
2835 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2837 /* if a specific delay period was requested, continue
2838 * until that delay has passed. don't stop just because
2839 * incoming media has arrived.
2845 switch (new->frametype) {
2846 /* all of these frametypes qualify as 'media' */
2847 case AST_FRAME_VOICE:
2848 case AST_FRAME_VIDEO:
2849 case AST_FRAME_TEXT:
2850 case AST_FRAME_DTMF_BEGIN:
2851 case AST_FRAME_DTMF_END:
2852 case AST_FRAME_IMAGE:
2853 case AST_FRAME_HTML:
2854 case AST_FRAME_MODEM:
2857 case AST_FRAME_CONTROL:
2859 case AST_FRAME_NULL:
2870 ast_channel_lock(chan);
2871 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2872 ast_queue_frame_head(chan, cur);
2875 ast_channel_unlock(chan);
2886 int ast_answer(struct ast_channel *chan)
2888 return __ast_answer(chan, 0, 1);
2891 void ast_deactivate_generator(struct ast_channel *chan)
2893 ast_channel_lock(chan);
2894 if (chan->generatordata) {
2895 if (chan->generator && chan->generator->release)
2896 chan->generator->release(chan, chan->generatordata);
2897 chan->generatordata = NULL;
2898 chan->generator = NULL;
2899 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2900 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2901 ast_settimeout(chan, 0, NULL, NULL);
2903 ast_channel_unlock(chan);
2906 static void generator_write_format_change(struct ast_channel *chan)
2908 ast_channel_lock(chan);
2909 if (chan->generator && chan->generator->write_format_change) {
2910 chan->generator->write_format_change(chan, chan->generatordata);
2912 ast_channel_unlock(chan);
2915 static int generator_force(const void *data)
2917 /* Called if generator doesn't have data */
2920 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2921 struct ast_channel *chan = (struct ast_channel *)data;
2923 ast_channel_lock(chan);
2924 tmp = chan->generatordata;
2925 chan->generatordata = NULL;
2926 if (chan->generator)
2927 generate = chan->generator->generate;
2928 ast_channel_unlock(chan);
2930 if (!tmp || !generate)
2933 res = generate(chan, tmp, 0, ast_format_rate(&chan->writeformat) / 50);
2935 chan->generatordata = tmp;
2938 ast_debug(1, "Auto-deactivating generator\n");
2939 ast_deactivate_generator(chan);
2945 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2949 ast_channel_lock(chan);
2950 if (chan->generatordata) {
2951 if (chan->generator && chan->generator->release)
2952 chan->generator->release(chan, chan->generatordata);
2953 chan->generatordata = NULL;
2955 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2959 ast_settimeout(chan, 50, generator_force, chan);
2960 chan->generator = gen;
2962 ast_channel_unlock(chan);
2969 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2970 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2973 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2977 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2979 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2980 int *exception, int *outfd, int *ms)
2982 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2983 int *exception, int *outfd, int *ms)
2986 struct timeval start = { 0 , 0 };
2987 struct pollfd *pfds = NULL;
2992 struct timeval now = { 0, 0 };
2993 struct timeval whentohangup = { 0, 0 }, diff;
2994 struct ast_channel *winner = NULL;
3000 if ((sz = n * AST_MAX_FDS + nfds)) {
3001 pfds = alloca(sizeof(*pfds) * sz);
3002 fdmap = alloca(sizeof(*fdmap) * sz);
3010 /* Perform any pending masquerades */
3011 for (x = 0; x < n; x++) {
3012 if (c[x]->masq && ast_do_masquerade(c[x])) {
3013 ast_log(LOG_WARNING, "Masquerade failed\n");
3018 ast_channel_lock(c[x]);
3019 if (!ast_tvzero(c[x]->whentohangup)) {
3020 if (ast_tvzero(whentohangup))
3022 diff = ast_tvsub(c[x]->whentohangup, now);
3023 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3024 /* Should already be hungup */
3025 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3026 ast_channel_unlock(c[x]);
3029 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3030 whentohangup = diff;
3032 ast_channel_unlock(c[x]);
3034 /* Wait full interval */
3036 /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3037 if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3038 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
3039 if (*ms >= 0 && *ms < rms) { /* original *ms still smaller */
3042 } else if (!ast_tvzero(whentohangup) && rms < 0) {
3043 /* Tiny corner case... call would need to last >24 days */
3047 * Build the pollfd array, putting the channels' fds first,
3048 * followed by individual fds. Order is important because
3049 * individual fd's must have priority over channel fds.
3052 for (x = 0; x < n; x++) {
3053 for (y = 0; y < AST_MAX_FDS; y++) {
3054 fdmap[max].fdno = y; /* fd y is linked to this pfds */
3055 fdmap[max].chan = x; /* channel x is linked to this pfds */
3056 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
3058 CHECK_BLOCKING(c[x]);
3060 /* Add the individual fds */
3061 for (x = 0; x < nfds; x++) {
3062 fdmap[max].chan = -1;
3063 max += ast_add_fd(&pfds[max], fds[x]);
3067 start = ast_tvnow();
3069 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3074 res = ast_poll(pfds, max, kbrms);
3077 } while (!res && (rms > 0));
3079 res = ast_poll(pfds, max, rms);
3081 for (x = 0; x < n; x++)
3082 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
3083 if (res < 0) { /* Simulate a timeout if we were interrupted */
3088 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
3090 for (x = 0; x < n; x++) {
3091 if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
3092 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3098 if (res == 0) { /* no fd ready, reset timeout and done */
3099 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
3103 * Then check if any channel or fd has a pending event.
3104 * Remember to check channels first and fds last, as they
3105 * must have priority on setting 'winner'
3107 for (x = 0; x < max; x++) {
3108 res = pfds[x].revents;
3111 if (fdmap[x].chan >= 0) { /* this is a channel */
3112 winner = c[fdmap[x].chan]; /* override previous winners */
3114 ast_set_flag(winner, AST_FLAG_EXCEPTION);
3116 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3117 winner->fdno = fdmap[x].fdno;
3118 } else { /* this is an fd */
3120 *outfd = pfds[x].fd;
3122 *exception = (res & POLLPRI) ? -1 : 0;
3127 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3135 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3137 struct timeval start = { 0 , 0 };
3139 struct epoll_event ev[1];
3140 long diff, rms = *ms;
3141 struct ast_channel *winner = NULL;
3142 struct ast_epoll_data *aed = NULL;
3145 /* See if this channel needs to be masqueraded */
3146 if (chan->masq && ast_do_masquerade(chan)) {
3147 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", ast_channel_name(chan));
3152 ast_channel_lock(chan);
3153 /* Figure out their timeout */
3154 if (!ast_tvzero(chan->whentohangup)) {
3155 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
3156 /* They should already be hungup! */
3157 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3158 ast_channel_unlock(chan);
3161 /* If this value is smaller then the current one... make it priority */
3166 ast_channel_unlock(chan);
3168 /* Time to make this channel block... */
3169 CHECK_BLOCKING(chan);
3172 start = ast_tvnow();
3174 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3175 res = epoll_wait(chan->epfd, ev, 1, rms);
3178 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3180 /* Simulate a timeout if we were interrupted */
3187 /* If this channel has a timeout see if it expired */
3188 if (!ast_tvzero(chan->whentohangup)) {
3189 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
3190 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3195 /* No fd ready, reset timeout and be done for now */
3201 /* See what events are pending */
3202 aed = ev[0].data.ptr;
3203 chan->fdno = aed->which;
3204 if (ev[0].events & EPOLLPRI)
3205 ast_set_flag(chan, AST_FLAG_EXCEPTION);
3207 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3210 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3218 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3220 struct timeval start = { 0 , 0 };
3222 struct epoll_event ev[25] = { { 0, } };
3223 struct timeval now = { 0, 0 };
3224 long whentohangup = 0, diff = 0, rms = *ms;
3225 struct ast_channel *winner = NULL;
3227 for (i = 0; i < n; i++) {
3228 if (c[i]->masq && ast_do_masquerade(c[i])) {
3229 ast_log(LOG_WARNING, "Masquerade failed\n");
3234 ast_channel_lock(c[i]);
3235 if (!ast_tvzero(c[i]->whentohangup)) {
3236 if (whentohangup == 0)
3238 if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
3239 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3240 ast_channel_unlock(c[i]);
3243 if (!whentohangup || whentohangup > diff)
3244 whentohangup = diff;
3246 ast_channel_unlock(c[i]);
3247 CHECK_BLOCKING(c[i]);
3253 if (*ms >= 0 && *ms < rms)
3258 start = ast_tvnow();
3260 res = epoll_wait(c[0]->epfd, ev, 25, rms);
3262 for (i = 0; i < n; i++)
3263 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
3273 for (i = 0; i < n; i++) {
3274 if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
3275 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3287 for (i = 0; i < res; i++) {
3288 struct ast_epoll_data *aed = ev[i].data.ptr;
3290 if (!ev[i].events || !aed)
3294 if (ev[i].events & EPOLLPRI)
3295 ast_set_flag(winner, AST_FLAG_EXCEPTION);
3297 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3298 winner->fdno = aed->which;
3302 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3310 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3311 int *exception, int *outfd, int *ms)
3313 /* Clear all provided values in one place. */
3319 /* If no epoll file descriptor is available resort to classic nandfds */
3320 if (!n || nfds || c[0]->epfd == -1)
3321 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3322 else if (!nfds && n == 1)
3323 return ast_waitfor_nandfds_simple(c[0], ms);
3325 return ast_waitfor_nandfds_complex(c, n, ms);
3329 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3331 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3334 int ast_waitfor(struct ast_channel *c, int ms)
3336 int oldms = ms; /* -1 if no timeout */
3338 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3339 if ((ms < 0) && (oldms < 0))
3344 /* XXX never to be called with ms = -1 */
3345 int ast_waitfordigit(struct ast_channel *c, int ms)
3347 return ast_waitfordigit_full(c, ms, -1, -1);
3350 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3353 unsigned int real_rate = rate, max_rate;
3355 ast_channel_lock(c);
3357 if (c->timingfd == -1) {
3358 ast_channel_unlock(c);
3367 if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
3368 real_rate = max_rate;
3371 ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3373 res = ast_timer_set_rate(c->timer, real_rate);
3375 c->timingfunc = func;
3376 c->timingdata = data;
3378 ast_channel_unlock(c);
3383 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
3385 /* Stop if we're a zombie or need a soft hangup */
3386 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3389 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3390 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
3392 /* Wait for a digit, no more than ms milliseconds total. */
3395 struct ast_channel *rchan;
3399 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3401 if (!rchan && outfd < 0 && ms) {
3402 if (errno == 0 || errno == EINTR)
3404 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
3405 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3407 } else if (outfd > -1) {
3408 /* The FD we were watching has something waiting */
3409 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
3410 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3414 struct ast_frame *f = ast_read(c);
3418 switch (f->frametype) {
3419 case AST_FRAME_DTMF_BEGIN:
3421 case AST_FRAME_DTMF_END:
3422 res = f->subclass.integer;
3424 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3426 case AST_FRAME_CONTROL:
3427 switch (f->subclass.integer) {
3428 case AST_CONTROL_HANGUP:
3430 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3432 case AST_CONTROL_RINGING:
3433 case AST_CONTROL_ANSWER:
3434 case AST_CONTROL_SRCUPDATE:
3435 case AST_CONTROL_SRCCHANGE:
3436 case AST_CONTROL_CONNECTED_LINE:
3437 case AST_CONTROL_REDIRECTING:
3438 case AST_CONTROL_UPDATE_RTP_PEER:
3443 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
3447 case AST_FRAME_VOICE:
3448 /* Write audio if appropriate */
3450 if (write(audiofd, f->data.ptr, f->datalen) < 0) {
3451 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3462 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3464 return 0; /* Time is up */
3467 static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
3469 ast_manager_event(chan, EVENT_FLAG_DTMF,
3477 ast_channel_name(chan), chan->uniqueid, digit, direction, begin, end);
3480 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
3482 if (chan->generator && chan->generator->generate && chan->generatordata && !ast_internal_timing_enabled(chan)) {
3483 void *tmp = chan->generatordata;
3484 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = chan->generator->generate;
3488 if (chan->timingfunc) {
3489 ast_debug(1, "Generator got voice, switching to phase locked mode\n");
3490 ast_settimeout(chan, 0, NULL, NULL);
3493 chan->generatordata = NULL; /* reset, to let writes go through */
3495 if (ast_format_cmp(&f->subclass.format, &chan->writeformat) == AST_FORMAT_CMP_NOT_EQUAL) {
3497 factor = ((float) ast_format_rate(&chan->writeformat)) / ((float) ast_format_rate(&f->subclass.format));
3498 samples = (int) ( ((float) f->samples) * factor );
3500 samples = f->samples;
3503 /* This unlock is here based on two assumptions that hold true at this point in the
3504 * code. 1) this function is only called from within __ast_read() and 2) all generators
3505 * call ast_write() in their generate callback.
3507 * The reason this is added is so that when ast_write is called, the lock that occurs
3508 * there will not recursively lock the channel. Doing this will cause intended deadlock
3509 * avoidance not to work in deeper functions
3511 ast_channel_unlock(chan);
3512 res = generate(chan, tmp, f->datalen, samples);
3513 ast_channel_lock(chan);
3514 chan->generatordata = tmp;
3516 ast_debug(1, "Auto-deactivating generator\n");
3517 ast_deactivate_generator(chan);
3520 } else if (f->frametype == AST_FRAME_CNG) {
3521 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
3522 ast_debug(1, "Generator got CNG, switching to timed mode\n");
3523 ast_settimeout(chan, 50, generator_force, chan);
3528 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3530 struct ast_frame *fr = &chan->dtmff;
3532 fr->frametype = AST_FRAME_DTMF_END;
3533 fr->subclass.integer = f->subclass.integer;
3536 /* The only time this function will be called is for a frame that just came
3537 * out of the channel driver. So, we want to stick it on the tail of the
3540 ast_queue_frame(chan, fr);
3544 * \brief Determine whether or not we should ignore DTMF in the readq
3546 static inline int should_skip_dtmf(struct ast_channel *chan)
3548 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
3549 /* We're in the middle of emulating a digit, or DTMF has been
3550 * explicitly deferred. Skip this digit, then. */
3554 if (!ast_tvzero(chan->dtmf_tv) &&
3555 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3556 /* We're not in the middle of a digit, but it hasn't been long enough
3557 * since the last digit, so we'll have to skip DTMF for now. */
3565 * \brief calculates the number of samples to jump forward with in a monitor stream.
3567 * \note When using ast_seekstream() with the read and write streams of a monitor,
3568 * the number of samples to seek forward must be of the same sample rate as the stream
3569 * or else the jump will not be calculated correctly.
3571 * \retval number of samples to seek forward after rate conversion.
3573 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
3575 int diff = sample_rate - seek_rate;
3578 samples = samples / (float) (sample_rate / seek_rate);
3579 } else if (diff < 0) {
3580 samples = samples * (float) (seek_rate / sample_rate);
3586 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
3588 struct ast_frame *f = NULL; /* the return value */
3593 /* this function is very long so make sure there is only one return
3594 * point at the end (there are only two exceptions to this).
3598 if (ast_do_masquerade(chan))
3599 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
3601 f = &ast_null_frame;
3605 /* if here, no masq has happened, lock the channel and proceed */
3606 ast_channel_lock(chan);
3608 /* Stop if we're a zombie or need a soft hangup */
3609 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
3610 if (chan->generator)
3611 ast_deactivate_generator(chan);
3614 * It is possible for chan->_softhangup to be set and there
3615 * still be control frames that need to be read. Instead of
3616 * just going to 'done' in the case of ast_check_hangup(), we
3617 * need to queue the end-of-Q frame so that it can mark the end
3618 * of the read queue. If there are frames to be read,
3619 * ast_queue_control() will be called repeatedly, but will only
3620 * queue the first end-of-Q frame.
3622 if (chan->_softhangup) {
3623 ast_queue_control(chan, AST_CONTROL_END_OF_Q);
3630 * The ast_waitfor() code records which of the channel's file
3631 * descriptors reported that data is available. In theory,
3632 * ast_read() should only be called after ast_waitfor() reports
3633 * that a channel has data available for reading. However,
3634 * there still may be some edge cases throughout the code where
3635 * ast_read() is called improperly. This can potentially cause
3636 * problems, so if this is a developer build, make a lot of
3637 * noise if this happens so that it can be addressed.
3639 * One of the potential problems is blocking on a dead channel.
3641 if (chan->fdno == -1) {
3643 "ast_read() on chan '%s' called with no recorded file descriptor.\n",
3644 ast_channel_name(chan));
3649 prestate = chan->_state;
3651 /* Read and ignore anything on the alertpipe, but read only
3652 one sizeof(blah) per frame that we send from it */
3653 if (chan->alertpipe[0] > -1) {
3654 int flags = fcntl(chan->alertpipe[0], F_GETFL);
3655 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
3656 * which immediately causes a deadlock scenario. Detect and prevent this. */
3657 if ((flags & O_NONBLOCK) == 0) {
3658 ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", ast_channel_name(chan));
3659 if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
3660 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
3661 f = &ast_null_frame;
3665 if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
3666 if (errno != EINTR && errno != EAGAIN)
3667 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
3671 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
3672 enum ast_timer_event res;
3674 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3676 res = ast_timer_get_event(chan->timer);
3679 case AST_TIMING_EVENT_EXPIRED:
3680 ast_timer_ack(chan->timer, 1);
3682 if (chan->timingfunc) {
3683 /* save a copy of func/data before unlocking the channel */
3684 int (*func)(const void *) = chan->timingfunc;
3685 void *data = chan->timingdata;
3687 ast_channel_unlock(chan);
3690 ast_timer_set_rate(chan->timer, 0);
3692 ast_channel_unlock(chan);
3695 /* cannot 'goto done' because the channel is already unlocked */
3696 return &ast_null_frame;
3698 case AST_TIMING_EVENT_CONTINUOUS:
3699 if (AST_LIST_EMPTY(&chan->readq) ||
3700 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
3701 ast_timer_disable_continuous(chan->timer);
3706 } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
3707 /* if the AST_GENERATOR_FD is set, call the generator with args
3708 * set to -1 so it can do whatever it needs to.
3710 void *tmp = chan->generatordata;
3711 chan->generatordata = NULL; /* reset to let ast_write get through */
3712 chan->generator->generate(chan, tmp, -1, -1);
3713 chan->generatordata = tmp;
3714 f = &ast_null_frame;
3717 } else if (chan->fds[AST_JITTERBUFFER_FD] > -1 && chan->fdno == AST_JITTERBUFFER_FD) {
3718 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3721 /* Check for pending read queue */
3722 if (!AST_LIST_EMPTY(&chan->readq)) {
3723 int skip_dtmf = should_skip_dtmf(chan);
3725 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
3726 /* We have to be picky about which frame we pull off of the readq because
3727 * there are cases where we want to leave DTMF frames on the queue until
3728 * some later time. */
3730 if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
3734 AST_LIST_REMOVE_CURRENT(frame_list);
3737 AST_LIST_TRAVERSE_SAFE_END;
3740 /* There were no acceptable frames on the readq. */
3741 f = &ast_null_frame;
3742 if (chan->alertpipe[0] > -1) {
3744 /* Restore the state of the alertpipe since we aren't ready for any
3745 * of the frames in the readq. */
3746 if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
3747 ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
3752 /* Interpret hangup and end-of-Q frames to return NULL */
3753 /* XXX why not the same for frames from the channel ? */
3754 if (f->frametype == AST_FRAME_CONTROL) {
3755 switch (f->subclass.integer) {
3756 case AST_CONTROL_HANGUP:
3757 chan->_softhangup |= AST_SOFTHANGUP_DEV;
3758 cause = f->data.uint32;
3760 case AST_CONTROL_END_OF_Q:
3769 chan->blocker = pthread_self();
3770 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
3771 if (chan->tech->exception)
3772 f = chan->tech->exception(chan);
3774 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", ast_channel_name(chan));
3775 f = &ast_null_frame;
3777 /* Clear the exception flag */
3778 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3779 } else if (chan->tech && chan->tech->read)
3780 f = chan->tech->read(chan);
3782 ast_log(LOG_WARNING, "No read routine on channel %s\n", ast_channel_name(chan));
3785 /* Perform the framehook read event here. After the frame enters the framehook list
3786 * there is no telling what will happen, <insert mad scientist laugh here>!!! */
3787 f = ast_framehook_list_read_event(chan->framehooks, f);
3790 * Reset the recorded file descriptor that triggered this read so that we can
3791 * easily detect when ast_read() is called without properly using ast_waitfor().
3796 struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
3797 struct ast_control_read_action_payload *read_action_payload;
3798 struct ast_party_connected_line connected;
3800 /* if the channel driver returned more than one frame, stuff the excess
3801 into the readq for the next ast_read call
3803 if (AST_LIST_NEXT(f, frame_list)) {
3804 ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
3805 ast_frfree(AST_LIST_NEXT(f, frame_list));
3806 AST_LIST_NEXT(f, frame_list) = NULL;
3809 switch (f->frametype) {
3810 case AST_FRAME_CONTROL:
3811 if (f->subclass.integer == AST_CONTROL_ANSWER) {
3812 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
3813 ast_debug(1, "Ignoring answer on an inbound call!\n");
3815 f = &ast_null_frame;
3816 } else if (prestate == AST_STATE_UP && ast_bridged_channel(chan)) {
3817 ast_debug(1, "Dropping duplicate answer!\n");