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/sched.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/musiconhold.h"
43 #include "asterisk/say.h"
44 #include "asterisk/file.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/translate.h"
47 #include "asterisk/manager.h"
48 #include "asterisk/cel.h"
49 #include "asterisk/chanvars.h"
50 #include "asterisk/linkedlists.h"
51 #include "asterisk/indications.h"
52 #include "asterisk/monitor.h"
53 #include "asterisk/causes.h"
54 #include "asterisk/callerid.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/lock.h"
57 #include "asterisk/app.h"
58 #include "asterisk/transcap.h"
59 #include "asterisk/devicestate.h"
60 #include "asterisk/sha1.h"
61 #include "asterisk/threadstorage.h"
62 #include "asterisk/slinfactory.h"
63 #include "asterisk/audiohook.h"
64 #include "asterisk/timing.h"
65 #include "asterisk/autochan.h"
66 #include "asterisk/stringfields.h"
69 #include <sys/epoll.h>
72 struct ast_epoll_data {
73 struct ast_channel *chan;
77 /* uncomment if you have problems with 'monitoring' synchronized files */
79 #define MONITOR_CONSTANT_DELAY
80 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
83 /*! \brief Prevent new channel allocation if shutting down. */
84 static int shutting_down;
88 unsigned long global_fin, global_fout;
90 AST_THREADSTORAGE(state2str_threadbuf);
91 #define STATE2STR_BUFSIZE 32
93 /*! Default amount of time to use when emulating a digit as a begin and end
95 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
97 /*! Minimum allowed digit length - 80ms */
98 #define AST_MIN_DTMF_DURATION 80
100 /*! Minimum amount of time between the end of the last digit and the beginning
101 * of a new one - 45ms */
102 #define AST_MIN_DTMF_GAP 45
104 /*! \brief List of channel drivers */
106 const struct ast_channel_tech *tech;
107 AST_LIST_ENTRY(chanlist) list;
111 /*! \brief Structure to hold channel context backtrace data */
112 struct ast_chan_trace_data {
114 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
117 /*! \brief Structure to save contexts where an ast_chan has been into */
118 struct ast_chan_trace {
119 char context[AST_MAX_CONTEXT];
120 char exten[AST_MAX_EXTENSION];
122 AST_LIST_ENTRY(ast_chan_trace) entry;
126 /*! \brief the list of registered channel types */
127 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
130 #define NUM_CHANNEL_BUCKETS 61
132 #define NUM_CHANNEL_BUCKETS 1567
135 /*! \brief All active channels on the system */
136 static struct ao2_container *channels;
138 /*! \brief map AST_CAUSE's to readable string representations
142 static const struct {
147 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
148 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
149 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
150 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
151 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
152 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
153 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
154 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
155 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
156 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
157 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
158 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
159 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
160 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
161 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
162 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
163 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
164 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
165 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
166 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
167 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
168 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
169 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
170 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
171 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
172 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
173 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
174 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
175 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
176 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
177 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
178 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
179 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
180 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
181 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
182 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
183 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
184 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
185 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
186 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
187 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
188 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
189 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
190 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
193 struct ast_variable *ast_channeltype_list(void)
196 struct ast_variable *var = NULL, *prev = NULL;
198 AST_RWLIST_RDLOCK(&backends);
199 AST_RWLIST_TRAVERSE(&backends, cl, list) {
201 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
204 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
208 AST_RWLIST_UNLOCK(&backends);
213 /*! \brief Show channel types - CLI command */
214 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
216 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
222 e->command = "core show channeltypes";
224 "Usage: core show channeltypes\n"
225 " Lists available channel types registered in your\n"
226 " Asterisk server.\n";
233 return CLI_SHOWUSAGE;
235 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
236 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
238 AST_RWLIST_RDLOCK(&backends);
239 AST_RWLIST_TRAVERSE(&backends, cl, list) {
240 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
241 (cl->tech->devicestate) ? "yes" : "no",
242 (cl->tech->indicate) ? "yes" : "no",
243 (cl->tech->transfer) ? "yes" : "no");
246 AST_RWLIST_UNLOCK(&backends);
248 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
255 static char *complete_channeltypes(struct ast_cli_args *a)
265 wordlen = strlen(a->word);
267 AST_RWLIST_RDLOCK(&backends);
268 AST_RWLIST_TRAVERSE(&backends, cl, list) {
269 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
270 ret = ast_strdup(cl->tech->type);
274 AST_RWLIST_UNLOCK(&backends);
279 /*! \brief Show details about a channel driver - CLI command */
280 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
282 struct chanlist *cl = NULL;
287 e->command = "core show channeltype";
289 "Usage: core show channeltype <name>\n"
290 " Show details about the specified channel type, <name>.\n";
293 return complete_channeltypes(a);
297 return CLI_SHOWUSAGE;
299 AST_RWLIST_RDLOCK(&backends);
301 AST_RWLIST_TRAVERSE(&backends, cl, list) {
302 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
308 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
309 AST_RWLIST_UNLOCK(&backends);
314 "-- Info about channel driver: %s --\n"
315 " Device State: %s\n"
318 " Capabilities: %s\n"
322 " Image Support: %s\n"
323 " Text Support: %s\n",
325 (cl->tech->devicestate) ? "yes" : "no",
326 (cl->tech->indicate) ? "yes" : "no",
327 (cl->tech->transfer) ? "yes" : "no",
328 ast_getformatname_multiple(buf, sizeof(buf), (cl->tech->capabilities) ? cl->tech->capabilities : -1),
329 (cl->tech->send_digit_begin) ? "yes" : "no",
330 (cl->tech->send_digit_end) ? "yes" : "no",
331 (cl->tech->send_html) ? "yes" : "no",
332 (cl->tech->send_image) ? "yes" : "no",
333 (cl->tech->send_text) ? "yes" : "no"
337 AST_RWLIST_UNLOCK(&backends);
342 static struct ast_cli_entry cli_channel[] = {
343 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
344 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
348 /*! \brief Destructor for the channel trace datastore */
349 static void ast_chan_trace_destroy_cb(void *data)
351 struct ast_chan_trace *trace;
352 struct ast_chan_trace_data *traced = data;
353 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
359 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
360 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
362 .destroy = ast_chan_trace_destroy_cb
365 /*! \brief Put the channel backtrace in a string */
366 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
369 struct ast_chan_trace *trace;
370 struct ast_chan_trace_data *traced;
371 struct ast_datastore *store;
373 ast_channel_lock(chan);
374 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
376 ast_channel_unlock(chan);
379 traced = store->data;
381 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
382 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
383 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
389 ast_channel_unlock(chan);
393 /* !\brief Whether or not context tracing is enabled */
394 int ast_channel_trace_is_enabled(struct ast_channel *chan)
396 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
399 return ((struct ast_chan_trace_data *)store->data)->enabled;
402 /*! \brief Update the context backtrace data if tracing is enabled */
403 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
405 struct ast_chan_trace *trace;
406 if (!traced->enabled)
408 /* If the last saved context does not match the current one
409 OR we have not saved any context so far, then save the current context */
410 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) ||
411 (AST_LIST_EMPTY(&traced->trace))) {
412 /* Just do some debug logging */
413 if (AST_LIST_EMPTY(&traced->trace))
414 ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
416 ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
417 /* alloc or bail out */
418 trace = ast_malloc(sizeof(*trace));
421 /* save the current location and store it in the trace list */
422 ast_copy_string(trace->context, chan->context, sizeof(trace->context));
423 ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
424 trace->priority = chan->priority;
425 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
430 /*! \brief Update the context backtrace if tracing is enabled */
431 int ast_channel_trace_update(struct ast_channel *chan)
433 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
436 return ast_channel_trace_data_update(chan, store->data);
439 /*! \brief Enable context tracing in the channel */
440 int ast_channel_trace_enable(struct ast_channel *chan)
442 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
443 struct ast_chan_trace_data *traced;
445 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
448 traced = ast_calloc(1, sizeof(*traced));
450 ast_datastore_free(store);
453 store->data = traced;
454 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
455 ast_channel_datastore_add(chan, store);
457 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
458 ast_channel_trace_data_update(chan, store->data);
462 /*! \brief Disable context tracing in the channel */
463 int ast_channel_trace_disable(struct ast_channel *chan)
465 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
468 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
471 #endif /* CHANNEL_TRACE */
473 /*! \brief Checks to see if a channel is needing hang up */
474 int ast_check_hangup(struct ast_channel *chan)
476 if (chan->_softhangup) /* yes if soft hangup flag set */
478 if (ast_tvzero(chan->whentohangup)) /* no if no hangup scheduled */
480 if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0) /* no if hangup time has not come yet. */
482 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
486 int ast_check_hangup_locked(struct ast_channel *chan)
489 ast_channel_lock(chan);
490 res = ast_check_hangup(chan);
491 ast_channel_unlock(chan);
495 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
497 struct ast_channel *chan = obj;
499 ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
504 void ast_begin_shutdown(int hangup)
509 ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
513 /*! \brief returns number of active/allocated channels */
514 int ast_active_channels(void)
516 return channels ? ao2_container_count(channels) : 0;
519 /*! \brief Cancel a shutdown in progress */
520 void ast_cancel_shutdown(void)
525 /*! \brief Returns non-zero if Asterisk is being shut down */
526 int ast_shutting_down(void)
528 return shutting_down;
531 /*! \brief Set when to hangup channel */
532 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
534 chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
535 ast_queue_frame(chan, &ast_null_frame);
539 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
541 struct timeval when = { offset, };
542 ast_channel_setwhentohangup_tv(chan, when);
545 /*! \brief Compare a offset with when to hangup channel */
546 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
548 struct timeval whentohangup;
550 if (ast_tvzero(chan->whentohangup))
551 return ast_tvzero(offset) ? 0 : -1;
553 if (ast_tvzero(offset))
556 whentohangup = ast_tvadd(offset, ast_tvnow());
558 return ast_tvdiff_ms(whentohangup, chan->whentohangup);
561 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
563 struct timeval when = { offset, };
564 return ast_channel_cmpwhentohangup_tv(chan, when);
567 /*! \brief Register a new telephony channel in Asterisk */
568 int ast_channel_register(const struct ast_channel_tech *tech)
570 struct chanlist *chan;
572 AST_RWLIST_WRLOCK(&backends);
574 AST_RWLIST_TRAVERSE(&backends, chan, list) {
575 if (!strcasecmp(tech->type, chan->tech->type)) {
576 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
577 AST_RWLIST_UNLOCK(&backends);
582 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
583 AST_RWLIST_UNLOCK(&backends);
587 AST_RWLIST_INSERT_HEAD(&backends, chan, list);
589 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
591 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
593 AST_RWLIST_UNLOCK(&backends);
598 /*! \brief Unregister channel driver */
599 void ast_channel_unregister(const struct ast_channel_tech *tech)
601 struct chanlist *chan;
603 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
605 AST_RWLIST_WRLOCK(&backends);
607 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
608 if (chan->tech == tech) {
609 AST_LIST_REMOVE_CURRENT(list);
611 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
615 AST_LIST_TRAVERSE_SAFE_END;
617 AST_RWLIST_UNLOCK(&backends);
620 /*! \brief Get handle to channel driver based on name */
621 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
623 struct chanlist *chanls;
624 const struct ast_channel_tech *ret = NULL;
626 AST_RWLIST_RDLOCK(&backends);
628 AST_RWLIST_TRAVERSE(&backends, chanls, list) {
629 if (!strcasecmp(name, chanls->tech->type)) {
635 AST_RWLIST_UNLOCK(&backends);
640 /*! \brief Gives the string form of a given hangup cause */
641 const char *ast_cause2str(int cause)
645 for (x = 0; x < ARRAY_LEN(causes); x++) {
646 if (causes[x].cause == cause)
647 return causes[x].desc;
653 /*! \brief Convert a symbolic hangup cause to number */
654 int ast_str2cause(const char *name)
658 for (x = 0; x < ARRAY_LEN(causes); x++)
659 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
660 return causes[x].cause;
665 /*! \brief Gives the string form of a given channel state.
666 \note This function is not reentrant.
668 const char *ast_state2str(enum ast_channel_state state)
675 case AST_STATE_RESERVED:
677 case AST_STATE_OFFHOOK:
679 case AST_STATE_DIALING:
683 case AST_STATE_RINGING:
689 case AST_STATE_DIALING_OFFHOOK:
690 return "Dialing Offhook";
691 case AST_STATE_PRERING:
694 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
696 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
701 /*! \brief Gives the string form of a given transfer capability */
702 char *ast_transfercapability2str(int transfercapability)
704 switch (transfercapability) {
705 case AST_TRANS_CAP_SPEECH:
707 case AST_TRANS_CAP_DIGITAL:
709 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
710 return "RESTRICTED_DIGITAL";
711 case AST_TRANS_CAP_3_1K_AUDIO:
713 case AST_TRANS_CAP_DIGITAL_W_TONES:
714 return "DIGITAL_W_TONES";
715 case AST_TRANS_CAP_VIDEO:
722 /*! \brief Pick the best audio codec */
723 format_t ast_best_codec(format_t fmts)
725 /* This just our opinion, expressed in code. We are asked to choose
726 the best codec to use, given no information */
728 static const format_t prefs[] =
730 /*! Okay, ulaw is used by all telephony equipment, so start with it */
732 /*! Unless of course, you're a silly European, so then prefer ALAW */
737 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
739 /*! Okay, well, signed linear is easy to translate into other stuff */
740 AST_FORMAT_SLINEAR16,
742 /*! G.726 is standard ADPCM, in RFC3551 packing order */
744 /*! G.726 is standard ADPCM, in AAL2 packing order */
745 AST_FORMAT_G726_AAL2,
746 /*! ADPCM has great sound quality and is still pretty easy to translate */
748 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
749 translate and sounds pretty good */
751 /*! iLBC is not too bad */
753 /*! Speex is free, but computationally more expensive than GSM */
755 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
758 /*! G.729a is faster than 723 and slightly less expensive */
760 /*! Down to G.723.1 which is proprietary but at least designed for voice */
765 /* Strip out video */
766 fmts &= AST_FORMAT_AUDIO_MASK;
768 /* Find the first preferred codec in the format given */
769 for (x = 0; x < ARRAY_LEN(prefs); x++) {
774 ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), fmts));
779 static const struct ast_channel_tech null_tech = {
781 .description = "Null channel (should not see this)",
784 static void ast_channel_destructor(void *obj);
785 static void ast_dummy_channel_destructor(void *obj);
787 /*! \brief Create a new channel structure */
788 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
789 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
790 const char *acctcode, const char *exten, const char *context,
791 const char *linkedid, const int amaflag, const char *file, int line,
792 const char *function, const char *name_fmt, va_list ap1, va_list ap2)
794 struct ast_channel *tmp;
797 struct varshead *headp;
799 /* If shutting down, don't allocate any new channels */
801 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
805 #if defined(REF_DEBUG)
806 if (!(tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line, function, 1))) {
809 #elif defined(__AST_DEBUG_MALLOC)
810 if (!(tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line, function, 0))) {
814 if (!(tmp = ao2_alloc(sizeof(*tmp), ast_channel_destructor))) {
819 if (!(tmp->sched = sched_context_create())) {
820 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
821 return ast_channel_unref(tmp);
824 if ((ast_string_field_init(tmp, 128))) {
825 return ast_channel_unref(tmp);
829 if (!(tmp->cid.cid_name = ast_strdup(cid_name))) {
830 return ast_channel_unref(tmp);
834 if (!(tmp->cid.cid_num = ast_strdup(cid_num))) {
835 return ast_channel_unref(tmp);
840 tmp->epfd = epoll_create(25);
843 for (x = 0; x < AST_MAX_FDS; x++) {
846 tmp->epfd_data[x] = NULL;
850 if ((tmp->timer = ast_timer_open())) {
852 tmp->timingfd = ast_timer_fd(tmp->timer);
858 if (pipe(tmp->alertpipe)) {
859 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
862 ast_timer_close(tmp->timer);
865 sched_context_destroy(tmp->sched);
866 ast_string_field_free_memory(tmp);
867 ast_free(tmp->cid.cid_name);
868 ast_free(tmp->cid.cid_num);
872 flags = fcntl(tmp->alertpipe[0], F_GETFL);
873 if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
874 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
875 close(tmp->alertpipe[0]);
876 close(tmp->alertpipe[1]);
877 goto alertpipe_failed;
879 flags = fcntl(tmp->alertpipe[1], F_GETFL);
880 if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
881 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
882 close(tmp->alertpipe[0]);
883 close(tmp->alertpipe[1]);
884 goto alertpipe_failed;
887 } else /* Make sure we've got it done right if they don't */
888 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
890 /* Always watch the alertpipe */
891 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
892 /* And timing pipe */
893 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
894 ast_string_field_set(tmp, name, "**Unknown**");
901 tmp->fin = global_fin;
902 tmp->fout = global_fout;
904 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
905 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
906 ast_atomic_fetchadd_int(&uniqueint, 1));
908 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
909 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
912 if (!ast_strlen_zero(linkedid)) {
913 ast_string_field_set(tmp, linkedid, linkedid);
916 ast_string_field_set(tmp, linkedid, tmp->uniqueid);
919 if (!ast_strlen_zero(name_fmt)) {
920 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
921 * And they all use slightly different formats for their name string.
922 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
923 * This means, that the stringfields must have a routine that takes the va_lists directly, and
924 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
925 * This new function was written so this can be accomplished.
927 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
930 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
932 /* These 4 variables need to be set up for the cdr_init() to work right */
934 tmp->amaflags = amaflag;
936 tmp->amaflags = ast_default_amaflags;
938 if (!ast_strlen_zero(acctcode))
939 ast_string_field_set(tmp, accountcode, acctcode);
941 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
943 if (!ast_strlen_zero(context))
944 ast_copy_string(tmp->context, context, sizeof(tmp->context));
946 strcpy(tmp->context, "default");
948 if (!ast_strlen_zero(exten))
949 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
951 strcpy(tmp->exten, "s");
955 tmp->cdr = ast_cdr_alloc();
956 ast_cdr_init(tmp->cdr, tmp);
957 ast_cdr_start(tmp->cdr);
959 ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
961 headp = &tmp->varshead;
962 AST_LIST_HEAD_INIT_NOLOCK(headp);
964 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
966 AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
968 ast_string_field_set(tmp, language, defaultlanguage);
970 tmp->tech = &null_tech;
972 ao2_link(channels, tmp);
975 * and now, since the channel structure is built, and has its name, let's
976 * call the manager event generator with this Newchannel event. This is the
977 * proper and correct place to make this call, but you sure do have to pass
978 * a lot of data into this func to do it here!
980 if (!ast_strlen_zero(name_fmt)) {
981 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
983 "ChannelState: %d\r\n"
984 "ChannelStateDesc: %s\r\n"
985 "CallerIDNum: %s\r\n"
986 "CallerIDName: %s\r\n"
987 "AccountCode: %s\r\n"
993 ast_state2str(state),
1005 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1006 const char *cid_name, const char *acctcode,
1007 const char *exten, const char *context,
1008 const char *linkedid, const int amaflag,
1009 const char *file, int line, const char *function,
1010 const char *name_fmt, ...)
1013 struct ast_channel *result;
1015 va_start(ap1, name_fmt);
1016 va_start(ap2, name_fmt);
1017 result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1018 linkedid, amaflag, file, line, function, name_fmt, ap1, ap2);
1025 /* only do the minimum amount of work needed here to make a channel
1026 * structure that can be used to expand channel vars */
1027 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1028 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1030 struct ast_channel *ast_dummy_channel_alloc(void)
1033 struct ast_channel *tmp;
1034 struct varshead *headp;
1036 #if defined(REF_DEBUG)
1037 if (!(tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel", file, line, function, 1))) {
1040 #elif defined(__AST_DEBUG_MALLOC)
1041 if (!(tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel", file, line, function, 0))) {
1045 if (!(tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor))) {
1050 if ((ast_string_field_init(tmp, 128))) {
1051 ast_channel_unref(tmp);
1055 headp = &tmp->varshead;
1056 AST_LIST_HEAD_INIT_NOLOCK(headp);
1061 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1063 struct ast_frame *f;
1064 struct ast_frame *cur;
1066 unsigned int new_frames = 0;
1067 unsigned int new_voice_frames = 0;
1068 unsigned int queued_frames = 0;
1069 unsigned int queued_voice_frames = 0;
1070 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1072 ast_channel_lock(chan);
1074 /* See if the last frame on the queue is a hangup, if so don't queue anything */
1075 if ((cur = AST_LIST_LAST(&chan->readq)) &&
1076 (cur->frametype == AST_FRAME_CONTROL) &&
1077 (cur->subclass.integer == AST_CONTROL_HANGUP)) {
1078 ast_channel_unlock(chan);
1082 /* Build copies of all the frames and count them */
1083 AST_LIST_HEAD_INIT_NOLOCK(&frames);
1084 for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1085 if (!(f = ast_frdup(cur))) {
1086 ast_frfree(AST_LIST_FIRST(&frames));
1087 ast_channel_unlock(chan);
1091 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1093 if (f->frametype == AST_FRAME_VOICE) {
1098 /* Count how many frames exist on the queue */
1099 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1101 if (cur->frametype == AST_FRAME_VOICE) {
1102 queued_voice_frames++;
1106 if ((queued_frames + new_frames) > 128) {
1107 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
1108 while ((f = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
1111 ast_channel_unlock(chan);
1115 if ((queued_voice_frames + new_voice_frames) > 96) {
1116 ast_log(LOG_WARNING, "Exceptionally long voice queue length queuing to %s\n", chan->name);
1117 while ((f = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
1120 ast_channel_unlock(chan);
1125 AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1128 AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1129 AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1131 AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1134 if (chan->alertpipe[1] > -1) {
1135 if (write(chan->alertpipe[1], &blah, new_frames * sizeof(blah)) != (new_frames * sizeof(blah))) {
1136 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1137 chan->name, queued_frames, strerror(errno));
1139 } else if (chan->timingfd > -1) {
1140 ast_timer_enable_continuous(chan->timer);
1141 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1142 pthread_kill(chan->blocker, SIGURG);
1145 ast_channel_unlock(chan);
1150 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1152 return __ast_queue_frame(chan, fin, 0, NULL);
1155 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1157 return __ast_queue_frame(chan, fin, 1, NULL);
1160 /*! \brief Queue a hangup frame for channel */
1161 int ast_queue_hangup(struct ast_channel *chan)
1163 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1164 /* Yeah, let's not change a lock-critical value without locking */
1165 if (!ast_channel_trylock(chan)) {
1166 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1167 ast_channel_unlock(chan);
1169 return ast_queue_frame(chan, &f);
1172 /*! \brief Queue a hangup frame for channel */
1173 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1175 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1178 f.data.uint32 = cause;
1180 /* Yeah, let's not change a lock-critical value without locking */
1181 if (!ast_channel_trylock(chan)) {
1182 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1184 f.data.uint32 = chan->hangupcause;
1186 ast_channel_unlock(chan);
1189 return ast_queue_frame(chan, &f);
1192 /*! \brief Queue a control frame */
1193 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1195 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1196 return ast_queue_frame(chan, &f);
1199 /*! \brief Queue a control frame with payload */
1200 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1201 const void *data, size_t datalen)
1203 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1204 return ast_queue_frame(chan, &f);
1207 /*! \brief Set defer DTMF flag on channel */
1208 int ast_channel_defer_dtmf(struct ast_channel *chan)
1213 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1214 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1219 /*! \brief Unset defer DTMF flag on channel */
1220 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1223 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1226 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1227 void *data, int ao2_flags)
1229 return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1232 struct ast_channel_iterator {
1233 /* storage for non-dynamically allocated iterator */
1234 struct ao2_iterator simple_iterator;
1235 /* pointer to the actual iterator (simple_iterator or a dynamically
1236 * allocated iterator)
1238 struct ao2_iterator *active_iterator;
1241 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1243 ao2_iterator_destroy(i->active_iterator);
1249 static struct ast_channel_iterator *channel_iterator_search(const char *name,
1250 size_t name_len, const char *exten,
1251 const char *context)
1253 struct ast_channel_iterator *i;
1254 struct ast_channel tmp_chan = {
1256 /* This is sort of a hack. Basically, we're using an arbitrary field
1257 * in ast_channel to pass the name_len for a prefix match. If this
1258 * gets changed, then the compare callback must be changed, too. */
1262 if (!(i = ast_calloc(1, sizeof(*i)))) {
1267 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1271 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1274 if (!(i->active_iterator = ao2_find(channels, &tmp_chan,
1275 OBJ_MULTIPLE | ((!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0)))) {
1283 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1285 return channel_iterator_search(NULL, 0, exten, context);
1288 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1290 return channel_iterator_search(name, name_len, NULL, NULL);
1293 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1295 struct ast_channel_iterator *i;
1297 if (!(i = ast_calloc(1, sizeof(*i)))) {
1301 i->simple_iterator = ao2_iterator_init(channels, 0);
1302 i->active_iterator = &i->simple_iterator;
1307 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1309 return ao2_iterator_next(i->active_iterator);
1312 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1314 struct ast_channel *chan = obj, *cmp_args = arg;
1316 int ret = CMP_MATCH;
1318 /* This is sort of a hack. Basically, we're using an arbitrary field
1319 * in ast_channel to pass the name_len for a prefix match. If this
1320 * gets changed, then the uses of ao2_find() must be changed, too. */
1321 name_len = cmp_args->rings;
1323 ast_channel_lock(chan);
1325 if (!ast_strlen_zero(cmp_args->name)) { /* match by name */
1326 if ((!name_len && strcasecmp(chan->name, cmp_args->name)) ||
1327 (name_len && strncasecmp(chan->name, cmp_args->name, name_len))) {
1328 ret = 0; /* name match failed */
1330 } else if (!ast_strlen_zero(cmp_args->exten)) {
1331 if (cmp_args->context && strcasecmp(chan->context, cmp_args->context) &&
1332 strcasecmp(chan->macrocontext, cmp_args->context)) {
1333 ret = 0; /* context match failed */
1335 if (ret && strcasecmp(chan->exten, cmp_args->exten) &&
1336 strcasecmp(chan->macroexten, cmp_args->exten)) {
1337 ret = 0; /* exten match failed */
1339 } else if (!ast_strlen_zero(cmp_args->uniqueid)) {
1340 if ((!name_len && strcasecmp(chan->uniqueid, cmp_args->uniqueid)) ||
1341 (name_len && strncasecmp(chan->uniqueid, cmp_args->uniqueid, name_len))) {
1342 ret = 0; /* uniqueid match failed */
1348 ast_channel_unlock(chan);
1353 static struct ast_channel *ast_channel_get_full(const char *name, size_t name_len,
1354 const char *exten, const char *context)
1356 struct ast_channel tmp_chan = {
1358 /* This is sort of a hack. Basically, we're using an arbitrary field
1359 * in ast_channel to pass the name_len for a prefix match. If this
1360 * gets changed, then the compare callback must be changed, too. */
1363 struct ast_channel *chan;
1366 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1370 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1373 if ((chan = ao2_find(channels, &tmp_chan,
1374 (!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0))) {
1382 /* If name was specified, but the result was NULL,
1383 * try a search on uniqueid, instead. */
1386 struct ast_channel tmp_chan2 = {
1391 return ao2_find(channels, &tmp_chan2, 0);
1395 struct ast_channel *ast_channel_get_by_name(const char *name)
1397 return ast_channel_get_full(name, 0, NULL, NULL);
1400 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1402 return ast_channel_get_full(name, name_len, NULL, NULL);
1405 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1407 return ast_channel_get_full(NULL, 0, exten, context);
1410 /*! \brief Wait, look for hangups and condition arg */
1411 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1413 struct ast_frame *f;
1416 if (cond && ((*cond)(data) == 0))
1418 ms = ast_waitfor(chan, ms);
1431 /*! \brief Wait, look for hangups */
1432 int ast_safe_sleep(struct ast_channel *chan, int ms)
1434 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1437 static void free_cid(struct ast_callerid *cid)
1440 ast_free(cid->cid_dnid);
1442 ast_free(cid->cid_num);
1444 ast_free(cid->cid_name);
1446 ast_free(cid->cid_ani);
1448 ast_free(cid->cid_rdnis);
1449 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1450 ast_party_subaddress_free(&cid->subaddress);
1451 ast_party_subaddress_free(&cid->dialed_subaddress);
1454 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1456 /* Safe, even if already unlinked. */
1457 ao2_unlink(channels, chan);
1458 return ast_channel_unref(chan);
1461 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1465 init->odd_even_indicator = 0;
1469 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1472 /* Don't copy to self */
1477 ast_free(dest->str);
1479 dest->str = ast_strdup(src->str);
1480 dest->type = src->type;
1481 dest->odd_even_indicator = src->odd_even_indicator;
1482 dest->valid = src->valid;
1485 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1488 init->type = guide->type;
1489 init->odd_even_indicator = guide->odd_even_indicator;
1490 init->valid = guide->valid;
1493 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1496 /* Don't set to self */
1500 if (src->str && src->str != dest->str) {
1502 ast_free(dest->str);
1504 dest->str = ast_strdup(src->str);
1507 dest->type = src->type;
1508 dest->odd_even_indicator = src->odd_even_indicator;
1509 dest->valid = src->valid;
1512 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1515 ast_free(doomed->str);
1522 * \brief Initialize the given party id structure.
1524 * \param init Party id structure to initialize.
1528 static void ast_party_id_init(struct ast_party_id *init)
1530 init->number = NULL;
1532 init->number_type = 0; /* Unknown */
1533 init->number_presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1534 ast_party_subaddress_init(&init->subaddress);
1539 * \brief Copy the source party id information to the destination party id.
1541 * \param dest Destination party id
1542 * \param src Source party id
1546 static void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1549 /* Don't copy to self */
1554 ast_free(dest->number);
1556 dest->number = ast_strdup(src->number);
1559 ast_free(dest->name);
1561 dest->name = ast_strdup(src->name);
1563 dest->number_type = src->number_type;
1564 dest->number_presentation = src->number_presentation;
1565 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1570 * \brief Initialize the given party id structure using the given guide
1571 * for a set update operation.
1574 * The initialization is needed to allow a set operation to know if a
1575 * value needs to be updated. Simple integers need the guide's original
1576 * value in case the set operation is not trying to set a new value.
1577 * String values are simply set to NULL pointers if they are not going
1580 * \param init Party id structure to initialize.
1581 * \param guide Source party id to use as a guide in initializing.
1585 static void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1587 init->number = NULL;
1589 init->number_type = guide->number_type;
1590 init->number_presentation = guide->number_presentation;
1591 ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1596 * \brief Set the source party id information into the destination party id.
1598 * \param dest Destination party id
1599 * \param src Source party id
1603 static void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src)
1606 /* Don't set to self */
1610 if (src->name && src->name != dest->name) {
1612 ast_free(dest->name);
1614 dest->name = ast_strdup(src->name);
1617 if (src->number && src->number != dest->number) {
1619 ast_free(dest->number);
1621 dest->number = ast_strdup(src->number);
1624 dest->number_type = src->number_type;
1625 dest->number_presentation = src->number_presentation;
1626 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1631 * \brief Destroy the party id contents
1633 * \param doomed The party id to destroy.
1637 static void ast_party_id_free(struct ast_party_id *doomed)
1639 if (doomed->number) {
1640 ast_free(doomed->number);
1641 doomed->number = NULL;
1645 ast_free(doomed->name);
1646 doomed->name = NULL;
1648 ast_party_subaddress_free(&doomed->subaddress);
1651 void ast_party_caller_init(struct ast_party_caller *init)
1653 ast_party_id_init(&init->id);
1658 void ast_party_caller_copy(struct ast_callerid *dest, const struct ast_callerid *src)
1661 /* Don't copy to self */
1666 /* Copy caller-id specific information ONLY from struct ast_callerid */
1669 ast_free(dest->cid_num);
1671 dest->cid_num = ast_strdup(src->cid_num);
1675 ast_free(dest->cid_name);
1677 dest->cid_name = ast_strdup(src->cid_name);
1679 dest->cid_ton = src->cid_ton;
1680 dest->cid_pres = src->cid_pres;
1685 ast_free(dest->cid_ani);
1687 dest->cid_ani = ast_strdup(src->cid_ani);
1689 dest->cid_ani2 = src->cid_ani2;
1691 ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1695 /* The src and dest parameter types will become struct ast_party_caller ptrs. */
1696 /* This is future code */
1698 ast_party_id_copy(&dest->id, &src->id);
1701 ast_free(dest->ani);
1703 dest->ani = ast_strdup(src->ani);
1705 dest->ani2 = src->ani2;
1709 void ast_party_connected_line_init(struct ast_party_connected_line *init)
1711 ast_party_id_init(&init->id);
1714 init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
1717 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
1720 /* Don't copy to self */
1724 ast_party_id_copy(&dest->id, &src->id);
1727 ast_free(dest->ani);
1729 dest->ani = ast_strdup(src->ani);
1731 dest->ani2 = src->ani2;
1732 dest->source = src->source;
1735 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
1737 ast_party_id_set_init(&init->id, &guide->id);
1739 init->ani2 = guide->ani2;
1740 init->source = guide->source;
1743 void ast_party_connected_line_set(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
1745 ast_party_id_set(&dest->id, &src->id);
1747 if (src->ani && src->ani != dest->ani) {
1749 ast_free(dest->ani);
1751 dest->ani = ast_strdup(src->ani);
1754 dest->ani2 = src->ani2;
1755 dest->source = src->source;
1758 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_callerid *cid)
1760 connected->id.number = cid->cid_num;
1761 connected->id.name = cid->cid_name;
1762 connected->id.number_type = cid->cid_ton;
1763 connected->id.number_presentation = cid->cid_pres;
1764 connected->id.subaddress = cid->subaddress;
1766 connected->ani = cid->cid_ani;
1767 connected->ani2 = cid->cid_ani2;
1768 connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
1771 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
1773 ast_party_id_free(&doomed->id);
1776 ast_free(doomed->ani);
1781 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
1784 /* Don't copy to self */
1788 ast_party_id_copy(&dest->from, &src->from);
1789 ast_party_id_copy(&dest->to, &src->to);
1790 dest->count = src->count;
1791 dest->reason = src->reason;
1794 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
1796 ast_party_id_set_init(&init->from, &guide->from);
1797 ast_party_id_set_init(&init->to, &guide->to);
1798 init->count = guide->count;
1799 init->reason = guide->reason;
1802 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
1804 ast_party_id_free(&doomed->from);
1805 ast_party_id_free(&doomed->to);
1808 /*! \brief Free a channel structure */
1809 static void ast_channel_destructor(void *obj)
1811 struct ast_channel *chan = obj;
1816 struct ast_var_t *vardata;
1817 struct ast_frame *f;
1818 struct varshead *headp;
1819 struct ast_datastore *datastore = NULL;
1820 char name[AST_CHANNEL_NAME], *dashptr;
1822 headp = &chan->varshead;
1824 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
1825 ast_cel_check_retire_linkedid(chan);
1827 /* Get rid of each of the data stores on the channel */
1828 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1829 /* Free the data store */
1830 ast_datastore_free(datastore);
1832 /* Lock and unlock the channel just to be sure nobody has it locked still
1833 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1834 ast_channel_lock(chan);
1835 ast_channel_unlock(chan);
1837 if (chan->tech_pvt) {
1838 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1839 ast_free(chan->tech_pvt);
1843 sched_context_destroy(chan->sched);
1845 ast_copy_string(name, chan->name, sizeof(name));
1846 if ((dashptr = strrchr(name, '-'))) {
1850 /* Stop monitoring */
1852 chan->monitor->stop( chan, 0 );
1854 /* If there is native format music-on-hold state, free it */
1855 if (chan->music_state)
1856 ast_moh_cleanup(chan);
1858 /* Free translators */
1859 if (chan->readtrans)
1860 ast_translator_free_path(chan->readtrans);
1861 if (chan->writetrans)
1862 ast_translator_free_path(chan->writetrans);
1864 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1866 free_cid(&chan->cid);
1867 ast_party_connected_line_free(&chan->connected);
1868 ast_party_redirecting_free(&chan->redirecting);
1870 /* Close pipes if appropriate */
1871 if ((fd = chan->alertpipe[0]) > -1)
1873 if ((fd = chan->alertpipe[1]) > -1)
1876 ast_timer_close(chan->timer);
1879 for (i = 0; i < AST_MAX_FDS; i++) {
1880 if (chan->epfd_data[i])
1881 free(chan->epfd_data[i]);
1885 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1888 /* loop over the variables list, freeing all data and deleting list items */
1889 /* no need to lock the list, as the channel is already locked */
1891 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1892 ast_var_delete(vardata);
1894 ast_app_group_discard(chan);
1896 /* Destroy the jitterbuffer */
1897 ast_jb_destroy(chan);
1900 ast_cdr_discard(chan->cdr);
1905 chan->zone = ast_tone_zone_unref(chan->zone);
1908 ast_string_field_free_memory(chan);
1910 /* Queue an unknown state, because, while we know that this particular
1911 * instance is dead, we don't know the state of all other possible
1913 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, name);
1916 /*! \brief Free a dummy channel structure */
1917 static void ast_dummy_channel_destructor(void *obj)
1919 struct ast_channel *chan = obj;
1920 struct ast_var_t *vardata;
1921 struct varshead *headp;
1923 headp = &chan->varshead;
1925 free_cid(&chan->cid);
1927 /* loop over the variables list, freeing all data and deleting list items */
1928 /* no need to lock the list, as the channel is already locked */
1929 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1930 ast_var_delete(vardata);
1933 ast_cdr_discard(chan->cdr);
1937 ast_string_field_free_memory(chan);
1940 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1942 return ast_datastore_alloc(info, uid);
1945 int ast_channel_datastore_free(struct ast_datastore *datastore)
1947 return ast_datastore_free(datastore);
1950 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1952 struct ast_datastore *datastore = NULL, *datastore2;
1954 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1955 if (datastore->inheritance > 0) {
1956 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
1958 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
1959 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1960 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1967 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1971 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1976 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1978 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1981 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1983 struct ast_datastore *datastore = NULL;
1988 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1989 if (datastore->info != info) {
1994 /* matched by type only */
1998 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
1999 /* Matched by type AND uid */
2003 AST_LIST_TRAVERSE_SAFE_END;
2008 /*! Set the file descriptor on the channel */
2009 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2012 struct epoll_event ev;
2013 struct ast_epoll_data *aed = NULL;
2015 if (chan->fds[which] > -1) {
2016 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2017 aed = chan->epfd_data[which];
2020 /* If this new fd is valid, add it to the epoll */
2022 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2025 chan->epfd_data[which] = aed;
2029 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2031 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2033 /* We don't have to keep around this epoll data structure now */
2035 chan->epfd_data[which] = NULL;
2038 chan->fds[which] = fd;
2042 /*! Add a channel to an optimized waitfor */
2043 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2046 struct epoll_event ev;
2049 if (chan0->epfd == -1)
2052 /* Iterate through the file descriptors on chan1, adding them to chan0 */
2053 for (i = 0; i < AST_MAX_FDS; i++) {
2054 if (chan1->fds[i] == -1)
2056 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2057 ev.data.ptr = chan1->epfd_data[i];
2058 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2065 /*! Delete a channel from an optimized waitfor */
2066 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2069 struct epoll_event ev;
2072 if (chan0->epfd == -1)
2075 for (i = 0; i < AST_MAX_FDS; i++) {
2076 if (chan1->fds[i] == -1)
2078 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2085 /*! \brief Softly hangup a channel, don't lock */
2086 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2088 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
2089 /* Inform channel driver that we need to be hung up, if it cares */
2090 chan->_softhangup |= cause;
2091 ast_queue_frame(chan, &ast_null_frame);
2092 /* Interrupt any poll call or such */
2093 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2094 pthread_kill(chan->blocker, SIGURG);
2098 /*! \brief Softly hangup a channel, lock */
2099 int ast_softhangup(struct ast_channel *chan, int cause)
2103 ast_channel_lock(chan);
2104 res = ast_softhangup_nolock(chan, cause);
2105 ast_channel_unlock(chan);
2110 static void free_translation(struct ast_channel *clonechan)
2112 if (clonechan->writetrans)
2113 ast_translator_free_path(clonechan->writetrans);
2114 if (clonechan->readtrans)
2115 ast_translator_free_path(clonechan->readtrans);
2116 clonechan->writetrans = NULL;
2117 clonechan->readtrans = NULL;
2118 clonechan->rawwriteformat = clonechan->nativeformats;
2119 clonechan->rawreadformat = clonechan->nativeformats;
2122 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2124 struct ast_channel *bridge;
2126 ast_channel_lock(chan);
2127 if (force || ast_strlen_zero(chan->hangupsource)) {
2128 ast_string_field_set(chan, hangupsource, source);
2130 bridge = ast_bridged_channel(chan);
2131 ast_channel_unlock(chan);
2133 if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
2134 ast_channel_lock(bridge);
2135 ast_string_field_set(chan, hangupsource, source);
2136 ast_channel_unlock(bridge);
2140 /*! \brief Hangup a channel */
2141 int ast_hangup(struct ast_channel *chan)
2144 char extra_str[64]; /* used for cel logging below */
2146 /* Don't actually hang up a channel that will masquerade as someone else, or
2147 if someone is going to masquerade as us */
2148 ast_channel_lock(chan);
2150 if (chan->audiohooks) {
2151 ast_audiohook_detach_list(chan->audiohooks);
2152 chan->audiohooks = NULL;
2155 ast_autoservice_stop(chan);
2158 ast_channel_unlock(chan);
2159 if (ast_do_masquerade(chan)) {
2160 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2162 ast_channel_lock(chan);
2166 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
2167 ast_channel_unlock(chan);
2170 /* If this channel is one which will be masqueraded into something,
2171 mark it as a zombie already, so we know to free it later */
2173 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2174 ast_channel_unlock(chan);
2177 ast_channel_unlock(chan);
2179 ao2_unlink(channels, chan);
2181 ast_channel_lock(chan);
2182 free_translation(chan);
2183 /* Close audio stream */
2185 ast_closestream(chan->stream);
2186 chan->stream = NULL;
2188 /* Close video stream */
2189 if (chan->vstream) {
2190 ast_closestream(chan->vstream);
2191 chan->vstream = NULL;
2194 sched_context_destroy(chan->sched);
2198 if (chan->generatordata) /* Clear any tone stuff remaining */
2199 if (chan->generator && chan->generator->release)
2200 chan->generator->release(chan, chan->generatordata);
2201 chan->generatordata = NULL;
2202 chan->generator = NULL;
2204 snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2205 ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2207 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2208 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2209 "is blocked by thread %ld in procedure %s! Expect a failure\n",
2210 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
2211 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2213 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
2214 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
2215 if (chan->tech->hangup)
2216 res = chan->tech->hangup(chan);
2218 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
2221 ast_channel_unlock(chan);
2222 ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2225 "CallerIDNum: %s\r\n"
2226 "CallerIDName: %s\r\n"
2228 "Cause-txt: %s\r\n",
2231 S_OR(chan->cid.cid_num, "<unknown>"),
2232 S_OR(chan->cid.cid_name, "<unknown>"),
2234 ast_cause2str(chan->hangupcause)
2237 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
2238 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
2239 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2240 ast_channel_lock(chan);
2242 ast_cdr_end(chan->cdr);
2243 ast_cdr_detach(chan->cdr);
2245 ast_channel_unlock(chan);
2248 chan = ast_channel_release(chan);
2253 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2257 ast_channel_lock(chan);
2259 /* You can't answer an outbound call */
2260 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2261 ast_channel_unlock(chan);
2265 /* Stop if we're a zombie or need a soft hangup */
2266 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2267 ast_channel_unlock(chan);
2271 ast_channel_unlock(chan);
2273 switch (chan->_state) {
2274 case AST_STATE_RINGING:
2275 case AST_STATE_RING:
2276 ast_channel_lock(chan);
2277 if (chan->tech->answer) {
2278 res = chan->tech->answer(chan);
2280 ast_setstate(chan, AST_STATE_UP);
2282 ast_cdr_answer(chan->cdr);
2284 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2285 ast_channel_unlock(chan);
2288 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2289 /* Calling ast_cdr_answer when it it has previously been called
2290 * is essentially a no-op, so it is safe.
2293 ast_cdr_answer(chan->cdr);
2300 ast_indicate(chan, -1);
2301 chan->visible_indication = 0;
2306 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2309 enum ast_channel_state old_state;
2311 old_state = chan->_state;
2312 if ((res = ast_raw_answer(chan, cdr_answer))) {
2316 switch (old_state) {
2317 case AST_STATE_RINGING:
2318 case AST_STATE_RING:
2319 /* wait for media to start flowing, but don't wait any longer
2320 * than 'delay' or 500 milliseconds, whichever is longer
2323 AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2324 struct ast_frame *cur, *new;
2325 int ms = MAX(delay, 500);
2326 unsigned int done = 0;
2328 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2331 ms = ast_waitfor(chan, ms);
2333 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
2338 ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
2341 cur = ast_read(chan);
2342 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2343 (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2348 ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
2352 if ((new = ast_frisolate(cur)) != cur) {
2356 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2358 /* if a specific delay period was requested, continue
2359 * until that delay has passed. don't stop just because
2360 * incoming media has arrived.
2366 switch (new->frametype) {
2367 /* all of these frametypes qualify as 'media' */
2368 case AST_FRAME_VOICE:
2369 case AST_FRAME_VIDEO:
2370 case AST_FRAME_TEXT:
2371 case AST_FRAME_DTMF_BEGIN:
2372 case AST_FRAME_DTMF_END:
2373 case AST_FRAME_IMAGE:
2374 case AST_FRAME_HTML:
2375 case AST_FRAME_MODEM:
2378 case AST_FRAME_CONTROL:
2380 case AST_FRAME_NULL:
2391 ast_channel_lock(chan);
2392 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2393 ast_queue_frame_head(chan, cur);
2396 ast_channel_unlock(chan);
2407 int ast_answer(struct ast_channel *chan)
2409 return __ast_answer(chan, 0, 1);
2412 void ast_deactivate_generator(struct ast_channel *chan)
2414 ast_channel_lock(chan);
2415 if (chan->generatordata) {
2416 if (chan->generator && chan->generator->release)
2417 chan->generator->release(chan, chan->generatordata);
2418 chan->generatordata = NULL;
2419 chan->generator = NULL;
2420 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2421 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2422 ast_settimeout(chan, 0, NULL, NULL);
2424 ast_channel_unlock(chan);
2427 static int generator_force(const void *data)
2429 /* Called if generator doesn't have data */
2432 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2433 struct ast_channel *chan = (struct ast_channel *)data;
2435 ast_channel_lock(chan);
2436 tmp = chan->generatordata;
2437 chan->generatordata = NULL;
2438 if (chan->generator)
2439 generate = chan->generator->generate;
2440 ast_channel_unlock(chan);
2442 if (!tmp || !generate)
2445 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
2447 chan->generatordata = tmp;
2450 ast_debug(1, "Auto-deactivating generator\n");
2451 ast_deactivate_generator(chan);
2457 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2461 ast_channel_lock(chan);
2463 if (chan->generatordata) {
2464 if (chan->generator && chan->generator->release)
2465 chan->generator->release(chan, chan->generatordata);
2466 chan->generatordata = NULL;
2470 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2475 ast_settimeout(chan, 50, generator_force, chan);
2476 chan->generator = gen;
2479 ast_channel_unlock(chan);
2484 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2485 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2488 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2492 /*! \brief Wait for x amount of time on a file descriptor to have input. */
2494 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2495 int *exception, int *outfd, int *ms)
2497 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2498 int *exception, int *outfd, int *ms)
2501 struct timeval start = { 0 , 0 };
2502 struct pollfd *pfds = NULL;
2507 struct timeval now = { 0, 0 };
2508 struct timeval whentohangup = { 0, 0 }, diff;
2509 struct ast_channel *winner = NULL;
2515 if ((sz = n * AST_MAX_FDS + nfds)) {
2516 pfds = alloca(sizeof(*pfds) * sz);
2517 fdmap = alloca(sizeof(*fdmap) * sz);
2525 /* Perform any pending masquerades */
2526 for (x = 0; x < n; x++) {
2527 if (c[x]->masq && ast_do_masquerade(c[x])) {
2528 ast_log(LOG_WARNING, "Masquerade failed\n");
2533 ast_channel_lock(c[x]);
2534 if (!ast_tvzero(c[x]->whentohangup)) {
2535 if (ast_tvzero(whentohangup))
2537 diff = ast_tvsub(c[x]->whentohangup, now);
2538 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
2539 /* Should already be hungup */
2540 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2541 ast_channel_unlock(c[x]);
2544 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
2545 whentohangup = diff;
2547 ast_channel_unlock(c[x]);
2549 /* Wait full interval */
2551 if (!ast_tvzero(whentohangup)) {
2552 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
2553 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
2557 * Build the pollfd array, putting the channels' fds first,
2558 * followed by individual fds. Order is important because
2559 * individual fd's must have priority over channel fds.
2562 for (x = 0; x < n; x++) {
2563 for (y = 0; y < AST_MAX_FDS; y++) {
2564 fdmap[max].fdno = y; /* fd y is linked to this pfds */
2565 fdmap[max].chan = x; /* channel x is linked to this pfds */
2566 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
2568 CHECK_BLOCKING(c[x]);
2570 /* Add the individual fds */
2571 for (x = 0; x < nfds; x++) {
2572 fdmap[max].chan = -1;
2573 max += ast_add_fd(&pfds[max], fds[x]);
2577 start = ast_tvnow();
2579 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
2584 res = ast_poll(pfds, max, kbrms);
2587 } while (!res && (rms > 0));
2589 res = ast_poll(pfds, max, rms);
2591 for (x = 0; x < n; x++)
2592 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
2593 if (res < 0) { /* Simulate a timeout if we were interrupted */
2598 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
2600 for (x = 0; x < n; x++) {
2601 if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
2602 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2608 if (res == 0) { /* no fd ready, reset timeout and done */
2609 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
2613 * Then check if any channel or fd has a pending event.
2614 * Remember to check channels first and fds last, as they
2615 * must have priority on setting 'winner'
2617 for (x = 0; x < max; x++) {
2618 res = pfds[x].revents;
2621 if (fdmap[x].chan >= 0) { /* this is a channel */
2622 winner = c[fdmap[x].chan]; /* override previous winners */
2624 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2626 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2627 winner->fdno = fdmap[x].fdno;
2628 } else { /* this is an fd */
2630 *outfd = pfds[x].fd;
2632 *exception = (res & POLLPRI) ? -1 : 0;
2637 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2645 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
2647 struct timeval start = { 0 , 0 };
2649 struct epoll_event ev[1];
2650 long diff, rms = *ms;
2651 struct ast_channel *winner = NULL;
2652 struct ast_epoll_data *aed = NULL;
2655 /* See if this channel needs to be masqueraded */
2656 if (chan->masq && ast_do_masquerade(chan)) {
2657 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
2662 ast_channel_lock(chan);
2663 /* Figure out their timeout */
2664 if (!ast_tvzero(chan->whentohangup)) {
2665 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
2666 /* They should already be hungup! */
2667 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2668 ast_channel_unlock(chan);
2671 /* If this value is smaller then the current one... make it priority */
2676 ast_channel_unlock(chan);
2678 /* Time to make this channel block... */
2679 CHECK_BLOCKING(chan);
2682 start = ast_tvnow();
2684 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
2685 res = epoll_wait(chan->epfd, ev, 1, rms);
2688 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2690 /* Simulate a timeout if we were interrupted */
2697 /* If this channel has a timeout see if it expired */
2698 if (!ast_tvzero(chan->whentohangup)) {
2699 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
2700 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2705 /* No fd ready, reset timeout and be done for now */
2711 /* See what events are pending */
2712 aed = ev[0].data.ptr;
2713 chan->fdno = aed->which;
2714 if (ev[0].events & EPOLLPRI)
2715 ast_set_flag(chan, AST_FLAG_EXCEPTION);
2717 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2720 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2728 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2730 struct timeval start = { 0 , 0 };
2732 struct epoll_event ev[25] = { { 0, } };
2733 struct timeval now = { 0, 0 };
2734 long whentohangup = 0, diff = 0, rms = *ms;
2735 struct ast_channel *winner = NULL;
2737 for (i = 0; i < n; i++) {
2738 if (c[i]->masq && ast_do_masquerade(c[i])) {
2739 ast_log(LOG_WARNING, "Masquerade failed\n");
2744 ast_channel_lock(c[i]);
2745 if (!ast_tvzero(c[i]->whentohangup)) {
2746 if (whentohangup == 0)
2748 if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
2749 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2750 ast_channel_unlock(c[i]);
2753 if (!whentohangup || whentohangup > diff)
2754 whentohangup = diff;
2756 ast_channel_unlock(c[i]);
2757 CHECK_BLOCKING(c[i]);
2763 if (*ms >= 0 && *ms < rms)
2768 start = ast_tvnow();
2770 res = epoll_wait(c[0]->epfd, ev, 25, rms);
2772 for (i = 0; i < n; i++)
2773 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2783 for (i = 0; i < n; i++) {
2784 if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
2785 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2797 for (i = 0; i < res; i++) {
2798 struct ast_epoll_data *aed = ev[i].data.ptr;
2800 if (!ev[i].events || !aed)
2804 if (ev[i].events & EPOLLPRI)
2805 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2807 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2808 winner->fdno = aed->which;
2812 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2820 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2821 int *exception, int *outfd, int *ms)
2823 /* Clear all provided values in one place. */
2829 /* If no epoll file descriptor is available resort to classic nandfds */
2830 if (!n || nfds || c[0]->epfd == -1)
2831 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2832 else if (!nfds && n == 1)
2833 return ast_waitfor_nandfds_simple(c[0], ms);
2835 return ast_waitfor_nandfds_complex(c, n, ms);
2839 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2841 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2844 int ast_waitfor(struct ast_channel *c, int ms)
2846 int oldms = ms; /* -1 if no timeout */
2848 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2849 if ((ms < 0) && (oldms < 0))
2854 /* XXX never to be called with ms = -1 */
2855 int ast_waitfordigit(struct ast_channel *c, int ms)
2857 return ast_waitfordigit_full(c, ms, -1, -1);
2860 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
2863 unsigned int real_rate = rate, max_rate;
2865 ast_channel_lock(c);
2867 if (c->timingfd == -1) {
2868 ast_channel_unlock(c);
2877 if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
2878 real_rate = max_rate;
2881 ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
2883 res = ast_timer_set_rate(c->timer, real_rate);
2885 c->timingfunc = func;
2886 c->timingdata = data;
2888 ast_channel_unlock(c);
2893 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2895 /* Stop if we're a zombie or need a soft hangup */
2896 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2899 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2900 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2902 /* Wait for a digit, no more than ms milliseconds total. */
2905 struct ast_channel *rchan;
2909 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2911 if (!rchan && outfd < 0 && ms) {
2912 if (errno == 0 || errno == EINTR)
2914 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2915 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2917 } else if (outfd > -1) {
2918 /* The FD we were watching has something waiting */
2919 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2920 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2924 struct ast_frame *f = ast_read(c);
2928 switch (f->frametype) {
2929 case AST_FRAME_DTMF_BEGIN:
2931 case AST_FRAME_DTMF_END:
2932 res = f->subclass.integer;
2934 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2936 case AST_FRAME_CONTROL:
2937 switch (f->subclass.integer) {
2938 case AST_CONTROL_HANGUP:
2940 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2942 case AST_CONTROL_RINGING:
2943 case AST_CONTROL_ANSWER:
2944 case AST_CONTROL_SRCUPDATE:
2945 case AST_CONTROL_CONNECTED_LINE:
2946 case AST_CONTROL_REDIRECTING:
2950 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
2954 case AST_FRAME_VOICE:
2955 /* Write audio if appropriate */
2957 if (write(audiofd, f->data.ptr, f->datalen) < 0) {
2958 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
2969 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2971 return 0; /* Time is up */
2974 static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2976 ast_manager_event(chan, EVENT_FLAG_DTMF,
2984 chan->name, chan->uniqueid, digit, direction, begin, end);
2987 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2989 if (chan->generator && chan->generator->generate && chan->generatordata && !ast_internal_timing_enabled(chan)) {
2990 void *tmp = chan->generatordata;
2991 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = chan->generator->generate;
2995 if (chan->timingfunc) {
2996 ast_debug(1, "Generator got voice, switching to phase locked mode\n");
2997 ast_settimeout(chan, 0, NULL, NULL);
3000 chan->generatordata = NULL; /* reset, to let writes go through */
3002 if (f->subclass.codec != chan->writeformat) {
3004 factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass.codec));
3005 samples = (int) ( ((float) f->samples) * factor );
3007 samples = f->samples;
3010 /* This unlock is here based on two assumptions that hold true at this point in the
3011 * code. 1) this function is only called from within __ast_read() and 2) all generators
3012 * call ast_write() in their generate callback.
3014 * The reason this is added is so that when ast_write is called, the lock that occurs
3015 * there will not recursively lock the channel. Doing this will cause intended deadlock
3016 * avoidance not to work in deeper functions
3018 ast_channel_unlock(chan);
3019 res = generate(chan, tmp, f->datalen, samples);
3020 ast_channel_lock(chan);
3021 chan->generatordata = tmp;
3023 ast_debug(1, "Auto-deactivating generator\n");
3024 ast_deactivate_generator(chan);
3027 } else if (f->frametype == AST_FRAME_CNG) {
3028 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
3029 ast_debug(1, "Generator got CNG, switching to timed mode\n");
3030 ast_settimeout(chan, 50, generator_force, chan);
3035 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3037 struct ast_frame *fr = &chan->dtmff;
3039 fr->frametype = AST_FRAME_DTMF_END;
3040 fr->subclass.integer = f->subclass.integer;
3043 /* The only time this function will be called is for a frame that just came
3044 * out of the channel driver. So, we want to stick it on the tail of the
3047 ast_queue_frame(chan, fr);
3051 * \brief Determine whether or not we should ignore DTMF in the readq
3053 static inline int should_skip_dtmf(struct ast_channel *chan)
3055 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
3056 /* We're in the middle of emulating a digit, or DTMF has been
3057 * explicitly deferred. Skip this digit, then. */
3061 if (!ast_tvzero(chan->dtmf_tv) &&
3062 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3063 /* We're not in the middle of a digit, but it hasn't been long enough
3064 * since the last digit, so we'll have to skip DTMF for now. */
3071 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
3073 struct ast_frame *f = NULL; /* the return value */
3078 /* this function is very long so make sure there is only one return
3079 * point at the end (there are only two exceptions to this).
3083 if (ast_do_masquerade(chan))
3084 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
3086 f = &ast_null_frame;
3090 /* if here, no masq has happened, lock the channel and proceed */
3091 ast_channel_lock(chan);
3093 /* Stop if we're a zombie or need a soft hangup */
3094 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
3095 if (chan->generator)
3096 ast_deactivate_generator(chan);
3102 * The ast_waitfor() code records which of the channel's file descriptors reported that
3103 * data is available. In theory, ast_read() should only be called after ast_waitfor()
3104 * reports that a channel has data available for reading. However, there still may be
3105 * some edge cases throughout the code where ast_read() is called improperly. This can
3106 * potentially cause problems, so if this is a developer build, make a lot of noise if
3107 * this happens so that it can be addressed.
3109 if (chan->fdno == -1) {
3110 ast_log(LOG_ERROR, "ast_read() called with no recorded file descriptor.\n");
3114 prestate = chan->_state;
3116 /* Read and ignore anything on the alertpipe, but read only
3117 one sizeof(blah) per frame that we send from it */
3118 if (chan->alertpipe[0] > -1) {
3119 int flags = fcntl(chan->alertpipe[0], F_GETFL);
3120 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
3121 * which immediately causes a deadlock scenario. Detect and prevent this. */
3122 if ((flags & O_NONBLOCK) == 0) {
3123 ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
3124 if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
3125 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
3126 f = &ast_null_frame;
3130 if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
3131 if (errno != EINTR && errno != EAGAIN)
3132 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
3136 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
3137 enum ast_timer_event res;
3139 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3141 res = ast_timer_get_event(chan->timer);
3144 case AST_TIMING_EVENT_EXPIRED:
3145 ast_timer_ack(chan->timer, 1);
3147 if (chan->timingfunc) {
3148 /* save a copy of func/data before unlocking the channel */
3149 int (*func)(const void *) = chan->timingfunc;
3150 void *data = chan->timingdata;
3152 ast_channel_unlock(chan);
3155 ast_timer_set_rate(chan->timer, 0);
3157 ast_channel_unlock(chan);
3160 /* cannot 'goto done' because the channel is already unlocked */
3161 return &ast_null_frame;
3163 case AST_TIMING_EVENT_CONTINUOUS:
3164 if (AST_LIST_EMPTY(&chan->readq) ||
3165 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
3166 ast_timer_disable_continuous(chan->timer);
3171 } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
3172 /* if the AST_GENERATOR_FD is set, call the generator with args
3173 * set to -1 so it can do whatever it needs to.
3175 void *tmp = chan->generatordata;
3176 chan->generatordata = NULL; /* reset to let ast_write get through */
3177 chan->generator->generate(chan, tmp, -1, -1);
3178 chan->generatordata = tmp;
3179 f = &ast_null_frame;
3184 /* Check for pending read queue */
3185 if (!AST_LIST_EMPTY(&chan->readq)) {
3186 int skip_dtmf = should_skip_dtmf(chan);
3188 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
3189 /* We have to be picky about which frame we pull off of the readq because
3190 * there are cases where we want to leave DTMF frames on the queue until
3191 * some later time. */
3193 if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
3197 AST_LIST_REMOVE_CURRENT(frame_list);
3200 AST_LIST_TRAVERSE_SAFE_END;
3203 /* There were no acceptable frames on the readq. */
3204 f = &ast_null_frame;
3205 if (chan->alertpipe[0] > -1) {
3207 /* Restore the state of the alertpipe since we aren't ready for any
3208 * of the frames in the readq. */
3209 if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
3210 ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
3215 /* Interpret hangup and return NULL */
3216 /* XXX why not the same for frames from the channel ? */
3217 if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
3218 cause = f->data.uint32;
3223 chan->blocker = pthread_self();
3224 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
3225 if (chan->tech->exception)
3226 f = chan->tech->exception(chan);
3228 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
3229 f = &ast_null_frame;
3231 /* Clear the exception flag */
3232 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3233 } else if (chan->tech->read)
3234 f = chan->tech->read(chan);
3236 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
3240 * Reset the recorded file descriptor that triggered this read so that we can
3241 * easily detect when ast_read() is called without properly using ast_waitfor().
3246 struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
3248 /* if the channel driver returned more than one frame, stuff the excess
3249 into the readq for the next ast_read call
3251 if (AST_LIST_NEXT(f, frame_list)) {
3252 ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
3253 ast_frfree(AST_LIST_NEXT(f, frame_list));
3254 AST_LIST_NEXT(f, frame_list) = NULL;
3257 switch (f->frametype) {
3258 case AST_FRAME_CONTROL:
3259 if (f->subclass.integer == AST_CONTROL_ANSWER) {
3260 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
3261 ast_debug(1, "Ignoring answer on an inbound call!\n");
3263 f = &ast_null_frame;
3264 } else if (prestate == AST_STATE_UP) {
3265 ast_debug(1, "Dropping duplicate answer!\n");
3267 f = &ast_null_frame;
3269 /* Answer the CDR */
3270 ast_setstate(chan, AST_STATE_UP);
3271 /* removed a call to ast_cdr_answer(chan->cdr) from here. */
3272 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
3276 case AST_FRAME_DTMF_END:
3277 send_dtmf_event(chan, "Received", f->subclass.integer, "No", "Yes");
3278 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass.integer, chan->name, f->len);
3279 /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
3280 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
3281 queue_dtmf_readq(chan, f);
3283 f = &ast_null_frame;
3284 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {