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 */
37 #include "asterisk/zapata.h"
39 #include "asterisk/pbx.h"
40 #include "asterisk/frame.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/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"
66 #include <sys/epoll.h>
69 struct ast_epoll_data {
70 struct ast_channel *chan;
74 /* uncomment if you have problems with 'monitoring' synchronized files */
76 #define MONITOR_CONSTANT_DELAY
77 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
80 /*! \brief Prevent new channel allocation if shutting down. */
81 static int shutting_down;
85 unsigned long global_fin, global_fout;
87 AST_THREADSTORAGE(state2str_threadbuf);
88 #define STATE2STR_BUFSIZE 32
90 /*! Default amount of time to use when emulating a digit as a begin and end
92 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
94 /*! Minimum allowed digit length - 80ms */
95 #define AST_MIN_DTMF_DURATION 80
97 /*! Minimum amount of time between the end of the last digit and the beginning
98 * of a new one - 45ms */
99 #define AST_MIN_DTMF_GAP 45
101 /*! \brief List of channel drivers */
103 const struct ast_channel_tech *tech;
104 AST_LIST_ENTRY(chanlist) list;
108 /*! \brief Structure to hold channel context backtrace data */
109 struct ast_chan_trace_data {
111 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
114 /*! \brief Structure to save contexts where an ast_chan has been into */
115 struct ast_chan_trace {
116 char context[AST_MAX_CONTEXT];
117 char exten[AST_MAX_EXTENSION];
119 AST_LIST_ENTRY(ast_chan_trace) entry;
123 /*! \brief the list of registered channel types */
124 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
126 /*! \brief the list of channels we have. Note that the lock for this list is used for
127 both the channels list and the backends list. */
128 static AST_RWLIST_HEAD_STATIC(channels, ast_channel);
130 /*! \brief map AST_CAUSE's to readable string representations
134 const struct ast_cause {
139 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
140 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
141 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
142 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
143 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
144 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
145 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
146 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
147 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
148 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
149 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
150 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
151 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
152 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
153 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
154 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
155 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
156 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
157 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
158 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
159 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
160 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
161 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
162 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
163 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
164 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
165 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
166 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
167 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
168 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
169 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
170 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
171 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
172 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
173 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
174 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
175 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
176 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
177 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
178 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
179 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
180 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
181 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
182 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
185 struct ast_variable *ast_channeltype_list(void)
188 struct ast_variable *var=NULL, *prev = NULL;
189 AST_LIST_TRAVERSE(&backends, cl, list) {
191 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
194 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
201 /*! \brief Show channel types - CLI command */
202 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
204 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
210 e->command = "core show channeltypes";
212 "Usage: core show channeltypes\n"
213 " Lists available channel types registered in your\n"
214 " Asterisk server.\n";
221 return CLI_SHOWUSAGE;
223 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
224 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
226 AST_RWLIST_RDLOCK(&channels);
228 AST_LIST_TRAVERSE(&backends, cl, list) {
229 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
230 (cl->tech->devicestate) ? "yes" : "no",
231 (cl->tech->indicate) ? "yes" : "no",
232 (cl->tech->transfer) ? "yes" : "no");
236 AST_RWLIST_UNLOCK(&channels);
238 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
245 static char *complete_channeltypes(struct ast_cli_args *a)
255 wordlen = strlen(a->word);
257 AST_LIST_TRAVERSE(&backends, cl, list) {
258 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
259 ret = ast_strdup(cl->tech->type);
267 /*! \brief Show details about a channel driver - CLI command */
268 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
270 struct chanlist *cl = NULL;
274 e->command = "core show channeltype";
276 "Usage: core show channeltype <name>\n"
277 " Show details about the specified channel type, <name>.\n";
280 return complete_channeltypes(a);
284 return CLI_SHOWUSAGE;
286 AST_RWLIST_RDLOCK(&channels);
288 AST_LIST_TRAVERSE(&backends, cl, list) {
289 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
295 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
296 AST_RWLIST_UNLOCK(&channels);
301 "-- Info about channel driver: %s --\n"
302 " Device State: %s\n"
305 " Capabilities: %d\n"
309 " Image Support: %s\n"
310 " Text Support: %s\n",
312 (cl->tech->devicestate) ? "yes" : "no",
313 (cl->tech->indicate) ? "yes" : "no",
314 (cl->tech->transfer) ? "yes" : "no",
315 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
316 (cl->tech->send_digit_begin) ? "yes" : "no",
317 (cl->tech->send_digit_end) ? "yes" : "no",
318 (cl->tech->send_html) ? "yes" : "no",
319 (cl->tech->send_image) ? "yes" : "no",
320 (cl->tech->send_text) ? "yes" : "no"
324 AST_RWLIST_UNLOCK(&channels);
328 static struct ast_cli_entry cli_channel[] = {
329 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
330 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
334 /*! \brief Destructor for the channel trace datastore */
335 static void ast_chan_trace_destroy_cb(void *data)
337 struct ast_chan_trace *trace;
338 struct ast_chan_trace_data *traced = data;
339 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
345 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
346 const struct ast_datastore_info ast_chan_trace_datastore_info = {
348 .destroy = ast_chan_trace_destroy_cb
351 /*! \brief Put the channel backtrace in a string */
352 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
355 struct ast_chan_trace *trace;
356 struct ast_chan_trace_data *traced;
357 struct ast_datastore *store;
359 ast_channel_lock(chan);
360 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
362 ast_channel_unlock(chan);
365 traced = store->data;
367 (*buf)->str[0] = '\0';
368 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
369 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
370 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
376 ast_channel_unlock(chan);
380 /* !\brief Whether or not context tracing is enabled */
381 int ast_channel_trace_is_enabled(struct ast_channel *chan)
383 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
386 return ((struct ast_chan_trace_data *)store->data)->enabled;
389 /*! \brief Update the context backtrace data if tracing is enabled */
390 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
392 struct ast_chan_trace *trace;
393 if (!traced->enabled)
395 /* If the last saved context does not match the current one
396 OR we have not saved any context so far, then save the current context */
397 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) ||
398 (AST_LIST_EMPTY(&traced->trace))) {
399 /* Just do some debug logging */
400 if (AST_LIST_EMPTY(&traced->trace))
401 ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
403 ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
404 /* alloc or bail out */
405 trace = ast_malloc(sizeof(*trace));
408 /* save the current location and store it in the trace list */
409 ast_copy_string(trace->context, chan->context, sizeof(trace->context));
410 ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
411 trace->priority = chan->priority;
412 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
417 /*! \brief Update the context backtrace if tracing is enabled */
418 int ast_channel_trace_update(struct ast_channel *chan)
420 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
423 return ast_channel_trace_data_update(chan, store->data);
426 /*! \brief Enable context tracing in the channel */
427 int ast_channel_trace_enable(struct ast_channel *chan)
429 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
430 struct ast_chan_trace_data *traced;
432 store = ast_channel_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
435 traced = ast_calloc(1, sizeof(*traced));
437 ast_channel_datastore_free(store);
440 store->data = traced;
441 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
442 ast_channel_datastore_add(chan, store);
444 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
445 ast_channel_trace_data_update(chan, store->data);
449 /*! \brief Disable context tracing in the channel */
450 int ast_channel_trace_disable(struct ast_channel *chan)
452 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
455 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
458 #endif /* CHANNEL_TRACE */
460 /*! \brief Checks to see if a channel is needing hang up */
461 int ast_check_hangup(struct ast_channel *chan)
463 if (chan->_softhangup) /* yes if soft hangup flag set */
465 if (!chan->tech_pvt) /* yes if no technology private data */
467 if (ast_tvzero(chan->whentohangup)) /* no if no hangup scheduled */
469 if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0) /* no if hangup time has not come yet. */
471 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
475 static int ast_check_hangup_locked(struct ast_channel *chan)
478 ast_channel_lock(chan);
479 res = ast_check_hangup(chan);
480 ast_channel_unlock(chan);
484 /*! \brief Initiate system shutdown */
485 void ast_begin_shutdown(int hangup)
487 struct ast_channel *c;
490 AST_RWLIST_RDLOCK(&channels);
491 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
492 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
494 AST_RWLIST_UNLOCK(&channels);
498 /*! \brief returns number of active/allocated channels */
499 int ast_active_channels(void)
501 struct ast_channel *c;
503 AST_RWLIST_RDLOCK(&channels);
504 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
506 AST_RWLIST_UNLOCK(&channels);
510 /*! \brief Cancel a shutdown in progress */
511 void ast_cancel_shutdown(void)
516 /*! \brief Returns non-zero if Asterisk is being shut down */
517 int ast_shutting_down(void)
519 return shutting_down;
522 /*! \brief Set when to hangup channel */
523 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
525 chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
526 ast_queue_frame(chan, &ast_null_frame);
530 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
532 struct timeval tv = { offset, };
533 ast_channel_setwhentohangup_tv(chan, tv);
536 /*! \brief Compare a offset with when to hangup channel */
537 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
539 struct timeval whentohangup;
541 if (ast_tvzero(chan->whentohangup))
542 return ast_tvzero(offset) ? 0 : -1;
544 if (ast_tvzero(offset))
547 whentohangup = ast_tvadd(offset, ast_tvnow());
549 return ast_tvdiff_ms(whentohangup, chan->whentohangup);
552 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
554 struct timeval tv = { offset, };
555 return ast_channel_cmpwhentohangup_tv(chan, tv);
558 /*! \brief Register a new telephony channel in Asterisk */
559 int ast_channel_register(const struct ast_channel_tech *tech)
561 struct chanlist *chan;
563 AST_RWLIST_WRLOCK(&channels);
565 AST_LIST_TRAVERSE(&backends, chan, list) {
566 if (!strcasecmp(tech->type, chan->tech->type)) {
567 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
568 AST_RWLIST_UNLOCK(&channels);
573 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
574 AST_RWLIST_UNLOCK(&channels);
578 AST_LIST_INSERT_HEAD(&backends, chan, list);
580 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
582 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
584 AST_RWLIST_UNLOCK(&channels);
588 /*! \brief Unregister channel driver */
589 void ast_channel_unregister(const struct ast_channel_tech *tech)
591 struct chanlist *chan;
593 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
595 AST_RWLIST_WRLOCK(&channels);
597 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
598 if (chan->tech == tech) {
599 AST_LIST_REMOVE_CURRENT(list);
601 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
605 AST_LIST_TRAVERSE_SAFE_END;
607 AST_RWLIST_UNLOCK(&channels);
610 /*! \brief Get handle to channel driver based on name */
611 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
613 struct chanlist *chanls;
614 const struct ast_channel_tech *ret = NULL;
616 AST_RWLIST_RDLOCK(&channels);
618 AST_LIST_TRAVERSE(&backends, chanls, list) {
619 if (!strcasecmp(name, chanls->tech->type)) {
625 AST_RWLIST_UNLOCK(&channels);
630 /*! \brief Gives the string form of a given hangup cause */
631 const char *ast_cause2str(int cause)
635 for (x = 0; x < ARRAY_LEN(causes); x++) {
636 if (causes[x].cause == cause)
637 return causes[x].desc;
643 /*! \brief Convert a symbolic hangup cause to number */
644 int ast_str2cause(const char *name)
648 for (x = 0; x < ARRAY_LEN(causes); x++)
649 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
650 return causes[x].cause;
655 /*! \brief Gives the string form of a given channel state.
656 \note This function is not reentrant.
658 const char *ast_state2str(enum ast_channel_state state)
665 case AST_STATE_RESERVED:
667 case AST_STATE_OFFHOOK:
669 case AST_STATE_DIALING:
673 case AST_STATE_RINGING:
679 case AST_STATE_DIALING_OFFHOOK:
680 return "Dialing Offhook";
681 case AST_STATE_PRERING:
684 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
686 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
691 /*! \brief Gives the string form of a given transfer capability */
692 char *ast_transfercapability2str(int transfercapability)
694 switch (transfercapability) {
695 case AST_TRANS_CAP_SPEECH:
697 case AST_TRANS_CAP_DIGITAL:
699 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
700 return "RESTRICTED_DIGITAL";
701 case AST_TRANS_CAP_3_1K_AUDIO:
703 case AST_TRANS_CAP_DIGITAL_W_TONES:
704 return "DIGITAL_W_TONES";
705 case AST_TRANS_CAP_VIDEO:
712 /*! \brief Pick the best audio codec */
713 int ast_best_codec(int fmts)
715 /* This just our opinion, expressed in code. We are asked to choose
716 the best codec to use, given no information */
718 static const int prefs[] =
720 /*! Okay, ulaw is used by all telephony equipment, so start with it */
722 /*! Unless of course, you're a silly European, so then prefer ALAW */
724 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
726 /*! Okay, well, signed linear is easy to translate into other stuff */
727 AST_FORMAT_SLINEAR16,
729 /*! G.726 is standard ADPCM, in RFC3551 packing order */
731 /*! G.726 is standard ADPCM, in AAL2 packing order */
732 AST_FORMAT_G726_AAL2,
733 /*! ADPCM has great sound quality and is still pretty easy to translate */
735 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
736 translate and sounds pretty good */
738 /*! iLBC is not too bad */
740 /*! Speex is free, but computationally more expensive than GSM */
742 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
745 /*! G.729a is faster than 723 and slightly less expensive */
747 /*! Down to G.723.1 which is proprietary but at least designed for voice */
751 /* Strip out video */
752 fmts &= AST_FORMAT_AUDIO_MASK;
754 /* Find the first preferred codec in the format given */
755 for (x = 0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++) {
760 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
765 static const struct ast_channel_tech null_tech = {
767 .description = "Null channel (should not see this)",
770 /*! \brief Create a new channel structure */
771 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num, const char *cid_name, const char *acctcode, const char *exten, const char *context, const int amaflag, const char *name_fmt, ...)
773 struct ast_channel *tmp;
776 struct varshead *headp;
779 /* If shutting down, don't allocate any new channels */
781 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
785 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
788 if (!(tmp->sched = sched_context_create())) {
789 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
794 if ((ast_string_field_init(tmp, 128))) {
795 sched_context_destroy(tmp->sched);
801 tmp->epfd = epoll_create(25);
804 for (x = 0; x < AST_MAX_FDS; x++) {
807 tmp->epfd_data[x] = NULL;
812 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
813 if (tmp->timingfd > -1) {
814 /* Check if timing interface supports new
817 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
825 if (pipe(tmp->alertpipe)) {
826 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
828 if (tmp->timingfd > -1)
829 close(tmp->timingfd);
831 sched_context_destroy(tmp->sched);
832 ast_string_field_free_memory(tmp);
836 flags = fcntl(tmp->alertpipe[0], F_GETFL);
837 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
838 flags = fcntl(tmp->alertpipe[1], F_GETFL);
839 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
841 } else /* Make sure we've got it done right if they don't */
842 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
844 /* Always watch the alertpipe */
845 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
846 /* And timing pipe */
847 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
848 ast_string_field_set(tmp, name, "**Unknown**");
855 tmp->fin = global_fin;
856 tmp->fout = global_fout;
858 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
859 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
860 ast_atomic_fetchadd_int(&uniqueint, 1));
862 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
863 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
866 tmp->cid.cid_name = ast_strdup(cid_name);
867 tmp->cid.cid_num = ast_strdup(cid_num);
869 if (!ast_strlen_zero(name_fmt)) {
870 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
871 * And they all use slightly different formats for their name string.
872 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
873 * This means, that the stringfields must have a routine that takes the va_lists directly, and
874 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
875 * This new function was written so this can be accomplished.
877 va_start(ap1, name_fmt);
878 va_start(ap2, name_fmt);
879 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
884 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
886 /* These 4 variables need to be set up for the cdr_init() to work right */
888 tmp->amaflags = amaflag;
890 tmp->amaflags = ast_default_amaflags;
892 if (!ast_strlen_zero(acctcode))
893 ast_string_field_set(tmp, accountcode, acctcode);
895 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
897 if (!ast_strlen_zero(context))
898 ast_copy_string(tmp->context, context, sizeof(tmp->context));
900 strcpy(tmp->context, "default");
902 if (!ast_strlen_zero(exten))
903 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
905 strcpy(tmp->exten, "s");
909 tmp->cdr = ast_cdr_alloc();
910 ast_cdr_init(tmp->cdr, tmp);
911 ast_cdr_start(tmp->cdr);
913 headp = &tmp->varshead;
914 AST_LIST_HEAD_INIT_NOLOCK(headp);
916 ast_mutex_init(&tmp->lock_dont_use);
918 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
920 ast_string_field_set(tmp, language, defaultlanguage);
922 tmp->tech = &null_tech;
924 AST_RWLIST_WRLOCK(&channels);
925 AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
926 AST_RWLIST_UNLOCK(&channels);
929 * and now, since the channel structure is built, and has its name, let's
930 * call the manager event generator with this Newchannel event. This is the
931 * proper and correct place to make this call, but you sure do have to pass
932 * a lot of data into this func to do it here!
934 if (!ast_strlen_zero(name_fmt)) {
935 manager_event(EVENT_FLAG_CALL, "Newchannel",
937 "ChannelState: %d\r\n"
938 "ChannelStateDesc: %s\r\n"
939 "CallerIDNum: %s\r\n"
940 "CallerIDName: %s\r\n"
941 "AccountCode: %s\r\n"
945 ast_state2str(state),
955 /*! \brief Queue an outgoing media frame */
956 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
959 struct ast_frame *cur;
963 /* Build us a copy and free the original one */
964 if (!(f = ast_frdup(fin))) {
965 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
968 ast_channel_lock(chan);
970 /* See if the last frame on the queue is a hangup, if so don't queue anything */
971 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
973 ast_channel_unlock(chan);
977 /* Count how many frames exist on the queue */
978 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
982 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
983 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
984 if (fin->frametype != AST_FRAME_VOICE) {
985 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
988 ast_debug(1, "Dropping voice to exceptionally long queue on %s\n", chan->name);
990 ast_channel_unlock(chan);
994 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
995 if (chan->alertpipe[1] > -1) {
996 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
997 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
998 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
1000 } else if (chan->timingfd > -1) {
1001 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
1003 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1004 pthread_kill(chan->blocker, SIGURG);
1006 ast_channel_unlock(chan);
1010 /*! \brief Queue a hangup frame for channel */
1011 int ast_queue_hangup(struct ast_channel *chan, int cause)
1013 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
1018 /* Yeah, let's not change a lock-critical value without locking */
1019 if (!ast_channel_trylock(chan)) {
1020 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1022 f.seqno = chan->hangupcause;
1024 ast_channel_unlock(chan);
1026 return ast_queue_frame(chan, &f);
1029 /*! \brief Queue a control frame */
1030 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1032 struct ast_frame f = { AST_FRAME_CONTROL, };
1034 f.subclass = control;
1036 return ast_queue_frame(chan, &f);
1039 /*! \brief Queue a control frame with payload */
1040 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1041 const void *data, size_t datalen)
1043 struct ast_frame f = { AST_FRAME_CONTROL, };
1045 f.subclass = control;
1046 f.data = (void *) data;
1047 f.datalen = datalen;
1049 return ast_queue_frame(chan, &f);
1052 /*! \brief Set defer DTMF flag on channel */
1053 int ast_channel_defer_dtmf(struct ast_channel *chan)
1058 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1059 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1064 /*! \brief Unset defer DTMF flag on channel */
1065 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1068 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1072 * \brief Helper function to find channels.
1074 * It supports these modes:
1076 * prev != NULL : get channel next in list after prev
1077 * name != NULL : get channel with matching name
1078 * name != NULL && namelen != 0 : get channel whose name starts with prefix
1079 * exten != NULL : get channel whose exten or macroexten matches
1080 * context != NULL && exten != NULL : get channel whose context or macrocontext
1082 * It returns with the channel's lock held. If getting the individual lock fails,
1083 * unlock and retry quickly up to 10 times, then give up.
1085 * \note XXX Note that this code has cost O(N) because of the need to verify
1086 * that the object is still on the global list.
1088 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
1089 * can only be done with the lock held or someone could delete the
1090 * object while we work on it. This causes some ugliness in the code.
1091 * Note that removing the first ast_log() may be harmful, as it would
1092 * shorten the retry period and possibly cause failures.
1093 * We should definitely go for a better scheme that is deadlock-free.
1095 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
1096 const char *name, const int namelen,
1097 const char *context, const char *exten)
1099 const char *msg = prev ? "deadlock" : "initial deadlock";
1101 struct ast_channel *c;
1102 const struct ast_channel *_prev = prev;
1104 for (retries = 0; retries < 200; retries++) {
1106 AST_RWLIST_RDLOCK(&channels);
1107 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
1109 if (prev) { /* look for next item */
1110 if (c != prev) /* not this one */
1112 /* found, prepare to return c->next */
1113 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
1114 /* If prev was the last item on the channel list, then we just
1115 * want to return NULL, instead of trying to deref NULL in the
1119 /* We want prev to be NULL in case we end up doing more searching through
1120 * the channel list to find the channel (ie: name searching). If we didn't
1121 * set this to NULL the logic would just blow up
1122 * XXX Need a better explanation for this ...
1125 if (name) { /* want match by name */
1126 if ((!namelen && strcasecmp(c->name, name) && strcmp(c->uniqueid, name)) ||
1127 (namelen && strncasecmp(c->name, name, namelen)))
1128 continue; /* name match failed */
1130 if (context && strcasecmp(c->context, context) &&
1131 strcasecmp(c->macrocontext, context))
1132 continue; /* context match failed */
1133 if (strcasecmp(c->exten, exten) &&
1134 strcasecmp(c->macroexten, exten))
1135 continue; /* exten match failed */
1137 /* if we get here, c points to the desired record */
1140 /* exit if chan not found or mutex acquired successfully */
1141 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1142 done = c == NULL || ast_channel_trylock(c) == 0;
1144 ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
1145 if (retries == 199) {
1146 /* We are about to fail due to a deadlock, so report this
1147 * while we still have the list lock.
1149 ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
1150 /* As we have deadlocked, we will skip this channel and
1151 * see if there is another match.
1152 * NOTE: No point doing this for a full-name match,
1153 * as there can be no more matches.
1155 if (!(name && !namelen)) {
1161 AST_RWLIST_UNLOCK(&channels);
1164 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1165 * starting from the beginning of the list we can restore our saved pointer to the previous
1166 * channel and start from there.
1169 usleep(1); /* give other threads a chance before retrying */
1175 /*! \brief Browse channels in use */
1176 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1178 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1181 /*! \brief Get channel by name and lock it */
1182 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1184 return channel_find_locked(NULL, name, 0, NULL, NULL);
1187 /*! \brief Get channel by name prefix and lock it */
1188 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1190 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1193 /*! \brief Get next channel by name prefix and lock it */
1194 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1197 return channel_find_locked(chan, name, namelen, NULL, NULL);
1200 /*! \brief Get channel by exten (and optionally context) and lock it */
1201 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1203 return channel_find_locked(NULL, NULL, 0, context, exten);
1206 /*! \brief Get next channel by exten (and optionally context) and lock it */
1207 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1208 const char *context)
1210 return channel_find_locked(chan, NULL, 0, context, exten);
1213 /*! \brief Wait, look for hangups and condition arg */
1214 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1216 struct ast_frame *f;
1219 if (cond && ((*cond)(data) == 0))
1221 ms = ast_waitfor(chan, ms);
1234 /*! \brief Wait, look for hangups */
1235 int ast_safe_sleep(struct ast_channel *chan, int ms)
1237 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1240 static void free_cid(struct ast_callerid *cid)
1243 ast_free(cid->cid_dnid);
1245 ast_free(cid->cid_num);
1247 ast_free(cid->cid_name);
1249 ast_free(cid->cid_ani);
1251 ast_free(cid->cid_rdnis);
1252 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1255 /*! \brief Free a channel structure */
1256 void ast_channel_free(struct ast_channel *chan)
1262 struct ast_var_t *vardata;
1263 struct ast_frame *f;
1264 struct varshead *headp;
1265 struct ast_datastore *datastore = NULL;
1266 char name[AST_CHANNEL_NAME];
1268 headp=&chan->varshead;
1270 AST_RWLIST_WRLOCK(&channels);
1271 if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1272 AST_RWLIST_UNLOCK(&channels);
1273 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1275 /* Lock and unlock the channel just to be sure nobody has it locked still
1276 due to a reference retrieved from the channel list. */
1277 ast_channel_lock(chan);
1278 ast_channel_unlock(chan);
1280 /* Get rid of each of the data stores on the channel */
1281 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1282 /* Free the data store */
1283 ast_channel_datastore_free(datastore);
1285 /* Lock and unlock the channel just to be sure nobody has it locked still
1286 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1287 ast_channel_lock(chan);
1288 ast_channel_unlock(chan);
1290 if (chan->tech_pvt) {
1291 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1292 ast_free(chan->tech_pvt);
1296 sched_context_destroy(chan->sched);
1298 ast_copy_string(name, chan->name, sizeof(name));
1300 /* Stop monitoring */
1302 chan->monitor->stop( chan, 0 );
1304 /* If there is native format music-on-hold state, free it */
1305 if (chan->music_state)
1306 ast_moh_cleanup(chan);
1308 /* Free translators */
1309 if (chan->readtrans)
1310 ast_translator_free_path(chan->readtrans);
1311 if (chan->writetrans)
1312 ast_translator_free_path(chan->writetrans);
1314 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1315 free_cid(&chan->cid);
1316 /* Close pipes if appropriate */
1317 if ((fd = chan->alertpipe[0]) > -1)
1319 if ((fd = chan->alertpipe[1]) > -1)
1321 if ((fd = chan->timingfd) > -1)
1324 for (i = 0; i < AST_MAX_FDS; i++) {
1325 if (chan->epfd_data[i])
1326 free(chan->epfd_data[i]);
1330 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1333 /* loop over the variables list, freeing all data and deleting list items */
1334 /* no need to lock the list, as the channel is already locked */
1336 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1337 ast_var_delete(vardata);
1339 ast_app_group_discard(chan);
1341 /* Destroy the jitterbuffer */
1342 ast_jb_destroy(chan);
1344 ast_mutex_destroy(&chan->lock_dont_use);
1346 ast_string_field_free_memory(chan);
1348 AST_RWLIST_UNLOCK(&channels);
1350 ast_device_state_changed_literal(name);
1353 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1355 struct ast_datastore *datastore = NULL;
1357 /* Make sure we at least have type so we can identify this */
1362 /* Allocate memory for datastore and clear it */
1363 datastore = ast_calloc(1, sizeof(*datastore));
1368 datastore->info = info;
1370 datastore->uid = ast_strdup(uid);
1375 int ast_channel_datastore_free(struct ast_datastore *datastore)
1379 /* Using the destroy function (if present) destroy the data */
1380 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1381 datastore->info->destroy(datastore->data);
1382 datastore->data = NULL;
1385 /* Free allocated UID memory */
1386 if (datastore->uid != NULL) {
1387 ast_free((void *) datastore->uid);
1388 datastore->uid = NULL;
1391 /* Finally free memory used by ourselves */
1392 ast_free(datastore);
1397 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1399 struct ast_datastore *datastore = NULL, *datastore2;
1401 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1402 if (datastore->inheritance > 0) {
1403 datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1405 datastore2->data = datastore->info->duplicate(datastore->data);
1406 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1407 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1414 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1418 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1423 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1425 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1428 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1430 struct ast_datastore *datastore = NULL;
1435 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1436 if (datastore->info == info) {
1437 if (uid != NULL && datastore->uid != NULL) {
1438 if (!strcasecmp(uid, datastore->uid)) {
1439 /* Matched by type AND uid */
1443 /* Matched by type at least */
1448 AST_LIST_TRAVERSE_SAFE_END
1453 /*! Set the file descriptor on the channel */
1454 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
1457 struct epoll_event ev;
1458 struct ast_epoll_data *aed = NULL;
1460 if (chan->fds[which] > -1) {
1461 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
1462 aed = chan->epfd_data[which];
1465 /* If this new fd is valid, add it to the epoll */
1467 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
1470 chan->epfd_data[which] = aed;
1474 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1476 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
1478 /* We don't have to keep around this epoll data structure now */
1480 chan->epfd_data[which] = NULL;
1483 chan->fds[which] = fd;
1487 /*! Add a channel to an optimized waitfor */
1488 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
1491 struct epoll_event ev;
1494 if (chan0->epfd == -1)
1497 /* Iterate through the file descriptors on chan1, adding them to chan0 */
1498 for (i = 0; i < AST_MAX_FDS; i++) {
1499 if (chan1->fds[i] == -1)
1501 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1502 ev.data.ptr = chan1->epfd_data[i];
1503 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
1510 /*! Delete a channel from an optimized waitfor */
1511 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
1514 struct epoll_event ev;
1517 if (chan0->epfd == -1)
1520 for (i = 0; i < AST_MAX_FDS; i++) {
1521 if (chan1->fds[i] == -1)
1523 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
1530 /*! \brief Softly hangup a channel, don't lock */
1531 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1533 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1534 /* Inform channel driver that we need to be hung up, if it cares */
1535 chan->_softhangup |= cause;
1536 ast_queue_frame(chan, &ast_null_frame);
1537 /* Interrupt any poll call or such */
1538 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1539 pthread_kill(chan->blocker, SIGURG);
1543 /*! \brief Softly hangup a channel, lock */
1544 int ast_softhangup(struct ast_channel *chan, int cause)
1547 ast_channel_lock(chan);
1548 res = ast_softhangup_nolock(chan, cause);
1549 ast_channel_unlock(chan);
1553 static void free_translation(struct ast_channel *clone)
1555 if (clone->writetrans)
1556 ast_translator_free_path(clone->writetrans);
1557 if (clone->readtrans)
1558 ast_translator_free_path(clone->readtrans);
1559 clone->writetrans = NULL;
1560 clone->readtrans = NULL;
1561 clone->rawwriteformat = clone->nativeformats;
1562 clone->rawreadformat = clone->nativeformats;
1565 /*! \brief Hangup a channel */
1566 int ast_hangup(struct ast_channel *chan)
1569 struct ast_cdr *cdr = NULL;
1571 /* Don't actually hang up a channel that will masquerade as someone else, or
1572 if someone is going to masquerade as us */
1573 ast_channel_lock(chan);
1575 if (chan->audiohooks) {
1576 ast_audiohook_detach_list(chan->audiohooks);
1577 chan->audiohooks = NULL;
1580 ast_autoservice_stop(chan);
1583 if (ast_do_masquerade(chan))
1584 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1588 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1589 ast_channel_unlock(chan);
1592 /* If this channel is one which will be masqueraded into something,
1593 mark it as a zombie already, so we know to free it later */
1595 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1596 ast_channel_unlock(chan);
1599 free_translation(chan);
1600 /* Close audio stream */
1602 ast_closestream(chan->stream);
1603 chan->stream = NULL;
1605 /* Close video stream */
1606 if (chan->vstream) {
1607 ast_closestream(chan->vstream);
1608 chan->vstream = NULL;
1611 sched_context_destroy(chan->sched);
1615 if (chan->generatordata) /* Clear any tone stuff remaining */
1616 if (chan->generator && chan->generator->release)
1617 chan->generator->release(chan, chan->generatordata);
1618 chan->generatordata = NULL;
1619 chan->generator = NULL;
1620 if (chan->cdr) { /* End the CDR if it hasn't already */
1621 ast_cdr_end(chan->cdr);
1625 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1626 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1627 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1628 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1631 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1632 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1633 if (chan->tech->hangup)
1634 res = chan->tech->hangup(chan);
1636 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1639 ast_channel_unlock(chan);
1640 manager_event(EVENT_FLAG_CALL, "Hangup",
1643 "CallerIDNum: %s\r\n"
1644 "CallerIDName: %s\r\n"
1646 "Cause-txt: %s\r\n",
1649 S_OR(chan->cid.cid_num, "<unknown>"),
1650 S_OR(chan->cid.cid_name, "<unknown>"),
1652 ast_cause2str(chan->hangupcause)
1654 ast_channel_free(chan);
1657 ast_cdr_detach(cdr);
1662 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1666 ast_channel_lock(chan);
1668 /* You can't answer an outbound call */
1669 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1670 ast_channel_unlock(chan);
1674 /* Stop if we're a zombie or need a soft hangup */
1675 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1676 ast_channel_unlock(chan);
1680 switch (chan->_state) {
1681 case AST_STATE_RINGING:
1682 case AST_STATE_RING:
1683 if (chan->tech->answer)
1684 res = chan->tech->answer(chan);
1685 ast_setstate(chan, AST_STATE_UP);
1686 ast_cdr_answer(chan->cdr);
1687 ast_channel_unlock(chan);
1689 ast_safe_sleep(chan, delay);
1693 ast_cdr_answer(chan->cdr);
1698 chan->visible_indication = 0;
1699 ast_channel_unlock(chan);
1704 int ast_answer(struct ast_channel *chan)
1706 return __ast_answer(chan, 500);
1709 void ast_deactivate_generator(struct ast_channel *chan)
1711 ast_channel_lock(chan);
1712 if (chan->generatordata) {
1713 if (chan->generator && chan->generator->release)
1714 chan->generator->release(chan, chan->generatordata);
1715 chan->generatordata = NULL;
1716 chan->generator = NULL;
1717 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
1718 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1719 ast_settimeout(chan, 0, NULL, NULL);
1721 ast_channel_unlock(chan);
1724 static int generator_force(const void *data)
1726 /* Called if generator doesn't have data */
1729 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1730 struct ast_channel *chan = (struct ast_channel *)data;
1732 ast_channel_lock(chan);
1733 tmp = chan->generatordata;
1734 chan->generatordata = NULL;
1735 if (chan->generator)
1736 generate = chan->generator->generate;
1737 ast_channel_unlock(chan);
1739 if (!tmp || !generate)
1742 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
1744 chan->generatordata = tmp;
1747 ast_debug(1, "Auto-deactivating generator\n");
1748 ast_deactivate_generator(chan);
1754 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1758 ast_channel_lock(chan);
1760 if (chan->generatordata) {
1761 if (chan->generator && chan->generator->release)
1762 chan->generator->release(chan, chan->generatordata);
1763 chan->generatordata = NULL;
1767 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1772 ast_settimeout(chan, 160, generator_force, chan);
1773 chan->generator = gen;
1776 ast_channel_unlock(chan);
1781 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1782 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1785 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1789 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1791 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
1792 int *exception, int *outfd, int *ms)
1794 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1795 int *exception, int *outfd, int *ms)
1798 struct timeval start = { 0 , 0 };
1799 struct pollfd *pfds = NULL;
1804 struct timeval now = { 0, 0 };
1805 struct timeval whentohangup = { 0, 0 }, diff;
1806 struct ast_channel *winner = NULL;
1812 if ((sz = n * AST_MAX_FDS + nfds)) {
1813 pfds = alloca(sizeof(*pfds) * sz);
1814 fdmap = alloca(sizeof(*fdmap) * sz);
1822 /* Perform any pending masquerades */
1823 for (x = 0; x < n; x++) {
1824 ast_channel_lock(c[x]);
1825 if (c[x]->masq && ast_do_masquerade(c[x])) {
1826 ast_log(LOG_WARNING, "Masquerade failed\n");
1828 ast_channel_unlock(c[x]);
1831 if (!ast_tvzero(c[x]->whentohangup)) {
1832 if (ast_tvzero(whentohangup))
1834 diff = ast_tvsub(c[x]->whentohangup, now);
1835 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
1836 /* Should already be hungup */
1837 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1838 ast_channel_unlock(c[x]);
1841 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
1842 whentohangup = diff;
1844 ast_channel_unlock(c[x]);
1846 /* Wait full interval */
1848 if (!ast_tvzero(whentohangup)) {
1849 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
1850 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1854 * Build the pollfd array, putting the channels' fds first,
1855 * followed by individual fds. Order is important because
1856 * individual fd's must have priority over channel fds.
1859 for (x = 0; x < n; x++) {
1860 for (y = 0; y < AST_MAX_FDS; y++) {
1861 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1862 fdmap[max].chan = x; /* channel x is linked to this pfds */
1863 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1865 CHECK_BLOCKING(c[x]);
1867 /* Add the individual fds */
1868 for (x = 0; x < nfds; x++) {
1869 fdmap[max].chan = -1;
1870 max += ast_add_fd(&pfds[max], fds[x]);
1874 start = ast_tvnow();
1876 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1881 res = poll(pfds, max, kbrms);
1884 } while (!res && (rms > 0));
1886 res = poll(pfds, max, rms);
1888 for (x = 0; x < n; x++)
1889 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1890 if (res < 0) { /* Simulate a timeout if we were interrupted */
1895 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
1897 for (x = 0; x < n; x++) {
1898 if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
1899 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1905 if (res == 0) { /* no fd ready, reset timeout and done */
1906 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1910 * Then check if any channel or fd has a pending event.
1911 * Remember to check channels first and fds last, as they
1912 * must have priority on setting 'winner'
1914 for (x = 0; x < max; x++) {
1915 res = pfds[x].revents;
1918 if (fdmap[x].chan >= 0) { /* this is a channel */
1919 winner = c[fdmap[x].chan]; /* override previous winners */
1921 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1923 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1924 winner->fdno = fdmap[x].fdno;
1925 } else { /* this is an fd */
1927 *outfd = pfds[x].fd;
1929 *exception = (res & POLLPRI) ? -1 : 0;
1934 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1942 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
1944 struct timeval start = { 0 , 0 };
1946 struct epoll_event ev[1];
1947 long diff, rms = *ms;
1948 struct ast_channel *winner = NULL;
1949 struct ast_epoll_data *aed = NULL;
1951 ast_channel_lock(chan);
1953 /* See if this channel needs to be masqueraded */
1954 if (chan->masq && ast_do_masquerade(chan)) {
1955 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
1957 ast_channel_unlock(chan);
1961 /* Figure out their timeout */
1962 if (!ast_tvzero(chan->whentohangup)) {
1963 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
1964 /* They should already be hungup! */
1965 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1966 ast_channel_unlock(chan);
1969 /* If this value is smaller then the current one... make it priority */
1974 ast_channel_unlock(chan);
1976 /* Time to make this channel block... */
1977 CHECK_BLOCKING(chan);
1980 start = ast_tvnow();
1982 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
1983 res = epoll_wait(chan->epfd, ev, 1, rms);
1986 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1988 /* Simulate a timeout if we were interrupted */
1995 /* If this channel has a timeout see if it expired */
1996 if (!ast_tvzero(chan->whentohangup)) {
1997 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
1998 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2003 /* No fd ready, reset timeout and be done for now */
2009 /* See what events are pending */
2010 aed = ev[0].data.ptr;
2011 chan->fdno = aed->which;
2012 if (ev[0].events & EPOLLPRI)
2013 ast_set_flag(chan, AST_FLAG_EXCEPTION);
2015 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2018 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2026 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2028 struct timeval start = { 0 , 0 };
2030 struct epoll_event ev[25] = { { 0, } };
2031 struct timeval now = { 0, 0 };
2032 long whentohangup = 0, diff = 0, rms = *ms;
2033 struct ast_channel *winner = NULL;
2035 for (i = 0; i < n; i++) {
2036 ast_channel_lock(c[i]);
2037 if (c[i]->masq && ast_do_masquerade(c[i])) {
2038 ast_log(LOG_WARNING, "Masquerade failed\n");
2040 ast_channel_unlock(c[i]);
2043 if (!ast_tvzero(c[i]->whentohangup)) {
2044 if (whentohangup == 0)
2046 if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
2047 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2048 ast_channel_unlock(c[i]);
2051 if (!whentohangup || whentohangup > diff)
2052 whentohangup = diff;
2054 ast_channel_unlock(c[i]);
2055 CHECK_BLOCKING(c[i]);
2061 if (*ms >= 0 && *ms < rms)
2066 start = ast_tvnow();
2068 res = epoll_wait(c[0]->epfd, ev, 25, rms);
2070 for (i = 0; i < n; i++)
2071 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2081 for (i = 0; i < n; i++) {
2082 if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
2083 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2095 for (i = 0; i < res; i++) {
2096 struct ast_epoll_data *aed = ev[i].data.ptr;
2098 if (!ev[i].events || !aed)
2102 if (ev[i].events & EPOLLPRI)
2103 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2105 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2106 winner->fdno = aed->which;
2110 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2118 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2119 int *exception, int *outfd, int *ms)
2121 /* Clear all provided values in one place. */
2127 /* If no epoll file descriptor is available resort to classic nandfds */
2128 if (!n || nfds || c[0]->epfd == -1)
2129 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2130 else if (!nfds && n == 1)
2131 return ast_waitfor_nandfds_simple(c[0], ms);
2133 return ast_waitfor_nandfds_complex(c, n, ms);
2137 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2139 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2142 int ast_waitfor(struct ast_channel *c, int ms)
2144 int oldms = ms; /* -1 if no timeout */
2146 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2147 if ((ms < 0) && (oldms < 0))
2152 /* XXX never to be called with ms = -1 */
2153 int ast_waitfordigit(struct ast_channel *c, int ms)
2155 return ast_waitfordigit_full(c, ms, -1, -1);
2158 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
2162 if (c->timingfd > -1) {
2167 ast_debug(1, "Scheduling timer at %d sample intervals\n", samples);
2168 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
2169 c->timingfunc = func;
2170 c->timingdata = data;
2176 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2178 /* Stop if we're a zombie or need a soft hangup */
2179 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2182 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2183 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2185 /* Wait for a digit, no more than ms milliseconds total. */
2188 struct ast_channel *rchan;
2192 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2194 if (!rchan && outfd < 0 && ms) {
2195 if (errno == 0 || errno == EINTR)
2197 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2198 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2200 } else if (outfd > -1) {
2201 /* The FD we were watching has something waiting */
2202 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2203 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2207 struct ast_frame *f = ast_read(c);
2211 switch (f->frametype) {
2212 case AST_FRAME_DTMF_BEGIN:
2214 case AST_FRAME_DTMF_END:
2217 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2219 case AST_FRAME_CONTROL:
2220 switch (f->subclass) {
2221 case AST_CONTROL_HANGUP:
2223 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2225 case AST_CONTROL_RINGING:
2226 case AST_CONTROL_ANSWER:
2227 case AST_CONTROL_SRCUPDATE:
2231 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2235 case AST_FRAME_VOICE:
2236 /* Write audio if appropriate */
2238 write(audiofd, f->data, f->datalen);
2247 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2249 return 0; /* Time is up */
2252 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2254 manager_event(EVENT_FLAG_DTMF,
2262 chan->name, chan->uniqueid, digit, direction, begin, end);
2265 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2267 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2268 void *tmp = chan->generatordata;
2269 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2273 if (chan->timingfunc) {
2274 ast_debug(1, "Generator got voice, switching to phase locked mode\n");
2275 ast_settimeout(chan, 0, NULL, NULL);
2278 chan->generatordata = NULL; /* reset, to let writes go through */
2280 if (f->subclass != chan->writeformat) {
2282 factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass));
2283 samples = (int) ( ((float) f->samples) * factor );
2285 samples = f->samples;
2288 if (chan->generator->generate) {
2289 generate = chan->generator->generate;
2291 /* This unlock is here based on two assumptions that hold true at this point in the
2292 * code. 1) this function is only called from within __ast_read() and 2) all generators
2293 * call ast_write() in their generate callback.
2295 * The reason this is added is so that when ast_write is called, the lock that occurs
2296 * there will not recursively lock the channel. Doing this will cause intended deadlock
2297 * avoidance not to work in deeper functions
2299 ast_channel_unlock(chan);
2300 res = generate(chan, tmp, f->datalen, samples);
2301 ast_channel_lock(chan);
2302 chan->generatordata = tmp;
2304 ast_debug(1, "Auto-deactivating generator\n");
2305 ast_deactivate_generator(chan);
2308 } else if (f->frametype == AST_FRAME_CNG) {
2309 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2310 ast_debug(1, "Generator got CNG, switching to timed mode\n");
2311 ast_settimeout(chan, 160, generator_force, chan);
2316 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2318 struct ast_frame *f = NULL; /* the return value */
2321 int count = 0, cause = 0;
2323 /* this function is very long so make sure there is only one return
2324 * point at the end (there are only two exceptions to this).
2326 while(ast_channel_trylock(chan)) {
2328 /*cannot goto done since the channel is not locked*/
2329 return &ast_null_frame;
2334 if (ast_do_masquerade(chan))
2335 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2337 f = &ast_null_frame;
2341 /* Stop if we're a zombie or need a soft hangup */
2342 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2343 if (chan->generator)
2344 ast_deactivate_generator(chan);
2347 prestate = chan->_state;
2349 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2350 !ast_strlen_zero(chan->dtmfq) &&
2351 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2352 /* We have DTMF that has been deferred. Return it now */
2353 chan->dtmff.subclass = chan->dtmfq[0];
2354 /* Drop first digit from the buffer */
2355 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2357 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2358 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2359 chan->dtmff.frametype = AST_FRAME_DTMF_END;
2361 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %d queued on %s\n", f->subclass, AST_DEFAULT_EMULATE_DTMF_DURATION, chan->name);
2362 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2363 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2364 chan->emulate_dtmf_digit = f->subclass;
2365 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2367 chan->dtmf_tv = ast_tvnow();
2371 /* Read and ignore anything on the alertpipe, but read only
2372 one sizeof(blah) per frame that we send from it */
2373 if (chan->alertpipe[0] > -1)
2374 read(chan->alertpipe[0], &blah, sizeof(blah));
2377 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2380 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2382 /* IF we can't get event, assume it's an expired as-per the old interface */
2383 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2385 blah = ZT_EVENT_TIMER_EXPIRED;
2387 if (blah == ZT_EVENT_TIMER_PING) {
2388 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2389 /* Acknowledge PONG unless we need it again */
2390 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2391 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2394 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2395 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2396 if (chan->timingfunc) {
2397 /* save a copy of func/data before unlocking the channel */
2398 int (*func)(const void *) = chan->timingfunc;
2399 void *data = chan->timingdata;
2400 ast_channel_unlock(chan);
2404 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2405 chan->timingdata = NULL;
2406 ast_channel_unlock(chan);
2408 /* cannot 'goto done' because the channel is already unlocked */
2409 return &ast_null_frame;
2411 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2414 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2415 /* if the AST_GENERATOR_FD is set, call the generator with args
2416 * set to -1 so it can do whatever it needs to.
2418 void *tmp = chan->generatordata;
2419 chan->generatordata = NULL; /* reset to let ast_write get through */
2420 chan->generator->generate(chan, tmp, -1, -1);
2421 chan->generatordata = tmp;
2422 f = &ast_null_frame;
2426 /* Check for pending read queue */
2427 if (!AST_LIST_EMPTY(&chan->readq)) {
2428 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2429 /* Interpret hangup and return NULL */
2430 /* XXX why not the same for frames from the channel ? */
2431 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2437 chan->blocker = pthread_self();
2438 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2439 if (chan->tech->exception)
2440 f = chan->tech->exception(chan);
2442 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2443 f = &ast_null_frame;
2445 /* Clear the exception flag */
2446 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2447 } else if (chan->tech->read)
2448 f = chan->tech->read(chan);
2450 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2454 /* if the channel driver returned more than one frame, stuff the excess
2455 into the readq for the next ast_read call (note that we can safely assume
2456 that the readq is empty, because otherwise we would not have called into
2457 the channel driver and f would be only a single frame)
2459 if (AST_LIST_NEXT(f, frame_list)) {
2460 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2461 AST_LIST_NEXT(f, frame_list) = NULL;
2464 switch (f->frametype) {
2465 case AST_FRAME_CONTROL:
2466 if (f->subclass == AST_CONTROL_ANSWER) {
2467 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2468 ast_debug(1, "Ignoring answer on an inbound call!\n");
2470 f = &ast_null_frame;
2471 } else if (prestate == AST_STATE_UP) {
2472 ast_debug(1, "Dropping duplicate answer!\n");
2474 f = &ast_null_frame;
2476 /* Answer the CDR */
2477 ast_setstate(chan, AST_STATE_UP);
2478 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2479 to keep from throwing off the basic order of the universe,
2480 we will try to keep this cdr from getting posted. */
2481 chan->cdr = ast_cdr_alloc();
2482 ast_cdr_init(chan->cdr, chan);
2483 ast_cdr_start(chan->cdr);
2486 ast_cdr_answer(chan->cdr);
2490 case AST_FRAME_DTMF_END:
2491 send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2492 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2493 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2494 * However, only let emulation be forced if the other end cares about BEGIN frames */
2495 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2496 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2497 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2498 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2499 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2501 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2503 f = &ast_null_frame;
2504 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2505 if (!ast_tvzero(chan->dtmf_tv) &&
2506 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2507 /* If it hasn't been long enough, defer this digit */
2508 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2509 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2510 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2512 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2514 f = &ast_null_frame;
2516 /* There was no begin, turn this into a begin and send the end later */
2517 f->frametype = AST_FRAME_DTMF_BEGIN;
2518 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2519 chan->emulate_dtmf_digit = f->subclass;
2520 chan->dtmf_tv = ast_tvnow();
2522 if (f->len > AST_MIN_DTMF_DURATION)
2523 chan->emulate_dtmf_duration = f->len;
2525 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2527 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2528 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2530 if (chan->audiohooks) {
2531 struct ast_frame *old_frame = f;
2533 * \todo XXX It is possible to write a digit to the audiohook twice
2534 * if the digit was originally read while the channel was in autoservice. */
2535 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2537 ast_frfree(old_frame);
2540 struct timeval now = ast_tvnow();
2541 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2542 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2543 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2545 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2546 } else if (!f->len) {
2547 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2548 f->len = AST_MIN_DTMF_DURATION;
2550 if (f->len < AST_MIN_DTMF_DURATION) {
2551 ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f->subclass, f->len, AST_MIN_DTMF_DURATION, chan->name);
2552 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2553 chan->emulate_dtmf_digit = f->subclass;
2554 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2556 f = &ast_null_frame;
2558 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2559 chan->dtmf_tv = now;
2561 if (chan->audiohooks) {
2562 struct ast_frame *old_frame = f;
2563 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2565 ast_frfree(old_frame);
2569 case AST_FRAME_DTMF_BEGIN:
2570 send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2571 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2572 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
2573 (!ast_tvzero(chan->dtmf_tv) &&
2574 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2575 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2577 f = &ast_null_frame;
2579 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2580 chan->dtmf_tv = ast_tvnow();
2581 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2584 case AST_FRAME_NULL:
2585 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2586 * is reached , because we want to make sure we pass at least one
2587 * voice frame through before starting the next digit, to ensure a gap
2588 * between DTMF digits. */
2589 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2590 struct timeval now = ast_tvnow();
2591 if (!chan->emulate_dtmf_duration) {
2592 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2593 chan->emulate_dtmf_digit = 0;
2594 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2595 chan->emulate_dtmf_duration = 0;
2598 f->frametype = AST_FRAME_DTMF_END;
2599 f->subclass = chan->emulate_dtmf_digit;
2600 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2601 chan->dtmf_tv = now;
2602 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2603 chan->emulate_dtmf_digit = 0;
2604 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2608 case AST_FRAME_VOICE:
2609 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2610 * is reached , because we want to make sure we pass at least one
2611 * voice frame through before starting the next digit, to ensure a gap
2612 * between DTMF digits. */
2613 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2614 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2615 chan->emulate_dtmf_digit = 0;
2618 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2620 ast_read_generator_actions(chan, f);
2622 f = &ast_null_frame;
2625 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2626 struct timeval now = ast_tvnow();
2627 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2628 chan->emulate_dtmf_duration = 0;
2631 f->frametype = AST_FRAME_DTMF_END;
2632 f->subclass = chan->emulate_dtmf_digit;
2633 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2634 chan->dtmf_tv = now;
2635 if (chan->audiohooks) {
2636 struct ast_frame *old_frame = f;
2637 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2639 ast_frfree(old_frame);
2641 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2643 /* Drop voice frames while we're still in the middle of the digit */
2645 f = &ast_null_frame;
2647 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2648 /* This frame can't be from the current native formats -- drop it on the
2650 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2651 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2653 f = &ast_null_frame;
2654 } else if ((f->frametype == AST_FRAME_VOICE)) {
2655 /* Send frame to audiohooks if present */
2656 if (chan->audiohooks) {
2657 struct ast_frame *old_frame = f;
2658 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2660 ast_frfree(old_frame);
2662 if (chan->monitor && chan->monitor->read_stream ) {
2663 /* XXX what does this do ? */
2664 #ifndef MONITOR_CONSTANT_DELAY
2665 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2667 jump = chan->outsmpl - chan->insmpl;
2668 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2669 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2670 chan->insmpl += jump + f->samples;
2672 chan->insmpl+= f->samples;
2674 int jump = chan->outsmpl - chan->insmpl;
2675 if (jump - MONITOR_DELAY >= 0) {
2676 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2677 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2678 chan->insmpl += jump;
2680 chan->insmpl += f->samples;
2682 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2683 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2684 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2688 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2689 f = &ast_null_frame;
2691 /* Run generator sitting on the line if timing device not available
2692 * and synchronous generation of outgoing frames is necessary */
2693 ast_read_generator_actions(chan, f);
2696 /* Just pass it on! */
2700 /* Make sure we always return NULL in the future */
2701 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2703 chan->hangupcause = cause;
2704 if (chan->generator)
2705 ast_deactivate_generator(chan);
2706 /* End the CDR if appropriate */
2708 ast_cdr_end(chan->cdr);
2711 /* High bit prints debugging */
2712 if (chan->fin & DEBUGCHAN_FLAG)
2713 ast_frame_dump(chan->name, f, "<<");
2714 chan->fin = FRAMECOUNT_INC(chan->fin);
2717 if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2718 chan->generator->digit(chan, f->subclass);
2720 ast_channel_unlock(chan);
2724 int ast_internal_timing_enabled(struct ast_channel *chan)
2726 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2727 ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2731 struct ast_frame *ast_read(struct ast_channel *chan)
2733 return __ast_read(chan, 0);
2736 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2738 return __ast_read(chan, 1);
2741 int ast_indicate(struct ast_channel *chan, int condition)
2743 return ast_indicate_data(chan, condition, NULL, 0);
2746 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2750 ast_channel_lock(chan);
2751 /* Stop if we're a zombie or need a soft hangup */
2752 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2753 ast_channel_unlock(chan);
2756 if (chan->tech->indicate)
2757 res = chan->tech->indicate(chan, condition, data, datalen);
2758 ast_channel_unlock(chan);
2759 if (!chan->tech->indicate || res) {
2761 * Device does not support (that) indication, lets fake
2762 * it by doing our own tone generation. (PM2002)
2765 ast_playtones_stop(chan);
2767 const struct ind_tone_zone_sound *ts = NULL;
2768 switch (condition) {
2769 case AST_CONTROL_RINGING:
2770 ts = ast_get_indication_tone(chan->zone, "ring");
2772 case AST_CONTROL_BUSY:
2773 ts = ast_get_indication_tone(chan->zone, "busy");
2775 case AST_CONTROL_CONGESTION:
2776 ts = ast_get_indication_tone(chan->zone, "congestion");
2779 if (ts && ts->data[0]) {
2780 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2781 ast_playtones_start(chan,0,ts->data, 1);
2783 chan->visible_indication = condition;
2784 } else if (condition == AST_CONTROL_PROGRESS) {
2785 /* ast_playtones_stop(chan); */
2786 } else if (condition == AST_CONTROL_PROCEEDING) {
2787 /* Do nothing, really */
2788 } else if (condition == AST_CONTROL_HOLD) {
2789 /* Do nothing.... */
2790 } else if (condition == AST_CONTROL_UNHOLD) {
2791 /* Do nothing.... */
2792 } else if (condition == AST_CONTROL_VIDUPDATE) {
2793 /* Do nothing.... */
2794 } else if (condition == AST_CONTROL_SRCUPDATE) {
2798 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2803 chan->visible_indication = condition;
2808 int ast_recvchar(struct ast_channel *chan, int timeout)
2811 char *buf = ast_recvtext(chan, timeout);
2813 return -1; /* error or timeout */
2814 c = *(unsigned char *)buf;
2819 char *ast_recvtext(struct ast_channel *chan, int timeout)
2825 struct ast_frame *f;
2826 if (ast_check_hangup(chan))
2828 res = ast_waitfor(chan, timeout);
2829 if (res <= 0) /* timeout or error */
2831 timeout = res; /* update timeout */
2834 break; /* no frame */
2835 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2836 done = 1; /* force a break */
2837 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2838 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2846 int ast_sendtext(struct ast_channel *chan, const char *text)
2849 /* Stop if we're a zombie or need a soft hangup */
2850 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2852 CHECK_BLOCKING(chan);
2853 if (chan->tech->send_text)
2854 res = chan->tech->send_text(chan, text);
2855 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2859 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2861 /* Device does not support DTMF tones, lets fake
2862 * it by doing our own generation. */
2863 static const char* dtmf_tones[] = {
2882 if (!chan->tech->send_digit_begin)
2885 if (!chan->tech->send_digit_begin(chan, digit))
2888 if (digit >= '0' && digit <='9')
2889 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2890 else if (digit >= 'A' && digit <= 'D')
2891 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2892 else if (digit == '*')
2893 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2894 else if (digit == '#')
2895 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2898 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2904 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2908 if (chan->tech->send_digit_end)
2909 res = chan->tech->send_digit_end(chan, digit, duration);
2911 if (res && chan->generator)
2912 ast_playtones_stop(chan);
2917 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
2919 if (chan->tech->send_digit_begin) {
2920 ast_senddigit_begin(chan, digit);
2921 ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2924 return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2927 int ast_prod(struct ast_channel *chan)
2929 struct ast_frame a = { AST_FRAME_VOICE };
2932 /* Send an empty audio frame to get things moving */
2933 if (chan->_state != AST_STATE_UP) {
2934 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2935 a.subclass = chan->rawwriteformat;
2936 a.data = nothing + AST_FRIENDLY_OFFSET;
2938 if (ast_write(chan, &a))
2939 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2944 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2947 if (!chan->tech->write_video)
2949 res = ast_write(chan, fr);
2955 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2958 struct ast_frame *f = NULL, *f2 = NULL;
2961 /*Deadlock avoidance*/
2962 while(ast_channel_trylock(chan)) {
2963 /*cannot goto done since the channel is not locked*/
2965 ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
2970 /* Stop if we're a zombie or need a soft hangup */
2971 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2974 /* Handle any pending masquerades */
2975 if (chan->masq && ast_do_masquerade(chan)) {
2976 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2980 res = 0; /* XXX explain, why 0 ? */
2983 if (chan->generatordata) {
2984 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2985 ast_deactivate_generator(chan);
2987 if (fr->frametype == AST_FRAME_DTMF_END) {
2988 /* There is a generator running while we're in the middle of a digit.
2989 * It's probably inband DTMF, so go ahead and pass it so it can
2990 * stop the generator */
2991 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2992 ast_channel_unlock(chan);
2993 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2994 ast_channel_lock(chan);
2995 CHECK_BLOCKING(chan);
2996 } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2997 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2998 res = (chan->tech->indicate == NULL) ? 0 :
2999 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
3001 res = 0; /* XXX explain, why 0 ? */
3005 /* High bit prints debugging */
3006 if (chan->fout & DEBUGCHAN_FLAG)
3007 ast_frame_dump(chan->name, fr, ">>");
3008 CHECK_BLOCKING(chan);
3009 switch (fr->frametype) {
3010 case AST_FRAME_CONTROL:
3011 res = (chan->tech->indicate == NULL) ? 0 :
3012 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
3014 case AST_FRAME_DTMF_BEGIN:
3015 if (chan->audiohooks) {
3016 struct ast_frame *old_frame = fr;
3017 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3018 if (old_frame != fr)
3021 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
3022 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3023 ast_channel_unlock(chan);
3024 res = ast_senddigit_begin(chan, fr->subclass);
3025 ast_channel_lock(chan);
3026 CHECK_BLOCKING(chan);
3028 case AST_FRAME_DTMF_END:
3029 if (chan->audiohooks) {
3030 struct ast_frame *old_frame = fr;
3031 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3032 if (old_frame != fr)
3035 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
3036 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3037 ast_channel_unlock(chan);
3038 res = ast_senddigit_end(chan, fr->subclass, fr->len);
3039 ast_channel_lock(chan);
3040 CHECK_BLOCKING(chan);
3042 case AST_FRAME_TEXT:
3043 if (fr->subclass == AST_FORMAT_T140) {
3044 res = (chan->tech->write_text == NULL) ? 0 :
3045 chan->tech->write_text(chan, fr);
3047 res = (chan->tech->send_text == NULL) ? 0 :
3048 chan->tech->send_text(chan, (char *) fr->data);
3051 case AST_FRAME_HTML:
3052 res = (chan->tech->send_html == NULL) ? 0 :
3053 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
3055 case AST_FRAME_VIDEO:
3056 /* XXX Handle translation of video codecs one day XXX */
3057 res = (chan->tech->write_video == NULL) ? 0 :
3058 chan->tech->write_video(chan, fr);
3060 case AST_FRAME_MODEM:
3061 res = (chan->tech->write == NULL) ? 0 :
3062 chan->tech->write(chan, fr);
3064 case AST_FRAME_VOICE:
3065 if (chan->tech->write == NULL)
3066 break; /*! \todo XXX should return 0 maybe ? */
3068 /* If audiohooks are present, write the frame out */
3069 if (chan->audiohooks) {
3070 struct ast_frame *old_frame = fr;
3071 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3072 if (old_frame != fr)
3076 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
3077 if (fr->subclass == chan->rawwriteformat)
3080 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
3087 /* If Monitor is running on this channel, then we have to write frames out there too */
3088 if (chan->monitor && chan->monitor->write_stream) {
3089 /* XXX must explain this code */
3090 #ifndef MONITOR_CONSTANT_DELAY
3091 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
3093 jump = chan->insmpl - chan->outsmpl;
3094 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
3095 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3096 chan->outsmpl += jump + f->samples;
3098 chan->outsmpl += f->samples;
3100 int jump = chan->insmpl - chan->outsmpl;
3101 if (jump - MONITOR_DELAY >= 0) {
3102 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
3103 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3104 chan->outsmpl += jump;
3106 chan->outsmpl += f->samples;
3108 if (chan->monitor->state == AST_MONITOR_RUNNING) {
3109 if (ast_writestream(chan->monitor->write_stream, f) < 0)
3110 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
3115 res = chan->tech->write(chan,f);
3119 case AST_FRAME_NULL:
3125 /* At this point, fr is the incoming frame and f is NULL. Channels do
3126 * not expect to get NULL as a frame pointer and will segfault. Hence,
3127 * we output the original frame passed in. */
3128 res = chan->tech->write(chan, fr);
3136 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3137 /* Consider a write failure to force a soft hangup */
3139 chan->_softhangup |= AST_SOFTHANGUP_DEV;
3141 chan->fout = FRAMECOUNT_INC(chan->fout);
3144 ast_channel_unlock(chan);
3148 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
3149 struct ast_trans_pvt **trans, const int direction)
3154 /* Make sure we only consider audio */
3155 fmt &= AST_FORMAT_AUDIO_MASK;
3157 native = chan->nativeformats;
3159 if (!fmt || !native) /* No audio requested */
3160 return 0; /* Let's try a call without any sounds (video, text) */
3162 /* Find a translation path from the native format to one of the desired formats */
3165 res = ast_translator_best_choice(&fmt, &native);
3168 res = ast_translator_best_choice(&native, &fmt);
3171 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
3172 ast_getformatname(native), ast_getformatname(fmt));
3176 /* Now we have a good choice for both. */
3177 ast_channel_lock(chan);
3179 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
3180 /* the channel is already in these formats, so nothing to do */
3181 ast_channel_unlock(chan);
3185 *rawformat = native;
3186 /* User perspective is fmt */
3188 /* Free any read translation we have right now */
3190 ast_translator_free_path(*trans);
3191 /* Build a translation path from the raw format to the desired format */
3194 *trans = ast_translator_build_path(*format, *rawformat);
3197 *trans = ast_translator_build_path(*rawformat, *format);
3198 ast_channel_unlock(chan);
3199 ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
3200 direction ? "write" : "read", ast_getformatname(fmt));
3204 int ast_set_read_format(struct ast_channel *chan, int fmt)
3206 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
3207 &chan->readtrans, 0);
3210 int ast_set_write_format(struct ast_channel *chan, int fmt)
3212 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
3213 &chan->writetrans, 1);
3216 const char *ast_channel_reason2str(int reason)
3218 switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
3221 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
3222 case AST_CONTROL_HANGUP:
3224 case AST_CONTROL_RING:
3225 return "Local Ring";
3226 case AST_CONTROL_RINGING:
3227 return "Remote end Ringing";
3228 case AST_CONTROL_ANSWER:
3229 return "Remote end has Answered";
3230 case AST_CONTROL_BUSY:
3231 return "Remote end is Busy";
3232 case AST_CONTROL_CONGESTION:
3233 return "Congestion (circuits busy)";
3235 return "Unknown Reason!!";
3239 struct ast_channel *__ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, struct outgoing_helper *oh)
3243 struct ast_channel *chan;
3245 int last_subclass = 0;
3250 outstate = &dummy_outstate; /* make outstate always a valid pointer */
3252 chan = ast_request(type, format, data, &cause);
3254 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
3255 /* compute error and return */
3256 if (cause == AST_CAUSE_BUSY)
3257 *outstate = AST_CONTROL_BUSY;
3258 else if (cause == AST_CAUSE_CONGESTION)
3259 *outstate = AST_CONTROL_CONGESTION;
3265 ast_set_variables(chan, oh->vars);
3266 /* XXX why is this necessary, for the parent_channel perhaps ? */
3267 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
3268 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
3269 if (oh->parent_channel) {
3270 ast_channel_inherit_variables(oh->parent_channel, chan);
3271 ast_channel_datastore_inherit(oh->parent_channel, chan);
3274 ast_cdr_setaccount(chan, oh->account);
3276 ast_set_callerid(chan, cid_num, cid_name, cid_num);
3280 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
3281 to keep from throwing off the basic order of the universe,
3282 we will try to keep this cdr from getting posted. */
3283 chan->cdr = ast_cdr_alloc();
3284 ast_cdr_init(chan->cdr, chan);
3285 ast_cdr_start(chan->cdr);
3287 if (ast_call(chan, data, 0)) { /* ast_call failed... */
3288 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
3290 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
3291 while (timeout && chan->_state != AST_STATE_UP) {
3292 struct ast_frame *f;
3293 res = ast_waitfor(chan, timeout);
3294 if (res <= 0) /* error, timeout, or done */
3300 *outstate = AST_CONTROL_HANGUP;
3304 if (f->frametype == AST_FRAME_CONTROL) {
3305 switch (f->subclass) {
3306 case AST_CONTROL_RINGING: /* record but keep going */
3307 *outstate = f->subclass;
3310 case AST_CONTROL_BUSY:
3311 case AST_CONTROL_CONGESTION:
3312 case AST_CONTROL_ANSWER:
3313 *outstate = f->subclass;
3314 timeout = 0; /* trick to force exit from the while() */
3318 case AST_CONTROL_PROGRESS:
3319 case AST_CONTROL_PROCEEDING:
3320 case AST_CONTROL_HOLD:
3321 case AST_CONTROL_UNHOLD:
3322 case AST_CONTROL_VIDUPDATE:
3323 case AST_CONTROL_SRCUPDATE:
3324 case -1: /* Ignore -- just stopping indications */
3328 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
3330 last_subclass = f->subclass;
3338 if (!ast_strlen_zero(oh->context))
3339 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
3340 if (!ast_strlen_zero(oh->exten))
3341 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
3343 chan->priority = oh->priority;
3345 if (chan->_state == AST_STATE_UP)
3346 *outstate = AST_CONTROL_ANSWER;
3349 if ( AST_CONTROL_RINGING == last_subclass )
3350 chan->hangupcause = AST_CAUSE_NO_ANSWER;
3351 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
3352 ast_cdr_init(chan->cdr, chan);
3355 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
3356 ast_cdr_setapp(chan->cdr,"Dial",tmp);
3357 ast_cdr_update(chan);
3358 ast_cdr_start(chan->cdr);
3359 ast_cdr_end(chan->cdr);
3360 /* If the cause wasn't handled properly */
3361 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
3362 ast_cdr_failed(chan->cdr);
3370 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
3372 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
3375 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
3377 struct chanlist *chan;
3378 struct ast_channel *c;
3383 int videoformat = format & AST_FORMAT_VIDEO_MASK;
3384 int textformat = format & AST_FORMAT_TEXT_MASK;
3388 *cause = AST_CAUSE_NOTDEFINED;
3390 if (AST_RWLIST_RDLOCK(&channels)) {
3391 ast_log(LOG_WARNING, "Unable to lock channel list\n");
3395 AST_LIST_TRAVERSE(&backends, chan, list) {
3396 if (strcasecmp(type, chan->tech->type))
3399 capabilities = chan->tech->capabilities;
3400 fmt = format & AST_FORMAT_AUDIO_MASK;
3402 /* We have audio - is it possible to connect the various calls to each other?
3403 (Avoid this check for calls without audio, like text+video calls)
3405 res = ast_translator_best_choice(&fmt, &capabilities);
3407 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native 0x%x) to 0x%x\n", type, chan->tech->capabilities, format);
3408 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3409 AST_RWLIST_UNLOCK(&channels);
3413 AST_RWLIST_UNLOCK(&channels);
3414 if (!chan->tech->requester)
3417 if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, data, cause)))
3420 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3424 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
3425 *cause = AST_CAUSE_NOSUCHDRIVER;
3426 AST_RWLIST_UNLOCK(&channels);
3431 int ast_call(struct ast_channel *chan, char *addr, int timeout)
3433 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3434 If the remote end does not answer within the timeout, then do NOT hang up, but
3437 /* Stop if we're a zombie or need a soft hangup */
3438 ast_channel_lock(chan);
3439 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3440 if (chan->tech->call)
3441 res = chan->tech->call(chan, addr, timeout);
3442 ast_set_flag(chan, AST_FLAG_OUTGOING);
3444 ast_channel_unlock(chan);
3449 \brief Transfer a call to dest, if the channel supports transfer
3453 \arg the manager interface
3455 int ast_transfer(struct ast_channel *chan, char *dest)
3459 /* Stop if we're a zombie or need a soft hangup */
3460 ast_channel_lock(chan);
3461 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3462 if (chan->tech->transfer) {
3463 res = chan->tech->transfer(chan, dest);
3469 ast_channel_unlock(chan);
3473 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3475 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3478 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3480 int pos = 0; /* index in the buffer where we accumulate digits */
3483 /* Stop if we're a zombie or need a soft hangup */
3484 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3491 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3495 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3497 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3509 if (!strchr(enders, d))
3511 if (strchr(enders, d) || (pos >= len)) {
3521 int ast_channel_supports_html(struct ast_channel *chan)
3523 return (chan->tech->send_html) ? 1 : 0;
3526 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3528 if (chan->tech->send_html)
3529 return chan->tech->send_html(chan, subclass, data, datalen);
3533 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3535 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3538 /*! \brief Set up translation from one channel to another */
3539 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
3544 if (from->readformat == to->writeformat && from->writeformat == to->readformat) {
3545 /* Already compatible! Moving on ... */
3549 /* Set up translation from the 'from' channel to the 'to' channel */