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/sha1.h"
62 #include "asterisk/threadstorage.h"
63 #include "asterisk/slinfactory.h"
64 #include "asterisk/audiohook.h"
65 #include "asterisk/timing.h"
66 #include "asterisk/autochan.h"
67 #include "asterisk/stringfields.h"
70 #include <sys/epoll.h>
73 struct ast_epoll_data {
74 struct ast_channel *chan;
78 /* uncomment if you have problems with 'monitoring' synchronized files */
80 #define MONITOR_CONSTANT_DELAY
81 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
84 /*! \brief Prevent new channel allocation if shutting down. */
85 static int shutting_down;
89 unsigned long global_fin, global_fout;
91 AST_THREADSTORAGE(state2str_threadbuf);
92 #define STATE2STR_BUFSIZE 32
94 /*! Default amount of time to use when emulating a digit as a begin and end
96 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
98 /*! Minimum allowed digit length - 80ms */
99 #define AST_MIN_DTMF_DURATION 80
101 /*! Minimum amount of time between the end of the last digit and the beginning
102 * of a new one - 45ms */
103 #define AST_MIN_DTMF_GAP 45
105 /*! \brief List of channel drivers */
107 const struct ast_channel_tech *tech;
108 AST_LIST_ENTRY(chanlist) list;
112 /*! \brief Structure to hold channel context backtrace data */
113 struct ast_chan_trace_data {
115 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
118 /*! \brief Structure to save contexts where an ast_chan has been into */
119 struct ast_chan_trace {
120 char context[AST_MAX_CONTEXT];
121 char exten[AST_MAX_EXTENSION];
123 AST_LIST_ENTRY(ast_chan_trace) entry;
127 /*! \brief the list of registered channel types */
128 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
131 #define NUM_CHANNEL_BUCKETS 61
133 #define NUM_CHANNEL_BUCKETS 1567
136 /*! \brief All active channels on the system */
137 static struct ao2_container *channels;
139 /*! \brief map AST_CAUSE's to readable string representations
143 static const struct {
148 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
149 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
150 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
151 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
152 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
153 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
154 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
155 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
156 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
157 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
158 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
159 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
160 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
161 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
162 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
163 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
164 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
165 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
166 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
167 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
168 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
169 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
170 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
171 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
172 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
173 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
174 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
175 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
176 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
177 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
178 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
179 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
180 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
181 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
182 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
183 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
184 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
185 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
186 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
187 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
188 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
189 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
190 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
191 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
194 struct ast_variable *ast_channeltype_list(void)
197 struct ast_variable *var = NULL, *prev = NULL;
199 AST_RWLIST_RDLOCK(&backends);
200 AST_RWLIST_TRAVERSE(&backends, cl, list) {
202 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
205 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
209 AST_RWLIST_UNLOCK(&backends);
214 /*! \brief Show channel types - CLI command */
215 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
217 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
223 e->command = "core show channeltypes";
225 "Usage: core show channeltypes\n"
226 " Lists available channel types registered in your\n"
227 " Asterisk server.\n";
234 return CLI_SHOWUSAGE;
236 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
237 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
239 AST_RWLIST_RDLOCK(&backends);
240 AST_RWLIST_TRAVERSE(&backends, cl, list) {
241 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
242 (cl->tech->devicestate) ? "yes" : "no",
243 (cl->tech->indicate) ? "yes" : "no",
244 (cl->tech->transfer) ? "yes" : "no");
247 AST_RWLIST_UNLOCK(&backends);
249 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
256 static char *complete_channeltypes(struct ast_cli_args *a)
266 wordlen = strlen(a->word);
268 AST_RWLIST_RDLOCK(&backends);
269 AST_RWLIST_TRAVERSE(&backends, cl, list) {
270 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
271 ret = ast_strdup(cl->tech->type);
275 AST_RWLIST_UNLOCK(&backends);
280 /*! \brief Show details about a channel driver - CLI command */
281 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
283 struct chanlist *cl = NULL;
288 e->command = "core show channeltype";
290 "Usage: core show channeltype <name>\n"
291 " Show details about the specified channel type, <name>.\n";
294 return complete_channeltypes(a);
298 return CLI_SHOWUSAGE;
300 AST_RWLIST_RDLOCK(&backends);
302 AST_RWLIST_TRAVERSE(&backends, cl, list) {
303 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
309 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
310 AST_RWLIST_UNLOCK(&backends);
315 "-- Info about channel driver: %s --\n"
316 " Device State: %s\n"
319 " Capabilities: %s\n"
323 " Image Support: %s\n"
324 " Text Support: %s\n",
326 (cl->tech->devicestate) ? "yes" : "no",
327 (cl->tech->indicate) ? "yes" : "no",
328 (cl->tech->transfer) ? "yes" : "no",
329 ast_getformatname_multiple(buf, sizeof(buf), (cl->tech->capabilities) ? cl->tech->capabilities : -1),
330 (cl->tech->send_digit_begin) ? "yes" : "no",
331 (cl->tech->send_digit_end) ? "yes" : "no",
332 (cl->tech->send_html) ? "yes" : "no",
333 (cl->tech->send_image) ? "yes" : "no",
334 (cl->tech->send_text) ? "yes" : "no"
338 AST_RWLIST_UNLOCK(&backends);
343 static struct ast_cli_entry cli_channel[] = {
344 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
345 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
349 /*! \brief Destructor for the channel trace datastore */
350 static void ast_chan_trace_destroy_cb(void *data)
352 struct ast_chan_trace *trace;
353 struct ast_chan_trace_data *traced = data;
354 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
360 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
361 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
363 .destroy = ast_chan_trace_destroy_cb
366 /*! \brief Put the channel backtrace in a string */
367 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
370 struct ast_chan_trace *trace;
371 struct ast_chan_trace_data *traced;
372 struct ast_datastore *store;
374 ast_channel_lock(chan);
375 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
377 ast_channel_unlock(chan);
380 traced = store->data;
382 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
383 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
384 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
390 ast_channel_unlock(chan);
394 /* !\brief Whether or not context tracing is enabled */
395 int ast_channel_trace_is_enabled(struct ast_channel *chan)
397 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
400 return ((struct ast_chan_trace_data *)store->data)->enabled;
403 /*! \brief Update the context backtrace data if tracing is enabled */
404 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
406 struct ast_chan_trace *trace;
407 if (!traced->enabled)
409 /* If the last saved context does not match the current one
410 OR we have not saved any context so far, then save the current context */
411 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) ||
412 (AST_LIST_EMPTY(&traced->trace))) {
413 /* Just do some debug logging */
414 if (AST_LIST_EMPTY(&traced->trace))
415 ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
417 ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
418 /* alloc or bail out */
419 trace = ast_malloc(sizeof(*trace));
422 /* save the current location and store it in the trace list */
423 ast_copy_string(trace->context, chan->context, sizeof(trace->context));
424 ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
425 trace->priority = chan->priority;
426 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
431 /*! \brief Update the context backtrace if tracing is enabled */
432 int ast_channel_trace_update(struct ast_channel *chan)
434 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
437 return ast_channel_trace_data_update(chan, store->data);
440 /*! \brief Enable context tracing in the channel */
441 int ast_channel_trace_enable(struct ast_channel *chan)
443 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
444 struct ast_chan_trace_data *traced;
446 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
449 traced = ast_calloc(1, sizeof(*traced));
451 ast_datastore_free(store);
454 store->data = traced;
455 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
456 ast_channel_datastore_add(chan, store);
458 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
459 ast_channel_trace_data_update(chan, store->data);
463 /*! \brief Disable context tracing in the channel */
464 int ast_channel_trace_disable(struct ast_channel *chan)
466 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
469 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
472 #endif /* CHANNEL_TRACE */
474 /*! \brief Checks to see if a channel is needing hang up */
475 int ast_check_hangup(struct ast_channel *chan)
477 if (chan->_softhangup) /* yes if soft hangup flag set */
479 if (ast_tvzero(chan->whentohangup)) /* no if no hangup scheduled */
481 if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0) /* no if hangup time has not come yet. */
483 ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(chan->whentohangup, ast_tvnow()));
484 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
488 int ast_check_hangup_locked(struct ast_channel *chan)
491 ast_channel_lock(chan);
492 res = ast_check_hangup(chan);
493 ast_channel_unlock(chan);
497 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
499 struct ast_channel *chan = obj;
501 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
506 void ast_begin_shutdown(int hangup)
511 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
515 /*! \brief returns number of active/allocated channels */
516 int ast_active_channels(void)
518 return channels ? ao2_container_count(channels) : 0;
521 /*! \brief Cancel a shutdown in progress */
522 void ast_cancel_shutdown(void)
527 /*! \brief Returns non-zero if Asterisk is being shut down */
528 int ast_shutting_down(void)
530 return shutting_down;
533 /*! \brief Set when to hangup channel */
534 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
536 chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
537 ast_queue_frame(chan, &ast_null_frame);
541 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
543 struct timeval when = { offset, };
544 ast_channel_setwhentohangup_tv(chan, when);
547 /*! \brief Compare a offset with when to hangup channel */
548 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
550 struct timeval whentohangup;
552 if (ast_tvzero(chan->whentohangup))
553 return ast_tvzero(offset) ? 0 : -1;
555 if (ast_tvzero(offset))
558 whentohangup = ast_tvadd(offset, ast_tvnow());
560 return ast_tvdiff_ms(whentohangup, chan->whentohangup);
563 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
565 struct timeval when = { offset, };
566 return ast_channel_cmpwhentohangup_tv(chan, when);
569 /*! \brief Register a new telephony channel in Asterisk */
570 int ast_channel_register(const struct ast_channel_tech *tech)
572 struct chanlist *chan;
574 AST_RWLIST_WRLOCK(&backends);
576 AST_RWLIST_TRAVERSE(&backends, chan, list) {
577 if (!strcasecmp(tech->type, chan->tech->type)) {
578 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
579 AST_RWLIST_UNLOCK(&backends);
584 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
585 AST_RWLIST_UNLOCK(&backends);
589 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
591 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
593 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
595 AST_RWLIST_UNLOCK(&backends);
600 /*! \brief Unregister channel driver */
601 void ast_channel_unregister(const struct ast_channel_tech *tech)
603 struct chanlist *chan;
605 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
607 AST_RWLIST_WRLOCK(&backends);
609 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
610 if (chan->tech == tech) {
611 AST_LIST_REMOVE_CURRENT(list);
613 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
617 AST_LIST_TRAVERSE_SAFE_END;
619 AST_RWLIST_UNLOCK(&backends);
622 /*! \brief Get handle to channel driver based on name */
623 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
625 struct chanlist *chanls;
626 const struct ast_channel_tech *ret = NULL;
628 AST_RWLIST_RDLOCK(&backends);
630 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
631 if (!strcasecmp(name, chanls->tech->type)) {
637 AST_RWLIST_UNLOCK(&backends);
642 /*! \brief Gives the string form of a given hangup cause */
643 const char *ast_cause2str(int cause)
647 for (x = 0; x < ARRAY_LEN(causes); x++) {
648 if (causes[x].cause == cause)
649 return causes[x].desc;
655 /*! \brief Convert a symbolic hangup cause to number */
656 int ast_str2cause(const char *name)
660 for (x = 0; x < ARRAY_LEN(causes); x++)
661 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
662 return causes[x].cause;
667 /*! \brief Gives the string form of a given channel state.
668 \note This function is not reentrant.
670 const char *ast_state2str(enum ast_channel_state state)
677 case AST_STATE_RESERVED:
679 case AST_STATE_OFFHOOK:
681 case AST_STATE_DIALING:
685 case AST_STATE_RINGING:
691 case AST_STATE_DIALING_OFFHOOK:
692 return "Dialing Offhook";
693 case AST_STATE_PRERING:
696 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
698 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
703 /*! \brief Gives the string form of a given transfer capability */
704 char *ast_transfercapability2str(int transfercapability)
706 switch (transfercapability) {
707 case AST_TRANS_CAP_SPEECH:
709 case AST_TRANS_CAP_DIGITAL:
711 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
712 return "RESTRICTED_DIGITAL";
713 case AST_TRANS_CAP_3_1K_AUDIO:
715 case AST_TRANS_CAP_DIGITAL_W_TONES:
716 return "DIGITAL_W_TONES";
717 case AST_TRANS_CAP_VIDEO:
724 /*! \brief Pick the best audio codec */
725 format_t ast_best_codec(format_t fmts)
727 /* This just our opinion, expressed in code. We are asked to choose
728 the best codec to use, given no information */
730 static const format_t prefs[] =
732 /*! Okay, ulaw is used by all telephony equipment, so start with it */
734 /*! Unless of course, you're a silly European, so then prefer ALAW */
739 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
741 /*! Okay, well, signed linear is easy to translate into other stuff */
742 AST_FORMAT_SLINEAR16,
744 /*! G.726 is standard ADPCM, in RFC3551 packing order */
746 /*! G.726 is standard ADPCM, in AAL2 packing order */
747 AST_FORMAT_G726_AAL2,
748 /*! ADPCM has great sound quality and is still pretty easy to translate */
750 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
751 translate and sounds pretty good */
753 /*! iLBC is not too bad */
755 /*! Speex is free, but computationally more expensive than GSM */
757 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
760 /*! G.729a is faster than 723 and slightly less expensive */
762 /*! Down to G.723.1 which is proprietary but at least designed for voice */
767 /* Strip out video */
768 fmts &= AST_FORMAT_AUDIO_MASK;
770 /* Find the first preferred codec in the format given */
771 for (x = 0; x < ARRAY_LEN(prefs); x++) {
776 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), fmts));
781 static const struct ast_channel_tech null_tech = {
783 .description = "Null channel (should not see this)",
786 static void ast_channel_destructor(void *obj);
787 static void ast_dummy_channel_destructor(void *obj);
789 /*! \brief Create a new channel structure */
790 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
791 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
792 const char *acctcode, const char *exten, const char *context,
793 const char *linkedid, const int amaflag, const char *file, int line,
794 const char *function, const char *name_fmt, va_list ap1, va_list ap2)
796 struct ast_channel *tmp;
799 struct varshead *headp;
801 /* If shutting down, don't allocate any new channels */
803 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
807 #if defined(REF_DEBUG)
808 if (!(tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line, function, 1))) {
811 #elif defined(__AST_DEBUG_MALLOC)
812 if (!(tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line, function, 0))) {
816 if (!(tmp = ao2_alloc(sizeof(*tmp), ast_channel_destructor))) {
821 if (!(tmp->sched = sched_context_create())) {
822 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
823 return ast_channel_unref(tmp);
826 if ((ast_string_field_init(tmp, 128))) {
827 return ast_channel_unref(tmp);
831 if (!(tmp->cid.cid_name = ast_strdup(cid_name))) {
832 return ast_channel_unref(tmp);
836 if (!(tmp->cid.cid_num = ast_strdup(cid_num))) {
837 return ast_channel_unref(tmp);
842 tmp->epfd = epoll_create(25);
845 for (x = 0; x < AST_MAX_FDS; x++) {
848 tmp->epfd_data[x] = NULL;
852 if ((tmp->timer = ast_timer_open())) {
854 tmp->timingfd = ast_timer_fd(tmp->timer);
860 if (pipe(tmp->alertpipe)) {
861 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
864 ast_timer_close(tmp->timer);
867 sched_context_destroy(tmp->sched);
868 ast_string_field_free_memory(tmp);
869 ast_free(tmp->cid.cid_name);
870 ast_free(tmp->cid.cid_num);
874 flags = fcntl(tmp->alertpipe[0], F_GETFL);
875 if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
876 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
877 close(tmp->alertpipe[0]);
878 close(tmp->alertpipe[1]);
879 goto alertpipe_failed;
881 flags = fcntl(tmp->alertpipe[1], F_GETFL);
882 if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
883 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
884 close(tmp->alertpipe[0]);
885 close(tmp->alertpipe[1]);
886 goto alertpipe_failed;
889 } else /* Make sure we've got it done right if they don't */
890 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
892 /* Always watch the alertpipe */
893 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
894 /* And timing pipe */
895 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
896 ast_string_field_set(tmp, name, "**Unknown**");
903 tmp->fin = global_fin;
904 tmp->fout = global_fout;
906 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
907 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
908 ast_atomic_fetchadd_int(&uniqueint, 1));
910 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
911 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
914 if (!ast_strlen_zero(linkedid)) {
915 ast_string_field_set(tmp, linkedid, linkedid);
918 ast_string_field_set(tmp, linkedid, tmp->uniqueid);
921 if (!ast_strlen_zero(name_fmt)) {
922 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
923 * And they all use slightly different formats for their name string.
924 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
925 * This means, that the stringfields must have a routine that takes the va_lists directly, and
926 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
927 * This new function was written so this can be accomplished.
929 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
932 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
934 /* These 4 variables need to be set up for the cdr_init() to work right */
936 tmp->amaflags = amaflag;
938 tmp->amaflags = ast_default_amaflags;
940 if (!ast_strlen_zero(acctcode))
941 ast_string_field_set(tmp, accountcode, acctcode);
943 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
945 if (!ast_strlen_zero(context))
946 ast_copy_string(tmp->context, context, sizeof(tmp->context));
948 strcpy(tmp->context, "default");
950 if (!ast_strlen_zero(exten))
951 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
953 strcpy(tmp->exten, "s");
957 tmp->cdr = ast_cdr_alloc();
958 ast_cdr_init(tmp->cdr, tmp);
959 ast_cdr_start(tmp->cdr);
961 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
963 headp = &tmp->varshead;
964 AST_LIST_HEAD_INIT_NOLOCK(headp);
966 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
968 AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
970 ast_string_field_set(tmp, language, defaultlanguage);
972 tmp->tech = &null_tech;
974 ao2_link(channels, tmp);
977 * and now, since the channel structure is built, and has its name, let's
978 * call the manager event generator with this Newchannel event. This is the
979 * proper and correct place to make this call, but you sure do have to pass
980 * a lot of data into this func to do it here!
982 if (!ast_strlen_zero(name_fmt)) {
983 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
985 "ChannelState: %d\r\n"
986 "ChannelStateDesc: %s\r\n"
987 "CallerIDNum: %s\r\n"
988 "CallerIDName: %s\r\n"
989 "AccountCode: %s\r\n"
995 ast_state2str(state),
1007 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1008 const char *cid_name, const char *acctcode,
1009 const char *exten, const char *context,
1010 const char *linkedid, const int amaflag,
1011 const char *file, int line, const char *function,
1012 const char *name_fmt, ...)
1015 struct ast_channel *result;
1017 va_start(ap1, name_fmt);
1018 va_start(ap2, name_fmt);
1019 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1020 linkedid, amaflag, file, line, function, name_fmt, ap1, ap2);
1027 /* only do the minimum amount of work needed here to make a channel
1028 * structure that can be used to expand channel vars */
1029 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1030 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1032 struct ast_channel *ast_dummy_channel_alloc(void)
1035 struct ast_channel *tmp;
1036 struct varshead *headp;
1038 #if defined(REF_DEBUG)
1039 if (!(tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel", file, line, function, 1))) {
1042 #elif defined(__AST_DEBUG_MALLOC)
1043 if (!(tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel", file, line, function, 0))) {
1047 if (!(tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor))) {
1052 if ((ast_string_field_init(tmp, 128))) {
1053 ast_channel_unref(tmp);
1057 headp = &tmp->varshead;
1058 AST_LIST_HEAD_INIT_NOLOCK(headp);
1063 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1065 struct ast_frame *f;
1066 struct ast_frame *cur;
1068 unsigned int new_frames = 0;
1069 unsigned int new_voice_frames = 0;
1070 unsigned int queued_frames = 0;
1071 unsigned int queued_voice_frames = 0;
1072 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1074 ast_channel_lock(chan);
1076 /* See if the last frame on the queue is a hangup, if so don't queue anything */
1077 if ((cur = AST_LIST_LAST(&chan->readq)) &&
1078 (cur->frametype == AST_FRAME_CONTROL) &&
1079 (cur->subclass.integer == AST_CONTROL_HANGUP)) {
1080 ast_channel_unlock(chan);
1084 /* Build copies of all the frames and count them */
1085 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1086 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1087 if (!(f = ast_frdup(cur))) {
1088 ast_frfree(AST_LIST_FIRST(&frames));
1089 ast_channel_unlock(chan);
1093 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1095 if (f->frametype == AST_FRAME_VOICE) {
1100 /* Count how many frames exist on the queue */
1101 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1103 if (cur->frametype == AST_FRAME_VOICE) {
1104 queued_voice_frames++;
1108 if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1110 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", chan->name);
1111 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
1112 /* Save the most recent frame */
1113 if (!AST_LIST_NEXT(cur, frame_list)) {
1115 } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1119 AST_LIST_REMOVE_CURRENT(frame_list);
1123 AST_LIST_TRAVERSE_SAFE_END;
1127 AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1130 AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1131 AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1133 AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1136 if (chan->alertpipe[1] > -1) {
1137 if (write(chan->alertpipe[1], &blah, new_frames * sizeof(blah)) != (new_frames * sizeof(blah))) {
1138 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1139 chan->name, queued_frames, strerror(errno));
1141 } else if (chan->timingfd > -1) {
1142 ast_timer_enable_continuous(chan->timer);
1143 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1144 pthread_kill(chan->blocker, SIGURG);
1147 ast_channel_unlock(chan);
1152 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1154 return __ast_queue_frame(chan, fin, 0, NULL);
1157 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1159 return __ast_queue_frame(chan, fin, 1, NULL);
1162 /*! \brief Queue a hangup frame for channel */
1163 int ast_queue_hangup(struct ast_channel *chan)
1165 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1166 /* Yeah, let's not change a lock-critical value without locking */
1167 if (!ast_channel_trylock(chan)) {
1168 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1169 ast_channel_unlock(chan);
1171 return ast_queue_frame(chan, &f);
1174 /*! \brief Queue a hangup frame for channel */
1175 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1177 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1180 f.data.uint32 = cause;
1182 /* Yeah, let's not change a lock-critical value without locking */
1183 if (!ast_channel_trylock(chan)) {
1184 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1186 f.data.uint32 = chan->hangupcause;
1188 ast_channel_unlock(chan);
1191 return ast_queue_frame(chan, &f);
1194 /*! \brief Queue a control frame */
1195 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1197 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1198 return ast_queue_frame(chan, &f);
1201 /*! \brief Queue a control frame with payload */
1202 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1203 const void *data, size_t datalen)
1205 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1206 return ast_queue_frame(chan, &f);
1209 /*! \brief Set defer DTMF flag on channel */
1210 int ast_channel_defer_dtmf(struct ast_channel *chan)
1215 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1216 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1221 /*! \brief Unset defer DTMF flag on channel */
1222 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1225 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1228 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1229 void *data, int ao2_flags)
1231 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1234 struct ast_channel_iterator {
1235 /* storage for non-dynamically allocated iterator */
1236 struct ao2_iterator simple_iterator;
1237 /* pointer to the actual iterator (simple_iterator or a dynamically
1238 * allocated iterator)
1240 struct ao2_iterator *active_iterator;
1243 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1245 ao2_iterator_destroy(i->active_iterator);
1251 static struct ast_channel_iterator *channel_iterator_search(const char *name,
1252 size_t name_len, const char *exten,
1253 const char *context)
1255 struct ast_channel_iterator *i;
1256 struct ast_channel tmp_chan = {
1258 /* This is sort of a hack. Basically, we're using an arbitrary field
1259 * in ast_channel to pass the name_len for a prefix match. If this
1260 * gets changed, then the compare callback must be changed, too. */
1264 if (!(i = ast_calloc(1, sizeof(*i)))) {
1269 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1273 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1276 if (!(i->active_iterator = ao2_find(channels, &tmp_chan,
1277 OBJ_MULTIPLE | ((!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0)))) {
1285 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1287 return channel_iterator_search(NULL, 0, exten, context);
1290 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1292 return channel_iterator_search(name, name_len, NULL, NULL);
1295 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1297 struct ast_channel_iterator *i;
1299 if (!(i = ast_calloc(1, sizeof(*i)))) {
1303 i->simple_iterator = ao2_iterator_init(channels, 0);
1304 i->active_iterator = &i->simple_iterator;
1309 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1311 return ao2_iterator_next(i->active_iterator);
1314 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1316 struct ast_channel *chan = obj, *cmp_args = arg;
1318 int ret = CMP_MATCH;
1320 /* This is sort of a hack. Basically, we're using an arbitrary field
1321 * in ast_channel to pass the name_len for a prefix match. If this
1322 * gets changed, then the uses of ao2_find() must be changed, too. */
1323 name_len = cmp_args->rings;
1325 ast_channel_lock(chan);
1327 if (!ast_strlen_zero(cmp_args->name)) { /* match by name */
1328 if ((!name_len && strcasecmp(chan->name, cmp_args->name)) ||
1329 (name_len && strncasecmp(chan->name, cmp_args->name, name_len))) {
1330 ret = 0; /* name match failed */
1332 } else if (!ast_strlen_zero(cmp_args->exten)) {
1333 if (cmp_args->context && strcasecmp(chan->context, cmp_args->context) &&
1334 strcasecmp(chan->macrocontext, cmp_args->context)) {
1335 ret = 0; /* context match failed */
1337 if (ret && strcasecmp(chan->exten, cmp_args->exten) &&
1338 strcasecmp(chan->macroexten, cmp_args->exten)) {
1339 ret = 0; /* exten match failed */
1341 } else if (!ast_strlen_zero(cmp_args->uniqueid)) {
1342 if ((!name_len && strcasecmp(chan->uniqueid, cmp_args->uniqueid)) ||
1343 (name_len && strncasecmp(chan->uniqueid, cmp_args->uniqueid, name_len))) {
1344 ret = 0; /* uniqueid match failed */
1350 ast_channel_unlock(chan);
1355 static struct ast_channel *ast_channel_get_full(const char *name, size_t name_len,
1356 const char *exten, const char *context)
1358 struct ast_channel tmp_chan = {
1360 /* This is sort of a hack. Basically, we're using an arbitrary field
1361 * in ast_channel to pass the name_len for a prefix match. If this
1362 * gets changed, then the compare callback must be changed, too. */
1365 struct ast_channel *chan;
1368 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1372 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1375 if ((chan = ao2_find(channels, &tmp_chan,
1376 (!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0))) {
1384 /* If name was specified, but the result was NULL,
1385 * try a search on uniqueid, instead. */
1388 struct ast_channel tmp_chan2 = {
1393 return ao2_find(channels, &tmp_chan2, 0);
1397 struct ast_channel *ast_channel_get_by_name(const char *name)
1399 return ast_channel_get_full(name, 0, NULL, NULL);
1402 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1404 return ast_channel_get_full(name, name_len, NULL, NULL);
1407 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1409 return ast_channel_get_full(NULL, 0, exten, context);
1412 /*! \brief Wait, look for hangups and condition arg */
1413 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1415 struct ast_frame *f;
1416 struct ast_silence_generator *silgen = NULL;
1419 /* If no other generator is present, start silencegen while waiting */
1420 if (ast_opt_transmit_silence && !chan->generatordata) {
1421 silgen = ast_channel_start_silence_generator(chan);
1425 if (cond && ((*cond)(data) == 0)) {
1428 ms = ast_waitfor(chan, ms);
1443 /* stop silgen if present */
1445 ast_channel_stop_silence_generator(chan, silgen);
1451 /*! \brief Wait, look for hangups */
1452 int ast_safe_sleep(struct ast_channel *chan, int ms)
1454 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1457 static void free_cid(struct ast_callerid *cid)
1460 ast_free(cid->cid_dnid);
1462 ast_free(cid->cid_num);
1464 ast_free(cid->cid_name);
1466 ast_free(cid->cid_ani);
1467 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = NULL;
1468 ast_party_subaddress_free(&cid->subaddress);
1469 ast_party_subaddress_free(&cid->dialed_subaddress);
1472 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1474 /* Safe, even if already unlinked. */
1475 ao2_unlink(channels, chan);
1476 return ast_channel_unref(chan);
1479 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1483 init->odd_even_indicator = 0;
1487 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1490 /* Don't copy to self */
1495 ast_free(dest->str);
1497 dest->str = ast_strdup(src->str);
1498 dest->type = src->type;
1499 dest->odd_even_indicator = src->odd_even_indicator;
1500 dest->valid = src->valid;
1503 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1506 init->type = guide->type;
1507 init->odd_even_indicator = guide->odd_even_indicator;
1508 init->valid = guide->valid;
1511 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1514 /* Don't set to self */
1518 if (src->str && src->str != dest->str) {
1520 ast_free(dest->str);
1522 dest->str = ast_strdup(src->str);
1525 dest->type = src->type;
1526 dest->odd_even_indicator = src->odd_even_indicator;
1527 dest->valid = src->valid;
1530 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1533 ast_free(doomed->str);
1540 * \brief Initialize the given party id structure.
1542 * \param init Party id structure to initialize.
1546 static void ast_party_id_init(struct ast_party_id *init)
1548 init->number = NULL;
1550 init->number_type = 0; /* Unknown */
1551 init->number_presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1552 ast_party_subaddress_init(&init->subaddress);
1557 * \brief Copy the source party id information to the destination party id.
1559 * \param dest Destination party id
1560 * \param src Source party id
1564 static void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1567 /* Don't copy to self */
1572 ast_free(dest->number);
1574 dest->number = ast_strdup(src->number);
1577 ast_free(dest->name);
1579 dest->name = ast_strdup(src->name);
1581 dest->number_type = src->number_type;
1582 dest->number_presentation = src->number_presentation;
1583 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1588 * \brief Initialize the given party id structure using the given guide
1589 * for a set update operation.
1592 * The initialization is needed to allow a set operation to know if a
1593 * value needs to be updated. Simple integers need the guide's original
1594 * value in case the set operation is not trying to set a new value.
1595 * String values are simply set to NULL pointers if they are not going
1598 * \param init Party id structure to initialize.
1599 * \param guide Source party id to use as a guide in initializing.
1603 static void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1605 init->number = NULL;
1607 init->number_type = guide->number_type;
1608 init->number_presentation = guide->number_presentation;
1609 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1614 * \brief Set the source party id information into the destination party id.
1616 * \param dest Destination party id
1617 * \param src Source party id
1621 static void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src)
1624 /* Don't set to self */
1628 if (src->name && src->name != dest->name) {
1630 ast_free(dest->name);
1632 dest->name = ast_strdup(src->name);
1635 if (src->number && src->number != dest->number) {
1637 ast_free(dest->number);
1639 dest->number = ast_strdup(src->number);
1642 dest->number_type = src->number_type;
1643 dest->number_presentation = src->number_presentation;
1644 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1649 * \brief Destroy the party id contents
1651 * \param doomed The party id to destroy.
1655 static void ast_party_id_free(struct ast_party_id *doomed)
1657 if (doomed->number) {
1658 ast_free(doomed->number);
1659 doomed->number = NULL;
1663 ast_free(doomed->name);
1664 doomed->name = NULL;
1666 ast_party_subaddress_free(&doomed->subaddress);
1669 void ast_party_caller_init(struct ast_party_caller *init)
1671 ast_party_id_init(&init->id);
1676 void ast_party_caller_copy(struct ast_callerid *dest, const struct ast_callerid *src)
1679 /* Don't copy to self */
1684 /* Copy caller-id specific information ONLY from struct ast_callerid */
1687 ast_free(dest->cid_num);
1689 dest->cid_num = ast_strdup(src->cid_num);
1693 ast_free(dest->cid_name);
1695 dest->cid_name = ast_strdup(src->cid_name);
1697 dest->cid_ton = src->cid_ton;
1698 dest->cid_pres = src->cid_pres;
1703 ast_free(dest->cid_ani);
1705 dest->cid_ani = ast_strdup(src->cid_ani);
1707 dest->cid_ani2 = src->cid_ani2;
1709 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1713 /* The src and dest parameter types will become struct ast_party_caller ptrs. */
1714 /* This is future code */
1716 ast_party_id_copy(&dest->id, &src->id);
1719 ast_free(dest->ani);
1721 dest->ani = ast_strdup(src->ani);
1723 dest->ani2 = src->ani2;
1727 void ast_party_connected_line_init(struct ast_party_connected_line *init)
1729 ast_party_id_init(&init->id);
1732 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
1735 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
1738 /* Don't copy to self */
1742 ast_party_id_copy(&dest->id, &src->id);
1745 ast_free(dest->ani);
1747 dest->ani = ast_strdup(src->ani);
1749 dest->ani2 = src->ani2;
1750 dest->source = src->source;
1753 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
1755 ast_party_id_set_init(&init->id, &guide->id);
1757 init->ani2 = guide->ani2;
1758 init->source = guide->source;
1761 void ast_party_connected_line_set(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
1763 ast_party_id_set(&dest->id, &src->id);
1765 if (src->ani && src->ani != dest->ani) {
1767 ast_free(dest->ani);
1769 dest->ani = ast_strdup(src->ani);
1772 dest->ani2 = src->ani2;
1773 dest->source = src->source;
1776 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_callerid *cid)
1778 connected->id.number = cid->cid_num;
1779 connected->id.name = cid->cid_name;
1780 connected->id.number_type = cid->cid_ton;
1781 connected->id.number_presentation = cid->cid_pres;
1782 connected->id.subaddress = cid->subaddress;
1784 connected->ani = cid->cid_ani;
1785 connected->ani2 = cid->cid_ani2;
1786 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
1789 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
1791 ast_party_id_free(&doomed->id);
1794 ast_free(doomed->ani);
1799 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
1802 /* Don't copy to self */
1806 ast_party_id_copy(&dest->from, &src->from);
1807 ast_party_id_copy(&dest->to, &src->to);
1808 dest->count = src->count;
1809 dest->reason = src->reason;
1812 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
1814 ast_party_id_set_init(&init->from, &guide->from);
1815 ast_party_id_set_init(&init->to, &guide->to);
1816 init->count = guide->count;
1817 init->reason = guide->reason;
1820 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
1822 ast_party_id_free(&doomed->from);
1823 ast_party_id_free(&doomed->to);
1826 /*! \brief Free a channel structure */
1827 static void ast_channel_destructor(void *obj)
1829 struct ast_channel *chan = obj;
1834 struct ast_var_t *vardata;
1835 struct ast_frame *f;
1836 struct varshead *headp;
1837 struct ast_datastore *datastore = NULL;
1838 char name[AST_CHANNEL_NAME], *dashptr;
1840 headp = &chan->varshead;
1842 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
1843 ast_cel_check_retire_linkedid(chan);
1845 /* Get rid of each of the data stores on the channel */
1846 ast_channel_lock(chan);
1847 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1848 /* Free the data store */
1849 ast_datastore_free(datastore);
1850 ast_channel_unlock(chan);
1852 /* Lock and unlock the channel just to be sure nobody has it locked still
1853 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1854 ast_channel_lock(chan);
1855 ast_channel_unlock(chan);
1857 if (chan->tech_pvt) {
1858 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1859 ast_free(chan->tech_pvt);
1863 sched_context_destroy(chan->sched);
1865 ast_copy_string(name, chan->name, sizeof(name));
1866 if ((dashptr = strrchr(name, '-'))) {
1870 /* Stop monitoring */
1872 chan->monitor->stop( chan, 0 );
1874 /* If there is native format music-on-hold state, free it */
1875 if (chan->music_state)
1876 ast_moh_cleanup(chan);
1878 /* Free translators */
1879 if (chan->readtrans)
1880 ast_translator_free_path(chan->readtrans);
1881 if (chan->writetrans)
1882 ast_translator_free_path(chan->writetrans);
1884 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1886 free_cid(&chan->cid);
1887 ast_party_connected_line_free(&chan->connected);
1888 ast_party_redirecting_free(&chan->redirecting);
1890 /* Close pipes if appropriate */
1891 if ((fd = chan->alertpipe[0]) > -1)
1893 if ((fd = chan->alertpipe[1]) > -1)
1896 ast_timer_close(chan->timer);
1899 for (i = 0; i < AST_MAX_FDS; i++) {
1900 if (chan->epfd_data[i])
1901 free(chan->epfd_data[i]);
1905 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1908 /* loop over the variables list, freeing all data and deleting list items */
1909 /* no need to lock the list, as the channel is already locked */
1911 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1912 ast_var_delete(vardata);
1914 ast_app_group_discard(chan);
1916 /* Destroy the jitterbuffer */
1917 ast_jb_destroy(chan);
1920 ast_cdr_discard(chan->cdr);
1925 chan->zone = ast_tone_zone_unref(chan->zone);
1928 ast_string_field_free_memory(chan);
1930 /* Queue an unknown state, because, while we know that this particular
1931 * instance is dead, we don't know the state of all other possible
1933 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, name);
1936 /*! \brief Free a dummy channel structure */
1937 static void ast_dummy_channel_destructor(void *obj)
1939 struct ast_channel *chan = obj;
1940 struct ast_var_t *vardata;
1941 struct varshead *headp;
1943 headp = &chan->varshead;
1945 free_cid(&chan->cid);
1947 /* loop over the variables list, freeing all data and deleting list items */
1948 /* no need to lock the list, as the channel is already locked */
1949 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1950 ast_var_delete(vardata);
1953 ast_cdr_discard(chan->cdr);
1957 ast_string_field_free_memory(chan);
1960 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1962 return ast_datastore_alloc(info, uid);
1965 int ast_channel_datastore_free(struct ast_datastore *datastore)
1967 return ast_datastore_free(datastore);
1970 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1972 struct ast_datastore *datastore = NULL, *datastore2;
1974 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1975 if (datastore->inheritance > 0) {
1976 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
1978 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
1979 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1980 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1987 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1991 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1996 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1998 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
2001 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2003 struct ast_datastore *datastore = NULL;
2008 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
2009 if (datastore->info != info) {
2014 /* matched by type only */
2018 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2019 /* Matched by type AND uid */
2023 AST_LIST_TRAVERSE_SAFE_END;
2028 /*! Set the file descriptor on the channel */
2029 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2032 struct epoll_event ev;
2033 struct ast_epoll_data *aed = NULL;
2035 if (chan->fds[which] > -1) {
2036 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2037 aed = chan->epfd_data[which];
2040 /* If this new fd is valid, add it to the epoll */
2042 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2045 chan->epfd_data[which] = aed;
2049 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2051 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2053 /* We don't have to keep around this epoll data structure now */
2055 chan->epfd_data[which] = NULL;
2058 chan->fds[which] = fd;
2062 /*! Add a channel to an optimized waitfor */
2063 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2066 struct epoll_event ev;
2069 if (chan0->epfd == -1)
2072 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2073 for (i = 0; i < AST_MAX_FDS; i++) {
2074 if (chan1->fds[i] == -1)
2076 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2077 ev.data.ptr = chan1->epfd_data[i];
2078 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2085 /*! Delete a channel from an optimized waitfor */
2086 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2089 struct epoll_event ev;
2092 if (chan0->epfd == -1)
2095 for (i = 0; i < AST_MAX_FDS; i++) {
2096 if (chan1->fds[i] == -1)
2098 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2105 /*! \brief Softly hangup a channel, don't lock */
2106 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2108 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
2109 /* Inform channel driver that we need to be hung up, if it cares */
2110 chan->_softhangup |= cause;
2111 ast_queue_frame(chan, &ast_null_frame);
2112 /* Interrupt any poll call or such */
2113 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2114 pthread_kill(chan->blocker, SIGURG);
2118 /*! \brief Softly hangup a channel, lock */
2119 int ast_softhangup(struct ast_channel *chan, int cause)
2123 ast_channel_lock(chan);
2124 res = ast_softhangup_nolock(chan, cause);
2125 ast_channel_unlock(chan);
2130 static void free_translation(struct ast_channel *clonechan)
2132 if (clonechan->writetrans)
2133 ast_translator_free_path(clonechan->writetrans);
2134 if (clonechan->readtrans)
2135 ast_translator_free_path(clonechan->readtrans);
2136 clonechan->writetrans = NULL;
2137 clonechan->readtrans = NULL;
2138 clonechan->rawwriteformat = clonechan->nativeformats;
2139 clonechan->rawreadformat = clonechan->nativeformats;
2142 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2144 struct ast_channel *bridge;
2146 ast_channel_lock(chan);
2147 if (force || ast_strlen_zero(chan->hangupsource)) {
2148 ast_string_field_set(chan, hangupsource, source);
2150 bridge = ast_bridged_channel(chan);
2151 ast_channel_unlock(chan);
2153 if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
2154 ast_channel_lock(bridge);
2155 ast_string_field_set(chan, hangupsource, source);
2156 ast_channel_unlock(bridge);
2160 /*! \brief Hangup a channel */
2161 int ast_hangup(struct ast_channel *chan)
2164 char extra_str[64]; /* used for cel logging below */
2166 /* Don't actually hang up a channel that will masquerade as someone else, or
2167 if someone is going to masquerade as us */
2168 ast_channel_lock(chan);
2170 if (chan->audiohooks) {
2171 ast_audiohook_detach_list(chan->audiohooks);
2172 chan->audiohooks = NULL;
2175 ast_autoservice_stop(chan);
2178 ast_channel_unlock(chan);
2179 if (ast_do_masquerade(chan)) {
2180 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2182 ast_channel_lock(chan);
2186 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
2187 ast_channel_unlock(chan);
2190 /* If this channel is one which will be masqueraded into something,
2191 mark it as a zombie already, so we know to free it later */
2193 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2194 ast_channel_unlock(chan);
2197 ast_channel_unlock(chan);
2199 ao2_unlink(channels, chan);
2201 ast_channel_lock(chan);
2202 free_translation(chan);
2203 /* Close audio stream */
2205 ast_closestream(chan->stream);
2206 chan->stream = NULL;
2208 /* Close video stream */
2209 if (chan->vstream) {
2210 ast_closestream(chan->vstream);
2211 chan->vstream = NULL;
2214 sched_context_destroy(chan->sched);
2218 if (chan->generatordata) /* Clear any tone stuff remaining */
2219 if (chan->generator && chan->generator->release)
2220 chan->generator->release(chan, chan->generatordata);
2221 chan->generatordata = NULL;
2222 chan->generator = NULL;
2224 snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2225 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2227 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2228 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2229 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2230 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
2231 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2233 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
2234 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
2235 if (chan->tech->hangup)
2236 res = chan->tech->hangup(chan);
2238 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
2241 ast_channel_unlock(chan);
2243 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2246 "CallerIDNum: %s\r\n"
2247 "CallerIDName: %s\r\n"
2249 "Cause-txt: %s\r\n",
2252 S_OR(chan->cid.cid_num, "<unknown>"),
2253 S_OR(chan->cid.cid_name, "<unknown>"),
2255 ast_cause2str(chan->hangupcause)
2258 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
2259 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
2260 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2261 ast_channel_lock(chan);
2263 ast_cdr_end(chan->cdr);
2264 ast_cdr_detach(chan->cdr);
2266 ast_channel_unlock(chan);
2269 chan = ast_channel_release(chan);
2274 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2278 ast_channel_lock(chan);
2280 /* You can't answer an outbound call */
2281 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2282 ast_channel_unlock(chan);
2286 /* Stop if we're a zombie or need a soft hangup */
2287 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2288 ast_channel_unlock(chan);
2292 ast_channel_unlock(chan);
2294 switch (chan->_state) {
2295 case AST_STATE_RINGING:
2296 case AST_STATE_RING:
2297 ast_channel_lock(chan);
2298 if (chan->tech->answer) {
2299 res = chan->tech->answer(chan);
2301 ast_setstate(chan, AST_STATE_UP);
2303 ast_cdr_answer(chan->cdr);
2305 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2306 ast_channel_unlock(chan);
2309 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2310 /* Calling ast_cdr_answer when it it has previously been called
2311 * is essentially a no-op, so it is safe.
2314 ast_cdr_answer(chan->cdr);
2321 ast_indicate(chan, -1);
2322 chan->visible_indication = 0;
2327 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2330 enum ast_channel_state old_state;
2332 old_state = chan->_state;
2333 if ((res = ast_raw_answer(chan, cdr_answer))) {
2337 switch (old_state) {
2338 case AST_STATE_RINGING:
2339 case AST_STATE_RING:
2340 /* wait for media to start flowing, but don't wait any longer
2341 * than 'delay' or 500 milliseconds, whichever is longer
2344 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2345 struct ast_frame *cur, *new;
2346 int ms = MAX(delay, 500);
2347 unsigned int done = 0;
2349 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2352 ms = ast_waitfor(chan, ms);
2354 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
2359 ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
2362 cur = ast_read(chan);
2363 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2364 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2369 ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
2373 if ((new = ast_frisolate(cur)) != cur) {
2377 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2379 /* if a specific delay period was requested, continue
2380 * until that delay has passed. don't stop just because
2381 * incoming media has arrived.
2387 switch (new->frametype) {
2388 /* all of these frametypes qualify as 'media' */
2389 case AST_FRAME_VOICE:
2390 case AST_FRAME_VIDEO:
2391 case AST_FRAME_TEXT:
2392 case AST_FRAME_DTMF_BEGIN:
2393 case AST_FRAME_DTMF_END:
2394 case AST_FRAME_IMAGE:
2395 case AST_FRAME_HTML:
2396 case AST_FRAME_MODEM:
2399 case AST_FRAME_CONTROL:
2401 case AST_FRAME_NULL:
2412 ast_channel_lock(chan);
2413 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2414 ast_queue_frame_head(chan, cur);
2417 ast_channel_unlock(chan);
2428 int ast_answer(struct ast_channel *chan)
2430 return __ast_answer(chan, 0, 1);
2433 void ast_deactivate_generator(struct ast_channel *chan)
2435 ast_channel_lock(chan);
2436 if (chan->generatordata) {
2437 if (chan->generator && chan->generator->release)
2438 chan->generator->release(chan, chan->generatordata);
2439 chan->generatordata = NULL;
2440 chan->generator = NULL;
2441 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2442 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2443 ast_settimeout(chan, 0, NULL, NULL);
2445 ast_channel_unlock(chan);
2448 static int generator_force(const void *data)
2450 /* Called if generator doesn't have data */
2453 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2454 struct ast_channel *chan = (struct ast_channel *)data;
2456 ast_channel_lock(chan);
2457 tmp = chan->generatordata;
2458 chan->generatordata = NULL;
2459 if (chan->generator)
2460 generate = chan->generator->generate;
2461 ast_channel_unlock(chan);
2463 if (!tmp || !generate)
2466 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
2468 chan->generatordata = tmp;
2471 ast_debug(1, "Auto-deactivating generator\n");
2472 ast_deactivate_generator(chan);
2478 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2482 ast_channel_lock(chan);
2484 if (chan->generatordata) {
2485 if (chan->generator && chan->generator->release)
2486 chan->generator->release(chan, chan->generatordata);
2487 chan->generatordata = NULL;
2491 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2496 ast_settimeout(chan, 50, generator_force, chan);
2497 chan->generator = gen;
2500 ast_channel_unlock(chan);
2505 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2506 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2509 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2513 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2515 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2516 int *exception, int *outfd, int *ms)
2518 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2519 int *exception, int *outfd, int *ms)
2522 struct timeval start = { 0 , 0 };
2523 struct pollfd *pfds = NULL;
2528 struct timeval now = { 0, 0 };
2529 struct timeval whentohangup = { 0, 0 }, diff;
2530 struct ast_channel *winner = NULL;
2536 if ((sz = n * AST_MAX_FDS + nfds)) {
2537 pfds = alloca(sizeof(*pfds) * sz);
2538 fdmap = alloca(sizeof(*fdmap) * sz);
2546 /* Perform any pending masquerades */
2547 for (x = 0; x < n; x++) {
2548 if (c[x]->masq && ast_do_masquerade(c[x])) {
2549 ast_log(LOG_WARNING, "Masquerade failed\n");
2554 ast_channel_lock(c[x]);
2555 if (!ast_tvzero(c[x]->whentohangup)) {
2556 if (ast_tvzero(whentohangup))
2558 diff = ast_tvsub(c[x]->whentohangup, now);
2559 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
2560 /* Should already be hungup */
2561 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2562 ast_channel_unlock(c[x]);
2565 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
2566 whentohangup = diff;
2568 ast_channel_unlock(c[x]);
2570 /* Wait full interval */
2572 if (!ast_tvzero(whentohangup)) {
2573 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
2574 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
2578 * Build the pollfd array, putting the channels' fds first,
2579 * followed by individual fds. Order is important because
2580 * individual fd's must have priority over channel fds.
2583 for (x = 0; x < n; x++) {
2584 for (y = 0; y < AST_MAX_FDS; y++) {
2585 fdmap[max].fdno = y; /* fd y is linked to this pfds */
2586 fdmap[max].chan = x; /* channel x is linked to this pfds */
2587 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
2589 CHECK_BLOCKING(c[x]);
2591 /* Add the individual fds */
2592 for (x = 0; x < nfds; x++) {
2593 fdmap[max].chan = -1;
2594 max += ast_add_fd(&pfds[max], fds[x]);
2598 start = ast_tvnow();
2600 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
2605 res = ast_poll(pfds, max, kbrms);
2608 } while (!res && (rms > 0));
2610 res = ast_poll(pfds, max, rms);
2612 for (x = 0; x < n; x++)
2613 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
2614 if (res < 0) { /* Simulate a timeout if we were interrupted */
2619 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
2621 for (x = 0; x < n; x++) {
2622 if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
2623 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2629 if (res == 0) { /* no fd ready, reset timeout and done */
2630 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
2634 * Then check if any channel or fd has a pending event.
2635 * Remember to check channels first and fds last, as they
2636 * must have priority on setting 'winner'
2638 for (x = 0; x < max; x++) {
2639 res = pfds[x].revents;
2642 if (fdmap[x].chan >= 0) { /* this is a channel */
2643 winner = c[fdmap[x].chan]; /* override previous winners */
2645 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2647 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2648 winner->fdno = fdmap[x].fdno;
2649 } else { /* this is an fd */
2651 *outfd = pfds[x].fd;
2653 *exception = (res & POLLPRI) ? -1 : 0;
2658 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2666 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
2668 struct timeval start = { 0 , 0 };
2670 struct epoll_event ev[1];
2671 long diff, rms = *ms;
2672 struct ast_channel *winner = NULL;
2673 struct ast_epoll_data *aed = NULL;
2676 /* See if this channel needs to be masqueraded */
2677 if (chan->masq && ast_do_masquerade(chan)) {
2678 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
2683 ast_channel_lock(chan);
2684 /* Figure out their timeout */
2685 if (!ast_tvzero(chan->whentohangup)) {
2686 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
2687 /* They should already be hungup! */
2688 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2689 ast_channel_unlock(chan);
2692 /* If this value is smaller then the current one... make it priority */
2697 ast_channel_unlock(chan);
2699 /* Time to make this channel block... */
2700 CHECK_BLOCKING(chan);
2703 start = ast_tvnow();
2705 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
2706 res = epoll_wait(chan->epfd, ev, 1, rms);
2709 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2711 /* Simulate a timeout if we were interrupted */
2718 /* If this channel has a timeout see if it expired */
2719 if (!ast_tvzero(chan->whentohangup)) {
2720 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
2721 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2726 /* No fd ready, reset timeout and be done for now */
2732 /* See what events are pending */
2733 aed = ev[0].data.ptr;
2734 chan->fdno = aed->which;
2735 if (ev[0].events & EPOLLPRI)
2736 ast_set_flag(chan, AST_FLAG_EXCEPTION);
2738 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2741 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2749 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2751 struct timeval start = { 0 , 0 };
2753 struct epoll_event ev[25] = { { 0, } };
2754 struct timeval now = { 0, 0 };
2755 long whentohangup = 0, diff = 0, rms = *ms;
2756 struct ast_channel *winner = NULL;
2758 for (i = 0; i < n; i++) {
2759 if (c[i]->masq && ast_do_masquerade(c[i])) {
2760 ast_log(LOG_WARNING, "Masquerade failed\n");
2765 ast_channel_lock(c[i]);
2766 if (!ast_tvzero(c[i]->whentohangup)) {
2767 if (whentohangup == 0)
2769 if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
2770 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2771 ast_channel_unlock(c[i]);
2774 if (!whentohangup || whentohangup > diff)
2775 whentohangup = diff;
2777 ast_channel_unlock(c[i]);
2778 CHECK_BLOCKING(c[i]);
2784 if (*ms >= 0 && *ms < rms)
2789 start = ast_tvnow();
2791 res = epoll_wait(c[0]->epfd, ev, 25, rms);
2793 for (i = 0; i < n; i++)
2794 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2804 for (i = 0; i < n; i++) {
2805 if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
2806 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2818 for (i = 0; i < res; i++) {
2819 struct ast_epoll_data *aed = ev[i].data.ptr;
2821 if (!ev[i].events || !aed)
2825 if (ev[i].events & EPOLLPRI)
2826 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2828 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2829 winner->fdno = aed->which;
2833 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2841 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2842 int *exception, int *outfd, int *ms)
2844 /* Clear all provided values in one place. */
2850 /* If no epoll file descriptor is available resort to classic nandfds */
2851 if (!n || nfds || c[0]->epfd == -1)
2852 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2853 else if (!nfds && n == 1)
2854 return ast_waitfor_nandfds_simple(c[0], ms);
2856 return ast_waitfor_nandfds_complex(c, n, ms);
2860 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2862 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2865 int ast_waitfor(struct ast_channel *c, int ms)
2867 int oldms = ms; /* -1 if no timeout */
2869 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2870 if ((ms < 0) && (oldms < 0))
2875 /* XXX never to be called with ms = -1 */
2876 int ast_waitfordigit(struct ast_channel *c, int ms)
2878 return ast_waitfordigit_full(c, ms, -1, -1);
2881 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
2884 unsigned int real_rate = rate, max_rate;
2886 ast_channel_lock(c);
2888 if (c->timingfd == -1) {
2889 ast_channel_unlock(c);
2898 if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
2899 real_rate = max_rate;
2902 ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
2904 res = ast_timer_set_rate(c->timer, real_rate);
2906 c->timingfunc = func;
2907 c->timingdata = data;
2909 ast_channel_unlock(c);
2914 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2916 /* Stop if we're a zombie or need a soft hangup */
2917 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2920 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2921 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2923 /* Wait for a digit, no more than ms milliseconds total. */
2926 struct ast_channel *rchan;
2930 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2932 if (!rchan && outfd < 0 && ms) {
2933 if (errno == 0 || errno == EINTR)
2935 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2936 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2938 } else if (outfd > -1) {
2939 /* The FD we were watching has something waiting */
2940 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2941 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2945 struct ast_frame *f = ast_read(c);
2949 switch (f->frametype) {
2950 case AST_FRAME_DTMF_BEGIN:
2952 case AST_FRAME_DTMF_END:
2953 res = f->subclass.integer;
2955 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2957 case AST_FRAME_CONTROL:
2958 switch (f->subclass.integer) {
2959 case AST_CONTROL_HANGUP:
2961 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2963 case AST_CONTROL_RINGING:
2964 case AST_CONTROL_ANSWER:
2965 case AST_CONTROL_SRCUPDATE:
2966 case AST_CONTROL_SRCCHANGE:
2967 case AST_CONTROL_CONNECTED_LINE:
2968 case AST_CONTROL_REDIRECTING:
2972 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
2976 case AST_FRAME_VOICE:
2977 /* Write audio if appropriate */
2979 if (write(audiofd, f->data.ptr, f->datalen) < 0) {
2980 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
2991 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2993 return 0; /* Time is up */
2996 static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2998 ast_manager_event(chan, EVENT_FLAG_DTMF,
3006 chan->name, chan->uniqueid, digit, direction, begin, end);
3009 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
3011 if (chan->generator && chan->generator->generate && chan->generatordata && !ast_internal_timing_enabled(chan)) {
3012 void *tmp = chan->generatordata;
3013 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = chan->generator->generate;
3017 if (chan->timingfunc) {
3018 ast_debug(1, "Generator got voice, switching to phase locked mode\n");
3019 ast_settimeout(chan, 0, NULL, NULL);
3022 chan->generatordata = NULL; /* reset, to let writes go through */
3024 if (f->subclass.codec != chan->writeformat) {
3026 factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass.codec));
3027 samples = (int) ( ((float) f->samples) * factor );
3029 samples = f->samples;
3032 /* This unlock is here based on two assumptions that hold true at this point in the
3033 * code. 1) this function is only called from within __ast_read() and 2) all generators
3034 * call ast_write() in their generate callback.
3036 * The reason this is added is so that when ast_write is called, the lock that occurs
3037 * there will not recursively lock the channel. Doing this will cause intended deadlock
3038 * avoidance not to work in deeper functions
3040 ast_channel_unlock(chan);
3041 res = generate(chan, tmp, f->datalen, samples);
3042 ast_channel_lock(chan);
3043 chan->generatordata = tmp;
3045 ast_debug(1, "Auto-deactivating generator\n");
3046 ast_deactivate_generator(chan);
3049 } else if (f->frametype == AST_FRAME_CNG) {
3050 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
3051 ast_debug(1, "Generator got CNG, switching to timed mode\n");
3052 ast_settimeout(chan, 50, generator_force, chan);
3057 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3059 struct ast_frame *fr = &chan->dtmff;
3061 fr->frametype = AST_FRAME_DTMF_END;
3062 fr->subclass.integer = f->subclass.integer;
3065 /* The only time this function will be called is for a frame that just came
3066 * out of the channel driver. So, we want to stick it on the tail of the
3069 ast_queue_frame(chan, fr);
3073 * \brief Determine whether or not we should ignore DTMF in the readq
3075 static inline int should_skip_dtmf(struct ast_channel *chan)
3077 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
3078 /* We're in the middle of emulating a digit, or DTMF has been
3079 * explicitly deferred. Skip this digit, then. */
3083 if (!ast_tvzero(chan->dtmf_tv) &&
3084 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3085 /* We're not in the middle of a digit, but it hasn't been long enough
3086 * since the last digit, so we'll have to skip DTMF for now. */
3094 * \brief calculates the number of samples to jump forward with in a monitor stream.
3096 * \note When using ast_seekstream() with the read and write streams of a monitor,
3097 * the number of samples to seek forward must be of the same sample rate as the stream
3098 * or else the jump will not be calculated correctly.
3100 * \retval number of samples to seek forward after rate conversion.
3102 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
3104 int diff = sample_rate - seek_rate;
3107 samples = samples / (float) (sample_rate / seek_rate);
3108 } else if (diff < 0) {
3109 samples = samples * (float) (seek_rate / sample_rate);
3115 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
3117 struct ast_frame *f = NULL; /* the return value */
3122 /* this function is very long so make sure there is only one return
3123 * point at the end (there are only two exceptions to this).
3127 if (ast_do_masquerade(chan))
3128 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
3130 f = &ast_null_frame;
3134 /* if here, no masq has happened, lock the channel and proceed */
3135 ast_channel_lock(chan);
3137 /* Stop if we're a zombie or need a soft hangup */
3138 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
3139 if (chan->generator)
3140 ast_deactivate_generator(chan);
3146 * The ast_waitfor() code records which of the channel's file descriptors reported that
3147 * data is available. In theory, ast_read() should only be called after ast_waitfor()
3148 * reports that a channel has data available for reading. However, there still may be
3149 * some edge cases throughout the code where ast_read() is called improperly. This can
3150 * potentially cause problems, so if this is a developer build, make a lot of noise if
3151 * this happens so that it can be addressed.
3153 if (chan->fdno == -1) {
3154 ast_log(LOG_ERROR, "ast_read() called with no recorded file descriptor.\n");
3158 prestate = chan->_state;
3160 /* Read and ignore anything on the alertpipe, but read only
3161 one sizeof(blah) per frame that we send from it */
3162 if (chan->alertpipe[0] > -1) {
3163 int flags = fcntl(chan->alertpipe[0], F_GETFL);
3164 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
3165 * which immediately causes a deadlock scenario. Detect and prevent this. */
3166 if ((flags & O_NONBLOCK) == 0) {
3167 ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
3168 if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
3169 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
3170 f = &ast_null_frame;
3174 if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
3175 if (errno != EINTR && errno != EAGAIN)
3176 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
3180 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
3181 enum ast_timer_event res;
3183 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3185 res = ast_timer_get_event(chan->timer);
3188 case AST_TIMING_EVENT_EXPIRED:
3189 ast_timer_ack(chan->timer, 1);
3191 if (chan->timingfunc) {
3192 /* save a copy of func/data before unlocking the channel */
3193 int (*func)(const void *) = chan->timingfunc;
3194 void *data = chan->timingdata;
3196 ast_channel_unlock(chan);
3199 ast_timer_set_rate(chan->timer, 0);
3201 ast_channel_unlock(chan);
3204 /* cannot 'goto done' because the channel is already unlocked */
3205 return &ast_null_frame;
3207 case AST_TIMING_EVENT_CONTINUOUS:
3208 if (AST_LIST_EMPTY(&chan->readq) ||
3209 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
3210 ast_timer_disable_continuous(chan->timer);
3215 } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
3216 /* if the AST_GENERATOR_FD is set, call the generator with args
3217 * set to -1 so it can do whatever it needs to.
3219 void *tmp = chan->generatordata;
3220 chan->generatordata = NULL; /* reset to let ast_write get through */
3221 chan->generator->generate(chan, tmp, -1, -1);
3222 chan->generatordata = tmp;
3223 f = &ast_null_frame;
3228 /* Check for pending read queue */
3229 if (!AST_LIST_EMPTY(&chan->readq)) {
3230 int skip_dtmf = should_skip_dtmf(chan);
3232 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
3233 /* We have to be picky about which frame we pull off of the readq because
3234 * there are cases where we want to leave DTMF frames on the queue until
3235 * some later time. */
3237 if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
3241 AST_LIST_REMOVE_CURRENT(frame_list);
3244 AST_LIST_TRAVERSE_SAFE_END;
3247 /* There were no acceptable frames on the readq. */
3248 f = &ast_null_frame;
3249 if (chan->alertpipe[0] > -1) {
3251 /* Restore the state of the alertpipe since we aren't ready for any
3252 * of the frames in the readq. */
3253 if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
3254 ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
3259 /* Interpret hangup and return NULL */
3260 /* XXX why not the same for frames from the channel ? */
3261 if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
3262 cause = f->data.uint32;
3267 chan->blocker = pthread_self();
3268 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
3269 if (chan->tech->exception)
3270 f = chan->tech->exception(chan);
3272 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
3273 f = &ast_null_frame;
3275 /* Clear the exception flag */
3276 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3277 } else if (chan->tech->read)
3278 f = chan->tech->read(chan);
3280 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
3284 * Reset the recorded file descriptor that triggered this read so that we can
3285 * easily detect when ast_read() is called without properly using ast_waitfor().
3290 struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
3292 /* if the channel driver returned more than one frame, stuff the excess
3293 into the readq for the next ast_read call
3295 if (AST_LIST_NEXT(f, frame_list)) {
3296 ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
3297 ast_frfree(AST_LIST_NEXT(f, frame_list));
3298 AST_LIST_NEXT(f, frame_list) = NULL;
3301 switch (f->frametype) {
3302 case AST_FRAME_CONTROL:
3303 if (f->subclass.integer == AST_CONTROL_ANSWER) {
3304 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
3305 ast_debug(1, "Ignoring answer on an inbound call!\n");
3307 f = &ast_null_frame;
3308 } else if (prestate == AST_STATE_UP) {
3309 ast_debug(1, "Dropping duplicate answer!\n");
3311 f = &ast_null_frame;
3313 /* Answer the CDR */
3314 ast_setstate(chan, AST_STATE_UP);
3315 /* removed a call to ast_cdr_answer(chan->cdr) from here. */
3316 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
3320 case AST_FRAME_DTMF_END:
3321 send_dtmf_event(chan, "Received", f->subclass.integer, "No", "Yes");
3322 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass.integer, chan->name, f->len);
3323 /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
3324 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
3325 queue_dtmf_readq(chan, f);
3327 f = &ast_null_frame;
3328 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
3329 if (!ast_tvzero(chan->dtmf_tv) &&
3330 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3331 /* If it hasn't been long enough, defer this digit */
3332 queue_dtmf_readq(chan, f);
3334 f = &ast_null_frame;
3336 /* There was no begin, turn this into a begin and send the end later */
3337 f->frametype = AST_FRAME_DTMF_BEGIN;
3338 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
3339 chan->emulate_dtmf_digit = f->subclass.integer;
3340 chan->dtmf_tv = ast_tvnow();
3342 if (f->len > AST_MIN_DTMF_DURATION)
3343 chan->emulate_dtmf_duration = f->len;
3345 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
3347 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
3348 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass.integer, chan->emulate_dtmf_duration, chan->name);
3350 if (chan->audiohooks) {
3351 struct ast_frame *old_frame = f;
3353 * \todo XXX It is possible to write a digit to the audiohook twice
3354 * if the digit was originally read while the channel was in autoservice. */
3355 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3357 ast_frfree(old_frame);
3360 struct timeval now = ast_tvnow();
3361 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
3362 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass.integer, chan->name);
3363 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
3365 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3366 } else if (!f->len) {
3367 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass.integer, chan->name);
3368 f->len = AST_MIN_DTMF_DURATION;
3370 if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
3371 ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f->subclass.integer, f->len, AST_MIN_DTMF_DURATION, chan->name);
3372 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
3373 chan->emulate_dtmf_digit = f->subclass.integer;
3374 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
3376 f = &ast_null_frame;
3378 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass.integer, chan->name);
3379 if (f->len < AST_MIN_DTMF_DURATION) {
3380 f->len = AST_MIN_DTMF_DURATION;
3382 chan->dtmf_tv = now;
3384 if (chan->audiohooks) {
3385 struct ast_frame *old_frame = f;
3386 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3388 ast_frfree(old_frame);
3392 case AST_FRAME_DTMF_BEGIN:
3393 send_dtmf_event(chan, "Received", f->subclass.integer, "Yes", "No");
3394 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass.integer, chan->name);
3395 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
3396 (!ast_tvzero(chan->dtmf_tv) &&
3397 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
3398 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass.integer, chan->name);
3400 f = &ast_null_frame;
3402 ast_set_flag(chan, AST_FLAG_IN_DTMF);
3403 chan->dtmf_tv = ast_tvnow();
3404 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass.integer, chan->name);
3407 case AST_FRAME_NULL:
3408 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
3409 * is reached , because we want to make sure we pass at least one
3410 * voice frame through before starting the next digit, to ensure a gap
3411 * between DTMF digits. */
3412 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
3413 struct timeval now = ast_tvnow();
3414 if (!chan->emulate_dtmf_duration) {
3415 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
3416 chan->emulate_dtmf_digit = 0;
3417 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
3418 chan->emulate_dtmf_duration = 0;
3421 f->frametype = AST_FRAME_DTMF_END;
3422 f->subclass.integer = chan->emulate_dtmf_digit;
3423 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3424 chan->dtmf_tv = now;
3425 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
3426 chan->emulate_dtmf_digit = 0;
3427 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, chan->name);
3428 if (chan->audiohooks) {
3429 struct ast_frame *old_frame = f;
3430 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3431 if (old_frame != f) {
3432 ast_frfree(old_frame);
3438 case AST_FRAME_VOICE:
3439 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
3440 * is reached , because we want to make sure we pass at least one
3441 * voice frame through before starting the next digit, to ensure a gap
3442 * between DTMF digits. */
3443 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
3444 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
3445 chan->emulate_dtmf_digit = 0;
3448 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
3450 ast_read_generator_actions(chan, f);
3452 f = &ast_null_frame;
3455 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
3456 struct timeval now = ast_tvnow();
3457 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
3458 chan->emulate_dtmf_duration = 0;
3461 f->frametype = AST_FRAME_DTMF_END;
3462 f->subclass.integer = chan->emulate_dtmf_digit;
3463 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
3464 chan->dtmf_tv = now;
3465 if (chan->audiohooks) {
3466 struct ast_frame *old_frame = f;
3467 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3469 ast_frfree(old_frame);
3471 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, chan->name);
3473 /* Drop voice frames while we're still in the middle of the digit */
3475 f = &ast_null_frame;
3477 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass.codec & chan->nativeformats)) {
3478 /* This frame is not one of the current native formats -- drop it on the floor */
3480 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
3481 chan->name, ast_getformatname(f->subclass.codec), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
3483 f = &ast_null_frame;
3484 } else if ((f->frametype == AST_FRAME_VOICE)) {
3485 /* Send frame to audiohooks if present */
3486 if (chan->audiohooks) {
3487 struct ast_frame *old_frame = f;
3488 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
3490 ast_frfree(old_frame);
3492 if (chan->monitor && chan->monitor->read_stream ) {
3493 /* XXX what does this do ? */
3494 #ifndef MONITOR_CONSTANT_DELAY
3495 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
3497 jump = calc_monitor_jump((chan->outsmpl - chan->insmpl), ast_format_rate(f->subclass.codec), ast_format_rate(chan->monitor->read_stream->fmt->format));
3498 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
3499 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
3500 chan->insmpl += (chan->outsmpl - chan->insmpl) + f->samples;
3502 chan->insmpl+= f->samples;
3504 int jump = calc_monitor_jump((chan->outsmpl - chan->insmpl), ast_format_rate(f->subclass.codec), ast_format_rate(chan->monitor->read_stream->fmt->format));
3505 if (jump - MONITOR_DELAY >= 0) {
3506 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
3507 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
3508 chan->insmpl += chan->outsmpl - chan->insmpl;
3510 chan->insmpl += f->samples;
3512 if (chan->monitor->state == AST_MONITOR_RUNNING) {
3513 if (ast_writestream(chan->monitor->read_stream, f) < 0)
3514 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
3518 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL) {
3519 f = &ast_null_frame;
3522 /* it is possible for the translation process on chan->readtrans to have
3523 produced multiple frames from the single input frame we passed it; if
3524 this happens, queue the additional frames *before* the frames we may
3525 have queued earlier. if the readq was empty, put them at the head of
3526 the queue, and if it was not, put them just after the frame that was
3527 at the end of the queue.
3529 if (AST_LIST_NEXT(f, frame_list)) {
3531 ast_queue_frame_head(chan, AST_LIST_NEXT(f, frame_list));
3533 __ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list), 0, readq_tail);
3535 ast_frfree(AST_LIST_NEXT(f, frame_list));
3536 AST_LIST_NEXT(f, frame_list) = NULL;
3539 /* Run generator sitting on the line if timing device not available
3540 * and synchronous generation of outgoing frames is necessary */
3541 ast_read_generator_actions(chan, f);
3544 /* Just pass it on! */
3548 /* Make sure we always return NULL in the future */
3549 chan->_softhangup |= AST_SOFTHANGUP_DEV;
3551 chan->hangupcause = cause;
3552 if (chan->generator)
3553 ast_deactivate_generator(chan);
3554 /* We no longer End the CDR here */
3557 /* High bit prints debugging */
3558 if (chan->fin & DEBUGCHAN_FLAG)
3559 ast_frame_dump(chan->name, f, "<<");
3560 chan->fin = FRAMECOUNT_INC(chan->fin);
3563 if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
3564 chan->generator->digit(chan, f->subclass.integer);
3566 ast_channel_unlock(chan);
3570 int ast_internal_timing_enabled(struct ast_channel *chan)
3572 return (ast_opt_internal_timing && chan->timingfd > -1);
3575 struct ast_frame *ast_read(struct ast_channel *chan)
3577 return __ast_read(chan, 0);
3580 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
3582 return __ast_read(chan, 1);
3585 int ast_indicate(struct ast_channel *chan, int condition)
3587 return ast_indicate_data(chan, condition, NULL, 0);
3590 static int attribute_const is_visible_indication(enum ast_control_frame_type condition)
3592 /* Don't include a default case here so that we get compiler warnings
3593 * when a new type is added. */
3595 switch (condition) {
3596 case AST_CONTROL_PROGRESS:
3597 case AST_CONTROL_PROCEEDING:
3598 case AST_CONTROL_VIDUPDATE:
3599 case AST_CONTROL_SRCUPDATE:
3600 case AST_CONTROL_SRCCHANGE:
3601 case AST_CONTROL_RADIO_KEY:
3602 case AST_CONTROL_RADIO_UNKEY:
3603 case AST_CONTROL_OPTION:
3604 case AST_CONTROL_WINK:
3605 case AST_CONTROL_FLASH:
3606 case AST_CONTROL_OFFHOOK:
3607 case AST_CONTROL_TAKEOFFHOOK:
3608 case AST_CONTROL_ANSWER:
3609 case AST_CONTROL_HANGUP:
3610 case AST_CONTROL_CONNECTED_LINE:
3611 case AST_CONTROL_REDIRECTING:
3612 case AST_CONTROL_TRANSFER:
3613 case AST_CONTROL_T38_PARAMETERS:
3614 case _XXX_AST_CONTROL_T38:
3615 case AST_CONTROL_CC:
3618 case AST_CONTROL_CONGESTION:
3619 case AST_CONTROL_BUSY:
3620 case AST_CONTROL_RINGING:
3621 case AST_CONTROL_RING:
3622 case AST_CONTROL_HOLD:
3623 case AST_CONTROL_UNHOLD:
3630 int ast_indicate_data(struct ast_channel *chan, int _condition,
3631 const void *data, size_t datalen)
3633 /* By using an enum, we'll get compiler warnings for values not handled
3634 * in switch statements. */
3635 enum ast_control_frame_type condition = _condition;
3636 struct ast_tone_zone_sound *ts = NULL;
3639 ast_channel_lock(chan);
3641 /* Don't bother if the channel is about to go away, anyway. */
3642 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
3643 ast_channel_unlock(chan);
3646 switch (condition) {
3647 case AST_CONTROL_CONNECTED_LINE:
3649 struct ast_party_connected_line connected;
3651 ast_party_connected_line_set_init(&connected, &chan->connected);
3652 res = ast_connected_line_parse_data(data, datalen, &connected);
3654 ast_channel_set_connected_line(chan, &connected);
3656 ast_party_connected_line_free(&connected);
3660 case AST_CONTROL_REDIRECTING:
3662 struct ast_party_redirecting redirecting;
3664 ast_party_redirecting_set_init(&redirecting, &chan->redirecting);
3665 res = ast_redirecting_parse_data(data, datalen, &redirecting);
3667 ast_channel_set_redirecting(chan, &redirecting);
3669 ast_party_redirecting_free(&redirecting);
3677 if (chan->tech->indicate) {
3678 /* See if the channel driver can handle this condition. */
3679 res = chan->tech->indicate(chan, condition, data, datalen);