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$")
40 #include "asterisk/zapata.h"
42 #include "asterisk/pbx.h"
43 #include "asterisk/frame.h"
44 #include "asterisk/sched.h"
45 #include "asterisk/options.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/musiconhold.h"
48 #include "asterisk/logger.h"
49 #include "asterisk/say.h"
50 #include "asterisk/file.h"
51 #include "asterisk/cli.h"
52 #include "asterisk/translate.h"
53 #include "asterisk/manager.h"
54 #include "asterisk/chanvars.h"
55 #include "asterisk/linkedlists.h"
56 #include "asterisk/indications.h"
57 #include "asterisk/monitor.h"
58 #include "asterisk/causes.h"
59 #include "asterisk/callerid.h"
60 #include "asterisk/utils.h"
61 #include "asterisk/lock.h"
62 #include "asterisk/app.h"
63 #include "asterisk/transcap.h"
64 #include "asterisk/devicestate.h"
65 #include "asterisk/sha1.h"
66 #include "asterisk/threadstorage.h"
67 #include "asterisk/slinfactory.h"
68 #include "asterisk/audiohook.h"
71 #include <sys/epoll.h>
74 struct ast_epoll_data {
75 struct ast_channel *chan;
79 /* uncomment if you have problems with 'monitoring' synchronized files */
81 #define MONITOR_CONSTANT_DELAY
82 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
85 /*! \brief Prevent new channel allocation if shutting down. */
86 static int shutting_down;
90 unsigned long global_fin, global_fout;
92 AST_THREADSTORAGE(state2str_threadbuf);
93 #define STATE2STR_BUFSIZE 32
95 /*! Default amount of time to use when emulating a digit as a begin and end
97 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
99 /*! Minimum allowed digit length - 80ms */
100 #define AST_MIN_DTMF_DURATION 80
102 /*! Minimum amount of time between the end of the last digit and the beginning
103 * of a new one - 45ms */
104 #define AST_MIN_DTMF_GAP 45
106 /*! \brief List of channel drivers */
108 const struct ast_channel_tech *tech;
109 AST_LIST_ENTRY(chanlist) list;
112 /*! \brief the list of registered channel types */
113 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
115 /*! \brief the list of channels we have. Note that the lock for this list is used for
116 both the channels list and the backends list. */
117 static AST_RWLIST_HEAD_STATIC(channels, ast_channel);
119 /*! \brief map AST_CAUSE's to readable string representations
123 const struct ast_cause {
128 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
129 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
130 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
131 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
132 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
133 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
134 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
135 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
136 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
137 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
138 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
139 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
140 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
141 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
142 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
143 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
144 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
145 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
146 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
147 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
148 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
149 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
150 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
151 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
152 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
153 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
154 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
155 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
156 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
157 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
158 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
159 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
160 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
161 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
162 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
163 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
164 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
165 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
166 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
167 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
168 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
169 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
170 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
171 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
174 struct ast_variable *ast_channeltype_list(void)
177 struct ast_variable *var=NULL, *prev = NULL;
178 AST_LIST_TRAVERSE(&backends, cl, list) {
180 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
183 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
190 /*! \brief Show channel types - CLI command */
191 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
193 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
199 e->command = "core show channeltypes";
201 "Usage: core show channeltypes\n"
202 " Lists available channel types registered in your\n"
203 " Asterisk server.\n";
210 return CLI_SHOWUSAGE;
212 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
213 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
214 if (AST_RWLIST_RDLOCK(&channels)) {
215 ast_log(LOG_WARNING, "Unable to lock channel list\n");
218 AST_LIST_TRAVERSE(&backends, cl, list) {
219 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
220 (cl->tech->devicestate) ? "yes" : "no",
221 (cl->tech->indicate) ? "yes" : "no",
222 (cl->tech->transfer) ? "yes" : "no");
225 AST_RWLIST_UNLOCK(&channels);
226 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
232 static char *complete_channeltypes(struct ast_cli_args *a)
242 wordlen = strlen(a->word);
244 AST_LIST_TRAVERSE(&backends, cl, list) {
245 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
246 ret = ast_strdup(cl->tech->type);
254 /*! \brief Show details about a channel driver - CLI command */
255 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
257 struct chanlist *cl = NULL;
261 e->command = "core show channeltype";
263 "Usage: core show channeltype <name>\n"
264 " Show details about the specified channel type, <name>.\n";
267 return complete_channeltypes(a);
271 return CLI_SHOWUSAGE;
273 if (AST_RWLIST_RDLOCK(&channels)) {
274 ast_log(LOG_WARNING, "Unable to lock channel list\n");
278 AST_LIST_TRAVERSE(&backends, cl, list) {
279 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
285 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
286 AST_RWLIST_UNLOCK(&channels);
291 "-- Info about channel driver: %s --\n"
292 " Device State: %s\n"
295 " Capabilities: %d\n"
299 " Image Support: %s\n"
300 " Text Support: %s\n",
302 (cl->tech->devicestate) ? "yes" : "no",
303 (cl->tech->indicate) ? "yes" : "no",
304 (cl->tech->transfer) ? "yes" : "no",
305 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
306 (cl->tech->send_digit_begin) ? "yes" : "no",
307 (cl->tech->send_digit_end) ? "yes" : "no",
308 (cl->tech->send_html) ? "yes" : "no",
309 (cl->tech->send_image) ? "yes" : "no",
310 (cl->tech->send_text) ? "yes" : "no"
314 AST_RWLIST_UNLOCK(&channels);
318 static struct ast_cli_entry cli_channel[] = {
319 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
320 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
323 /*! \brief Checks to see if a channel is needing hang up */
324 int ast_check_hangup(struct ast_channel *chan)
326 if (chan->_softhangup) /* yes if soft hangup flag set */
328 if (!chan->tech_pvt) /* yes if no technology private data */
330 if (!chan->whentohangup) /* no if no hangup scheduled */
332 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
334 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
338 static int ast_check_hangup_locked(struct ast_channel *chan)
341 ast_channel_lock(chan);
342 res = ast_check_hangup(chan);
343 ast_channel_unlock(chan);
347 /*! \brief Initiate system shutdown */
348 void ast_begin_shutdown(int hangup)
350 struct ast_channel *c;
353 AST_RWLIST_RDLOCK(&channels);
354 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
355 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
356 AST_RWLIST_UNLOCK(&channels);
360 /*! \brief returns number of active/allocated channels */
361 int ast_active_channels(void)
363 struct ast_channel *c;
365 AST_RWLIST_RDLOCK(&channels);
366 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
368 AST_RWLIST_UNLOCK(&channels);
372 /*! \brief Cancel a shutdown in progress */
373 void ast_cancel_shutdown(void)
378 /*! \brief Returns non-zero if Asterisk is being shut down */
379 int ast_shutting_down(void)
381 return shutting_down;
384 /*! \brief Set when to hangup channel */
385 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
387 chan->whentohangup = offset ? time(NULL) + offset : 0;
388 ast_queue_frame(chan, &ast_null_frame);
392 /*! \brief Compare a offset with when to hangup channel */
393 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
397 if (!chan->whentohangup)
398 return (offset == 0) ? 0 : -1;
400 if (!offset) /* XXX why is this special? */
403 whentohangup = offset + time(NULL);
405 if (chan->whentohangup < whentohangup)
407 else if (chan->whentohangup == whentohangup)
413 /*! \brief Register a new telephony channel in Asterisk */
414 int ast_channel_register(const struct ast_channel_tech *tech)
416 struct chanlist *chan;
418 AST_RWLIST_WRLOCK(&channels);
420 AST_LIST_TRAVERSE(&backends, chan, list) {
421 if (!strcasecmp(tech->type, chan->tech->type)) {
422 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
423 AST_RWLIST_UNLOCK(&channels);
428 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
429 AST_RWLIST_UNLOCK(&channels);
433 AST_LIST_INSERT_HEAD(&backends, chan, list);
435 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
437 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
439 AST_RWLIST_UNLOCK(&channels);
443 /*! \brief Unregister channel driver */
444 void ast_channel_unregister(const struct ast_channel_tech *tech)
446 struct chanlist *chan;
448 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
450 AST_RWLIST_WRLOCK(&channels);
452 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
453 if (chan->tech == tech) {
454 AST_LIST_REMOVE_CURRENT(list);
456 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
460 AST_LIST_TRAVERSE_SAFE_END;
462 AST_RWLIST_UNLOCK(&channels);
465 /*! \brief Get handle to channel driver based on name */
466 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
468 struct chanlist *chanls;
469 const struct ast_channel_tech *ret = NULL;
471 if (AST_RWLIST_RDLOCK(&channels)) {
472 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
476 AST_LIST_TRAVERSE(&backends, chanls, list) {
477 if (!strcasecmp(name, chanls->tech->type)) {
483 AST_RWLIST_UNLOCK(&channels);
488 /*! \brief Gives the string form of a given hangup cause */
489 const char *ast_cause2str(int cause)
493 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
494 if (causes[x].cause == cause)
495 return causes[x].desc;
501 /*! \brief Convert a symbolic hangup cause to number */
502 int ast_str2cause(const char *name)
506 for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
507 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
508 return causes[x].cause;
513 /*! \brief Gives the string form of a given channel state.
514 \note This function is not reentrant.
516 const char *ast_state2str(enum ast_channel_state state)
523 case AST_STATE_RESERVED:
525 case AST_STATE_OFFHOOK:
527 case AST_STATE_DIALING:
531 case AST_STATE_RINGING:
537 case AST_STATE_DIALING_OFFHOOK:
538 return "Dialing Offhook";
539 case AST_STATE_PRERING:
542 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
544 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
549 /*! \brief Gives the string form of a given transfer capability */
550 char *ast_transfercapability2str(int transfercapability)
552 switch (transfercapability) {
553 case AST_TRANS_CAP_SPEECH:
555 case AST_TRANS_CAP_DIGITAL:
557 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
558 return "RESTRICTED_DIGITAL";
559 case AST_TRANS_CAP_3_1K_AUDIO:
561 case AST_TRANS_CAP_DIGITAL_W_TONES:
562 return "DIGITAL_W_TONES";
563 case AST_TRANS_CAP_VIDEO:
570 /*! \brief Pick the best audio codec */
571 int ast_best_codec(int fmts)
573 /* This just our opinion, expressed in code. We are asked to choose
574 the best codec to use, given no information */
576 static const int prefs[] =
578 /*! Okay, ulaw is used by all telephony equipment, so start with it */
580 /*! Unless of course, you're a silly European, so then prefer ALAW */
582 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
584 /*! Okay, well, signed linear is easy to translate into other stuff */
586 /*! G.726 is standard ADPCM, in RFC3551 packing order */
588 /*! G.726 is standard ADPCM, in AAL2 packing order */
589 AST_FORMAT_G726_AAL2,
590 /*! ADPCM has great sound quality and is still pretty easy to translate */
592 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
593 translate and sounds pretty good */
595 /*! iLBC is not too bad */
597 /*! Speex is free, but computationally more expensive than GSM */
599 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
602 /*! G.729a is faster than 723 and slightly less expensive */
604 /*! Down to G.723.1 which is proprietary but at least designed for voice */
608 /* Strip out video */
609 fmts &= AST_FORMAT_AUDIO_MASK;
611 /* Find the first preferred codec in the format given */
612 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
615 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
619 static const struct ast_channel_tech null_tech = {
621 .description = "Null channel (should not see this)",
624 /*! \brief Create a new channel structure */
625 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, ...)
627 struct ast_channel *tmp;
630 struct varshead *headp;
633 /* If shutting down, don't allocate any new channels */
635 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
639 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
642 if (!(tmp->sched = sched_context_create())) {
643 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
648 if ((ast_string_field_init(tmp, 128))) {
649 sched_context_destroy(tmp->sched);
655 tmp->epfd = epoll_create(25);
658 for (x = 0; x < AST_MAX_FDS; x++) {
661 tmp->epfd_data[x] = NULL;
666 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
667 if (tmp->timingfd > -1) {
668 /* Check if timing interface supports new
671 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
679 if (pipe(tmp->alertpipe)) {
680 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
681 ast_string_field_free_memory(tmp);
685 flags = fcntl(tmp->alertpipe[0], F_GETFL);
686 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
687 flags = fcntl(tmp->alertpipe[1], F_GETFL);
688 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
690 } else /* Make sure we've got it done right if they don't */
691 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
693 /* Always watch the alertpipe */
694 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
695 /* And timing pipe */
696 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
697 ast_string_field_set(tmp, name, "**Unknown**");
704 tmp->fin = global_fin;
705 tmp->fout = global_fout;
707 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
708 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
709 ast_atomic_fetchadd_int(&uniqueint, 1));
711 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
712 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
715 tmp->cid.cid_name = ast_strdup(cid_name);
716 tmp->cid.cid_num = ast_strdup(cid_num);
718 if (!ast_strlen_zero(name_fmt)) {
719 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
720 * And they all use slightly different formats for their name string.
721 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
722 * This means, that the stringfields must have a routine that takes the va_lists directly, and
723 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
724 * This new function was written so this can be accomplished.
726 va_start(ap1, name_fmt);
727 va_start(ap2, name_fmt);
728 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
732 /* and now, since the channel structure is built, and has its name, let's call the
733 * manager event generator with this Newchannel event. This is the proper and correct
734 * place to make this call, but you sure do have to pass a lot of data into this func
737 manager_event(EVENT_FLAG_CALL, "Newchannel",
740 "CallerIDNum: %s\r\n"
741 "CallerIDName: %s\r\n"
743 tmp->name, ast_state2str(state),
744 S_OR(cid_num, "<unknown>"),
745 S_OR(cid_name, "<unknown>"),
749 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
751 /* These 4 variables need to be set up for the cdr_init() to work right */
753 tmp->amaflags = amaflag;
755 tmp->amaflags = ast_default_amaflags;
757 if (!ast_strlen_zero(acctcode))
758 ast_string_field_set(tmp, accountcode, acctcode);
760 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
762 if (!ast_strlen_zero(context))
763 ast_copy_string(tmp->context, context, sizeof(tmp->context));
765 strcpy(tmp->context, "default");
767 if (!ast_strlen_zero(exten))
768 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
770 strcpy(tmp->exten, "s");
774 tmp->cdr = ast_cdr_alloc();
775 ast_cdr_init(tmp->cdr, tmp);
776 ast_cdr_start(tmp->cdr);
778 headp = &tmp->varshead;
779 AST_LIST_HEAD_INIT_NOLOCK(headp);
781 ast_mutex_init(&tmp->lock);
783 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
785 ast_string_field_set(tmp, language, defaultlanguage);
787 tmp->tech = &null_tech;
789 AST_RWLIST_WRLOCK(&channels);
790 AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
791 AST_RWLIST_UNLOCK(&channels);
796 /*! \brief Queue an outgoing media frame */
797 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
800 struct ast_frame *cur;
804 /* Build us a copy and free the original one */
805 if (!(f = ast_frdup(fin))) {
806 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
809 ast_channel_lock(chan);
811 /* See if the last frame on the queue is a hangup, if so don't queue anything */
812 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
814 ast_channel_unlock(chan);
818 /* Count how many frames exist on the queue */
819 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
823 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
824 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
825 if (fin->frametype != AST_FRAME_VOICE) {
826 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
829 ast_debug(1, "Dropping voice to exceptionally long queue on %s\n", chan->name);
831 ast_channel_unlock(chan);
835 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
836 if (chan->alertpipe[1] > -1) {
837 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
838 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
839 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
841 } else if (chan->timingfd > -1) {
842 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
844 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
845 pthread_kill(chan->blocker, SIGURG);
847 ast_channel_unlock(chan);
851 /*! \brief Queue a hangup frame for channel */
852 int ast_queue_hangup(struct ast_channel *chan)
854 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
855 /* Yeah, let's not change a lock-critical value without locking */
856 if (!ast_channel_trylock(chan)) {
857 chan->_softhangup |= AST_SOFTHANGUP_DEV;
858 ast_channel_unlock(chan);
860 return ast_queue_frame(chan, &f);
863 /*! \brief Queue a control frame */
864 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
866 struct ast_frame f = { AST_FRAME_CONTROL, };
868 f.subclass = control;
870 return ast_queue_frame(chan, &f);
873 /*! \brief Queue a control frame with payload */
874 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
875 const void *data, size_t datalen)
877 struct ast_frame f = { AST_FRAME_CONTROL, };
879 f.subclass = control;
880 f.data = (void *) data;
883 return ast_queue_frame(chan, &f);
886 /*! \brief Set defer DTMF flag on channel */
887 int ast_channel_defer_dtmf(struct ast_channel *chan)
892 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
893 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
898 /*! \brief Unset defer DTMF flag on channel */
899 void ast_channel_undefer_dtmf(struct ast_channel *chan)
902 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
906 * \brief Helper function to find channels.
908 * It supports these modes:
910 * prev != NULL : get channel next in list after prev
911 * name != NULL : get channel with matching name
912 * name != NULL && namelen != 0 : get channel whose name starts with prefix
913 * exten != NULL : get channel whose exten or macroexten matches
914 * context != NULL && exten != NULL : get channel whose context or macrocontext
916 * It returns with the channel's lock held. If getting the individual lock fails,
917 * unlock and retry quickly up to 10 times, then give up.
919 * \note XXX Note that this code has cost O(N) because of the need to verify
920 * that the object is still on the global list.
922 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
923 * can only be done with the lock held or someone could delete the
924 * object while we work on it. This causes some ugliness in the code.
925 * Note that removing the first ast_log() may be harmful, as it would
926 * shorten the retry period and possibly cause failures.
927 * We should definitely go for a better scheme that is deadlock-free.
929 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
930 const char *name, const int namelen,
931 const char *context, const char *exten)
933 const char *msg = prev ? "deadlock" : "initial deadlock";
935 struct ast_channel *c;
936 const struct ast_channel *_prev = prev;
938 for (retries = 0; retries < 10; retries++) {
940 AST_RWLIST_RDLOCK(&channels);
941 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
943 if (prev) { /* look for next item */
944 if (c != prev) /* not this one */
946 /* found, prepare to return c->next */
947 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
948 /* If prev was the last item on the channel list, then we just
949 * want to return NULL, instead of trying to deref NULL in the
953 /* We want prev to be NULL in case we end up doing more searching through
954 * the channel list to find the channel (ie: name searching). If we didn't
955 * set this to NULL the logic would just blow up
956 * XXX Need a better explanation for this ...
959 if (name) { /* want match by name */
960 if ((!namelen && strcasecmp(c->name, name)) ||
961 (namelen && strncasecmp(c->name, name, namelen)))
962 continue; /* name match failed */
964 if (context && strcasecmp(c->context, context) &&
965 strcasecmp(c->macrocontext, context))
966 continue; /* context match failed */
967 if (strcasecmp(c->exten, exten) &&
968 strcasecmp(c->macroexten, exten))
969 continue; /* exten match failed */
971 /* if we get here, c points to the desired record */
974 /* exit if chan not found or mutex acquired successfully */
975 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
976 done = c == NULL || ast_channel_trylock(c) == 0;
978 ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
980 /* We are about to fail due to a deadlock, so report this
981 * while we still have the list lock.
983 ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
984 /* As we have deadlocked, we will skip this channel and
985 * see if there is another match.
986 * NOTE: No point doing this for a full-name match,
987 * as there can be no more matches.
989 if (!(name && !namelen)) {
995 AST_RWLIST_UNLOCK(&channels);
998 /* If we reach this point we basically tried to lock a channel and failed. Instead of
999 * starting from the beginning of the list we can restore our saved pointer to the previous
1000 * channel and start from there.
1003 usleep(1); /* give other threads a chance before retrying */
1009 /*! \brief Browse channels in use */
1010 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1012 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1015 /*! \brief Get channel by name and lock it */
1016 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1018 return channel_find_locked(NULL, name, 0, NULL, NULL);
1021 /*! \brief Get channel by name prefix and lock it */
1022 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1024 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1027 /*! \brief Get next channel by name prefix and lock it */
1028 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1031 return channel_find_locked(chan, name, namelen, NULL, NULL);
1034 /*! \brief Get channel by exten (and optionally context) and lock it */
1035 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1037 return channel_find_locked(NULL, NULL, 0, context, exten);
1040 /*! \brief Get next channel by exten (and optionally context) and lock it */
1041 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1042 const char *context)
1044 return channel_find_locked(chan, NULL, 0, context, exten);
1047 /*! \brief Wait, look for hangups and condition arg */
1048 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1050 struct ast_frame *f;
1053 if (cond && ((*cond)(data) == 0))
1055 ms = ast_waitfor(chan, ms);
1068 /*! \brief Wait, look for hangups */
1069 int ast_safe_sleep(struct ast_channel *chan, int ms)
1071 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1074 static void free_cid(struct ast_callerid *cid)
1077 ast_free(cid->cid_dnid);
1079 ast_free(cid->cid_num);
1081 ast_free(cid->cid_name);
1083 ast_free(cid->cid_ani);
1085 ast_free(cid->cid_rdnis);
1086 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1089 /*! \brief Free a channel structure */
1090 void ast_channel_free(struct ast_channel *chan)
1096 struct ast_var_t *vardata;
1097 struct ast_frame *f;
1098 struct varshead *headp;
1099 struct ast_datastore *datastore = NULL;
1100 char name[AST_CHANNEL_NAME];
1102 headp=&chan->varshead;
1104 AST_RWLIST_WRLOCK(&channels);
1105 if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1106 AST_RWLIST_UNLOCK(&channels);
1107 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1109 /* Lock and unlock the channel just to be sure nobody
1110 has it locked still */
1111 ast_channel_lock(chan);
1112 ast_channel_unlock(chan);
1113 if (chan->tech_pvt) {
1114 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1115 ast_free(chan->tech_pvt);
1119 sched_context_destroy(chan->sched);
1121 ast_copy_string(name, chan->name, sizeof(name));
1123 /* Stop monitoring */
1125 chan->monitor->stop( chan, 0 );
1127 /* If there is native format music-on-hold state, free it */
1128 if (chan->music_state)
1129 ast_moh_cleanup(chan);
1131 /* Free translators */
1132 if (chan->readtrans)
1133 ast_translator_free_path(chan->readtrans);
1134 if (chan->writetrans)
1135 ast_translator_free_path(chan->writetrans);
1137 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1138 free_cid(&chan->cid);
1139 ast_mutex_destroy(&chan->lock);
1140 /* Close pipes if appropriate */
1141 if ((fd = chan->alertpipe[0]) > -1)
1143 if ((fd = chan->alertpipe[1]) > -1)
1145 if ((fd = chan->timingfd) > -1)
1148 for (i = 0; i < AST_MAX_FDS; i++) {
1149 if (chan->epfd_data[i])
1150 free(chan->epfd_data[i]);
1154 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1157 /* Get rid of each of the data stores on the channel */
1158 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1159 /* Free the data store */
1160 ast_channel_datastore_free(datastore);
1161 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1163 /* loop over the variables list, freeing all data and deleting list items */
1164 /* no need to lock the list, as the channel is already locked */
1166 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1167 ast_var_delete(vardata);
1169 ast_app_group_discard(chan);
1171 /* Destroy the jitterbuffer */
1172 ast_jb_destroy(chan);
1174 ast_string_field_free_memory(chan);
1176 AST_RWLIST_UNLOCK(&channels);
1178 ast_device_state_changed_literal(name);
1181 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1183 struct ast_datastore *datastore = NULL;
1185 /* Make sure we at least have type so we can identify this */
1190 /* Allocate memory for datastore and clear it */
1191 datastore = ast_calloc(1, sizeof(*datastore));
1196 datastore->info = info;
1198 datastore->uid = ast_strdup(uid);
1203 int ast_channel_datastore_free(struct ast_datastore *datastore)
1207 /* Using the destroy function (if present) destroy the data */
1208 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1209 datastore->info->destroy(datastore->data);
1210 datastore->data = NULL;
1213 /* Free allocated UID memory */
1214 if (datastore->uid != NULL) {
1215 ast_free((void *) datastore->uid);
1216 datastore->uid = NULL;
1219 /* Finally free memory used by ourselves */
1220 ast_free(datastore);
1225 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1227 struct ast_datastore *datastore = NULL, *datastore2;
1229 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1230 if (datastore->inheritance > 0) {
1231 datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1233 datastore2->data = datastore->info->duplicate(datastore->data);
1234 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1235 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1242 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1246 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1251 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1253 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1256 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1258 struct ast_datastore *datastore = NULL;
1263 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1264 if (datastore->info == info) {
1265 if (uid != NULL && datastore->uid != NULL) {
1266 if (!strcasecmp(uid, datastore->uid)) {
1267 /* Matched by type AND uid */
1271 /* Matched by type at least */
1276 AST_LIST_TRAVERSE_SAFE_END
1281 /*! Set the file descriptor on the channel */
1282 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
1285 struct epoll_event ev;
1286 struct ast_epoll_data *aed = NULL;
1288 if (chan->fds[which] > -1) {
1289 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
1290 aed = chan->epfd_data[which];
1293 /* If this new fd is valid, add it to the epoll */
1295 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
1298 chan->epfd_data[which] = aed;
1302 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1304 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
1306 /* We don't have to keep around this epoll data structure now */
1308 chan->epfd_data[which] = NULL;
1311 chan->fds[which] = fd;
1315 /*! Add a channel to an optimized waitfor */
1316 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
1319 struct epoll_event ev;
1322 if (chan0->epfd == -1)
1325 /* Iterate through the file descriptors on chan1, adding them to chan0 */
1326 for (i = 0; i < AST_MAX_FDS; i++) {
1327 if (chan1->fds[i] == -1)
1329 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1330 ev.data.ptr = chan1->epfd_data[i];
1331 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
1338 /*! Delete a channel from an optimized waitfor */
1339 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
1342 struct epoll_event ev;
1345 if (chan0->epfd == -1)
1348 for (i = 0; i < AST_MAX_FDS; i++) {
1349 if (chan1->fds[i] == -1)
1351 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
1358 /*! \brief Softly hangup a channel, don't lock */
1359 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1361 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1362 /* Inform channel driver that we need to be hung up, if it cares */
1363 chan->_softhangup |= cause;
1364 ast_queue_frame(chan, &ast_null_frame);
1365 /* Interrupt any poll call or such */
1366 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1367 pthread_kill(chan->blocker, SIGURG);
1371 /*! \brief Softly hangup a channel, lock */
1372 int ast_softhangup(struct ast_channel *chan, int cause)
1375 ast_channel_lock(chan);
1376 res = ast_softhangup_nolock(chan, cause);
1377 ast_channel_unlock(chan);
1381 static void free_translation(struct ast_channel *clone)
1383 if (clone->writetrans)
1384 ast_translator_free_path(clone->writetrans);
1385 if (clone->readtrans)
1386 ast_translator_free_path(clone->readtrans);
1387 clone->writetrans = NULL;
1388 clone->readtrans = NULL;
1389 clone->rawwriteformat = clone->nativeformats;
1390 clone->rawreadformat = clone->nativeformats;
1393 /*! \brief Hangup a channel */
1394 int ast_hangup(struct ast_channel *chan)
1397 struct ast_cdr *cdr = NULL;
1399 /* Don't actually hang up a channel that will masquerade as someone else, or
1400 if someone is going to masquerade as us */
1401 ast_channel_lock(chan);
1403 if (chan->audiohooks) {
1404 ast_audiohook_detach_list(chan->audiohooks);
1405 chan->audiohooks = NULL;
1408 ast_autoservice_stop(chan);
1411 if (ast_do_masquerade(chan))
1412 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1416 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1417 ast_channel_unlock(chan);
1420 /* If this channel is one which will be masqueraded into something,
1421 mark it as a zombie already, so we know to free it later */
1423 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1424 ast_channel_unlock(chan);
1427 free_translation(chan);
1428 /* Close audio stream */
1430 ast_closestream(chan->stream);
1431 chan->stream = NULL;
1433 /* Close video stream */
1434 if (chan->vstream) {
1435 ast_closestream(chan->vstream);
1436 chan->vstream = NULL;
1439 sched_context_destroy(chan->sched);
1443 if (chan->generatordata) /* Clear any tone stuff remaining */
1444 if (chan->generator && chan->generator->release)
1445 chan->generator->release(chan, chan->generatordata);
1446 chan->generatordata = NULL;
1447 chan->generator = NULL;
1448 if (chan->cdr) { /* End the CDR if it hasn't already */
1449 ast_cdr_end(chan->cdr);
1453 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1454 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1455 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1456 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1459 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1460 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1461 if (chan->tech->hangup)
1462 res = chan->tech->hangup(chan);
1464 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1467 ast_channel_unlock(chan);
1468 manager_event(EVENT_FLAG_CALL, "Hangup",
1471 "CallerIDNum: %s\r\n"
1472 "CallerIDName: %s\r\n"
1474 "Cause-txt: %s\r\n",
1477 S_OR(chan->cid.cid_num, "<unknown"),
1478 S_OR(chan->cid.cid_name, "<unknown"),
1480 ast_cause2str(chan->hangupcause)
1482 ast_channel_free(chan);
1485 ast_cdr_detach(cdr);
1490 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1494 ast_channel_lock(chan);
1496 /* You can't answer an outbound call */
1497 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1498 ast_channel_unlock(chan);
1502 /* Stop if we're a zombie or need a soft hangup */
1503 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1504 ast_channel_unlock(chan);
1508 switch (chan->_state) {
1509 case AST_STATE_RINGING:
1510 case AST_STATE_RING:
1511 if (chan->tech->answer)
1512 res = chan->tech->answer(chan);
1513 ast_setstate(chan, AST_STATE_UP);
1514 ast_cdr_answer(chan->cdr);
1515 ast_channel_unlock(chan);
1517 ast_safe_sleep(chan, delay);
1521 ast_cdr_answer(chan->cdr);
1527 ast_channel_unlock(chan);
1532 int ast_answer(struct ast_channel *chan)
1534 return __ast_answer(chan, 500);
1537 void ast_deactivate_generator(struct ast_channel *chan)
1539 ast_channel_lock(chan);
1540 if (chan->generatordata) {
1541 if (chan->generator && chan->generator->release)
1542 chan->generator->release(chan, chan->generatordata);
1543 chan->generatordata = NULL;
1544 chan->generator = NULL;
1545 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
1546 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1547 ast_settimeout(chan, 0, NULL, NULL);
1549 ast_channel_unlock(chan);
1552 static int generator_force(const void *data)
1554 /* Called if generator doesn't have data */
1557 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1558 struct ast_channel *chan = (struct ast_channel *)data;
1559 tmp = chan->generatordata;
1560 chan->generatordata = NULL;
1561 generate = chan->generator->generate;
1562 res = generate(chan, tmp, 0, 160);
1563 chan->generatordata = tmp;
1565 ast_debug(1, "Auto-deactivating generator\n");
1566 ast_deactivate_generator(chan);
1571 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1575 ast_channel_lock(chan);
1577 if (chan->generatordata) {
1578 if (chan->generator && chan->generator->release)
1579 chan->generator->release(chan, chan->generatordata);
1580 chan->generatordata = NULL;
1584 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1589 ast_settimeout(chan, 160, generator_force, chan);
1590 chan->generator = gen;
1593 ast_channel_unlock(chan);
1598 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1599 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1602 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1606 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1608 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
1609 int *exception, int *outfd, int *ms)
1611 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1612 int *exception, int *outfd, int *ms)
1615 struct timeval start = { 0 , 0 };
1616 struct pollfd *pfds;
1622 long whentohangup = 0, diff;
1623 struct ast_channel *winner = NULL;
1629 sz = n * AST_MAX_FDS + nfds;
1630 pfds = alloca(sizeof(*pfds) * sz);
1631 fdmap = alloca(sizeof(*fdmap) * sz);
1638 /* Perform any pending masquerades */
1639 for (x = 0; x < n; x++) {
1640 ast_channel_lock(c[x]);
1641 if (c[x]->masq && ast_do_masquerade(c[x])) {
1642 ast_log(LOG_WARNING, "Masquerade failed\n");
1644 ast_channel_unlock(c[x]);
1647 if (c[x]->whentohangup) {
1650 diff = c[x]->whentohangup - now;
1652 /* Should already be hungup */
1653 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1654 ast_channel_unlock(c[x]);
1657 if (!whentohangup || (diff < whentohangup))
1658 whentohangup = diff;
1660 ast_channel_unlock(c[x]);
1662 /* Wait full interval */
1665 rms = whentohangup * 1000; /* timeout in milliseconds */
1666 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1670 * Build the pollfd array, putting the channels' fds first,
1671 * followed by individual fds. Order is important because
1672 * individual fd's must have priority over channel fds.
1675 for (x = 0; x < n; x++) {
1676 for (y = 0; y < AST_MAX_FDS; y++) {
1677 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1678 fdmap[max].chan = x; /* channel x is linked to this pfds */
1679 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1681 CHECK_BLOCKING(c[x]);
1683 /* Add the individual fds */
1684 for (x = 0; x < nfds; x++) {
1685 fdmap[max].chan = -1;
1686 max += ast_add_fd(&pfds[max], fds[x]);
1690 start = ast_tvnow();
1692 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1697 res = poll(pfds, max, kbrms);
1700 } while (!res && (rms > 0));
1702 res = poll(pfds, max, rms);
1704 for (x = 0; x < n; x++)
1705 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1706 if (res < 0) { /* Simulate a timeout if we were interrupted */
1711 if (whentohangup) { /* if we have a timeout, check who expired */
1713 for (x = 0; x < n; x++) {
1714 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1715 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1721 if (res == 0) { /* no fd ready, reset timeout and done */
1722 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1726 * Then check if any channel or fd has a pending event.
1727 * Remember to check channels first and fds last, as they
1728 * must have priority on setting 'winner'
1730 for (x = 0; x < max; x++) {
1731 res = pfds[x].revents;
1734 if (fdmap[x].chan >= 0) { /* this is a channel */
1735 winner = c[fdmap[x].chan]; /* override previous winners */
1737 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1739 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1740 winner->fdno = fdmap[x].fdno;
1741 } else { /* this is an fd */
1743 *outfd = pfds[x].fd;
1745 *exception = (res & POLLPRI) ? -1 : 0;
1750 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1758 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
1760 struct timeval start = { 0 , 0 };
1762 struct epoll_event ev[1];
1763 long whentohangup = 0, rms = *ms;
1765 struct ast_channel *winner = NULL;
1766 struct ast_epoll_data *aed = NULL;
1768 ast_channel_lock(chan);
1770 /* See if this channel needs to be masqueraded */
1771 if (chan->masq && ast_do_masquerade(chan)) {
1772 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
1774 ast_channel_unlock(chan);
1778 /* Figure out their timeout */
1779 if (chan->whentohangup) {
1781 if ((whentohangup = chan->whentohangup - now) < 1) {
1782 /* They should already be hungup! */
1783 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1784 ast_channel_unlock(chan);
1787 /* If this value is smaller then the current one... make it priority */
1788 whentohangup *= 1000;
1789 if (rms > whentohangup)
1793 ast_channel_unlock(chan);
1795 /* Time to make this channel block... */
1796 CHECK_BLOCKING(chan);
1799 start = ast_tvnow();
1801 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
1802 res = epoll_wait(chan->epfd, ev, 1, rms);
1805 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1807 /* Simulate a timeout if we were interrupted */
1814 /* If this channel has a timeout see if it expired */
1815 if (chan->whentohangup) {
1817 if (now >= chan->whentohangup) {
1818 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1823 /* No fd ready, reset timeout and be done for now */
1829 /* See what events are pending */
1830 aed = ev[0].data.ptr;
1831 chan->fdno = aed->which;
1832 if (ev[0].events & EPOLLPRI)
1833 ast_set_flag(chan, AST_FLAG_EXCEPTION);
1835 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1838 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1846 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
1848 struct timeval start = { 0 , 0 };
1850 struct epoll_event ev[25] = { { 0, } };
1851 long whentohangup = 0, diff, rms = *ms;
1853 struct ast_channel *winner = NULL;
1855 for (i = 0; i < n; i++) {
1856 ast_channel_lock(c[i]);
1857 if (c[i]->masq && ast_do_masquerade(c[i])) {
1858 ast_log(LOG_WARNING, "Masquerade failed\n");
1860 ast_channel_unlock(c[i]);
1863 if (c[i]->whentohangup) {
1866 if ((diff = c[i]->whentohangup - now) < 1) {
1867 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1868 ast_channel_unlock(c[i]);
1871 if (!whentohangup || (diff < whentohangup))
1872 whentohangup = diff;
1874 ast_channel_unlock(c[i]);
1875 CHECK_BLOCKING(c[i]);
1880 rms = whentohangup * 1000;
1881 if (*ms >= 0 && *ms < rms)
1886 start = ast_tvnow();
1888 res = epoll_wait(c[0]->epfd, ev, 25, rms);
1890 for (i = 0; i < n; i++)
1891 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
1901 for (i = 0; i < n; i++) {
1902 if (c[i]->whentohangup && now >= c[i]->whentohangup) {
1903 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1915 for (i = 0; i < 25; i++) {
1916 struct ast_epoll_data *aed = ev[i].data.ptr;
1918 if (!ev[i].events || !aed)
1922 if (ev[i].events & EPOLLPRI)
1923 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1925 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1926 winner->fdno = aed->which;
1930 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1938 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1939 int *exception, int *outfd, int *ms)
1941 /* Clear all provided values in one place. */
1947 /* If no epoll file descriptor is available resort to classic nandfds */
1948 if (!n || nfds || c[0]->epfd == -1)
1949 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
1950 else if (!nfds && n == 1)
1951 return ast_waitfor_nandfds_simple(c[0], ms);
1953 return ast_waitfor_nandfds_complex(c, n, ms);
1957 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1959 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1962 int ast_waitfor(struct ast_channel *c, int ms)
1964 int oldms = ms; /* -1 if no timeout */
1966 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1967 if ((ms < 0) && (oldms < 0))
1972 /* XXX never to be called with ms = -1 */
1973 int ast_waitfordigit(struct ast_channel *c, int ms)
1975 return ast_waitfordigit_full(c, ms, -1, -1);
1978 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
1982 if (c->timingfd > -1) {
1987 ast_debug(1, "Scheduling timer at %d sample intervals\n", samples);
1988 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1989 c->timingfunc = func;
1990 c->timingdata = data;
1996 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1998 /* Stop if we're a zombie or need a soft hangup */
1999 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2002 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2003 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2005 /* Wait for a digit, no more than ms milliseconds total. */
2008 struct ast_channel *rchan;
2012 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2014 if (!rchan && outfd < 0 && ms) {
2015 if (errno == 0 || errno == EINTR)
2017 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2018 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2020 } else if (outfd > -1) {
2021 /* The FD we were watching has something waiting */
2022 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2023 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2027 struct ast_frame *f = ast_read(c);
2031 switch (f->frametype) {
2032 case AST_FRAME_DTMF_BEGIN:
2034 case AST_FRAME_DTMF_END:
2037 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2039 case AST_FRAME_CONTROL:
2040 switch (f->subclass) {
2041 case AST_CONTROL_HANGUP:
2043 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2045 case AST_CONTROL_RINGING:
2046 case AST_CONTROL_ANSWER:
2050 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2054 case AST_FRAME_VOICE:
2055 /* Write audio if appropriate */
2057 write(audiofd, f->data, f->datalen);
2066 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2068 return 0; /* Time is up */
2071 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2073 manager_event(EVENT_FLAG_DTMF,
2081 chan->name, chan->uniqueid, digit, direction, begin, end);
2084 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2086 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2087 void *tmp = chan->generatordata;
2090 if (chan->timingfunc) {
2091 if (option_debug > 1)
2092 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2093 ast_settimeout(chan, 0, NULL, NULL);
2096 chan->generatordata = NULL; /* reset, to let writes go through */
2097 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2098 chan->generatordata = tmp;
2100 if (option_debug > 1)
2101 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2102 ast_deactivate_generator(chan);
2105 } else if (f->frametype == AST_FRAME_CNG) {
2106 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2107 if (option_debug > 1)
2108 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2109 ast_settimeout(chan, 160, generator_force, chan);
2114 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2116 struct ast_frame *f = NULL; /* the return value */
2121 /* this function is very long so make sure there is only one return
2122 * point at the end (there are only two exceptions to this).
2124 while(ast_channel_trylock(chan)) {
2126 /*cannot goto done since the channel is not locked*/
2127 return &ast_null_frame;
2132 if (ast_do_masquerade(chan))
2133 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2135 f = &ast_null_frame;
2139 /* Stop if we're a zombie or need a soft hangup */
2140 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2141 if (chan->generator)
2142 ast_deactivate_generator(chan);
2145 prestate = chan->_state;
2147 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2148 !ast_strlen_zero(chan->dtmfq) &&
2149 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2150 /* We have DTMF that has been deferred. Return it now */
2151 chan->dtmff.subclass = chan->dtmfq[0];
2152 /* Drop first digit from the buffer */
2153 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2155 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2156 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2157 chan->dtmff.frametype = AST_FRAME_DTMF_END;
2159 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);
2160 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2161 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2162 chan->emulate_dtmf_digit = f->subclass;
2163 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2165 chan->dtmf_tv = ast_tvnow();
2169 /* Read and ignore anything on the alertpipe, but read only
2170 one sizeof(blah) per frame that we send from it */
2171 if (chan->alertpipe[0] > -1)
2172 read(chan->alertpipe[0], &blah, sizeof(blah));
2175 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2178 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2180 /* IF we can't get event, assume it's an expired as-per the old interface */
2181 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2183 blah = ZT_EVENT_TIMER_EXPIRED;
2185 if (blah == ZT_EVENT_TIMER_PING) {
2186 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2187 /* Acknowledge PONG unless we need it again */
2188 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2189 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2192 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2193 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2194 if (chan->timingfunc) {
2195 chan->timingfunc(chan->timingdata);
2198 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2199 chan->timingdata = NULL;
2201 ast_channel_unlock(chan);
2202 /* cannot 'goto done' because the channel is already unlocked */
2203 return &ast_null_frame;
2205 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2208 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2209 /* if the AST_GENERATOR_FD is set, call the generator with args
2210 * set to -1 so it can do whatever it needs to.
2212 void *tmp = chan->generatordata;
2213 chan->generatordata = NULL; /* reset to let ast_write get through */
2214 chan->generator->generate(chan, tmp, -1, -1);
2215 chan->generatordata = tmp;
2216 f = &ast_null_frame;
2220 /* Check for pending read queue */
2221 if (!AST_LIST_EMPTY(&chan->readq)) {
2222 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2223 /* Interpret hangup and return NULL */
2224 /* XXX why not the same for frames from the channel ? */
2225 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2230 chan->blocker = pthread_self();
2231 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2232 if (chan->tech->exception)
2233 f = chan->tech->exception(chan);
2235 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2236 f = &ast_null_frame;
2238 /* Clear the exception flag */
2239 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2240 } else if (chan->tech->read)
2241 f = chan->tech->read(chan);
2243 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2247 /* if the channel driver returned more than one frame, stuff the excess
2248 into the readq for the next ast_read call (note that we can safely assume
2249 that the readq is empty, because otherwise we would not have called into
2250 the channel driver and f would be only a single frame)
2252 if (AST_LIST_NEXT(f, frame_list)) {
2253 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2254 AST_LIST_NEXT(f, frame_list) = NULL;
2257 switch (f->frametype) {
2258 case AST_FRAME_CONTROL:
2259 if (f->subclass == AST_CONTROL_ANSWER) {
2260 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2261 ast_debug(1, "Ignoring answer on an inbound call!\n");
2263 f = &ast_null_frame;
2264 } else if (prestate == AST_STATE_UP) {
2265 ast_debug(1, "Dropping duplicate answer!\n");
2267 f = &ast_null_frame;
2269 /* Answer the CDR */
2270 ast_setstate(chan, AST_STATE_UP);
2271 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2272 to keep from throwing off the basic order of the universe,
2273 we will try to keep this cdr from getting posted. */
2274 chan->cdr = ast_cdr_alloc();
2275 ast_cdr_init(chan->cdr, chan);
2276 ast_cdr_start(chan->cdr);
2279 ast_cdr_answer(chan->cdr);
2283 case AST_FRAME_DTMF_END:
2284 send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2285 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2286 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2287 * However, only let emulation be forced if the other end cares about BEGIN frames */
2288 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2289 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2290 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2291 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2292 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2294 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2296 f = &ast_null_frame;
2297 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2298 if (!ast_tvzero(chan->dtmf_tv) &&
2299 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2300 /* If it hasn't been long enough, defer this digit */
2301 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2302 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2303 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2305 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2307 f = &ast_null_frame;
2309 /* There was no begin, turn this into a begin and send the end later */
2310 f->frametype = AST_FRAME_DTMF_BEGIN;
2311 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2312 chan->emulate_dtmf_digit = f->subclass;
2313 chan->dtmf_tv = ast_tvnow();
2315 if (f->len > AST_MIN_DTMF_DURATION)
2316 chan->emulate_dtmf_duration = f->len;
2318 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2320 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2321 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2323 if (chan->audiohooks) {
2324 struct ast_frame *old_frame = f;
2325 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2327 ast_frfree(old_frame);
2330 struct timeval now = ast_tvnow();
2331 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2332 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2333 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2335 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2336 } else if (!f->len) {
2337 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2338 f->len = AST_MIN_DTMF_DURATION;
2340 if (f->len < AST_MIN_DTMF_DURATION) {
2341 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);
2342 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2343 chan->emulate_dtmf_digit = f->subclass;
2344 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2346 f = &ast_null_frame;
2348 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2349 chan->dtmf_tv = now;
2351 if (chan->audiohooks) {
2352 struct ast_frame *old_frame = f;
2353 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2355 ast_frfree(old_frame);
2359 case AST_FRAME_DTMF_BEGIN:
2360 send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2361 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2362 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY) ||
2363 (!ast_tvzero(chan->dtmf_tv) &&
2364 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2365 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2367 f = &ast_null_frame;
2369 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2370 chan->dtmf_tv = ast_tvnow();
2371 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2374 case AST_FRAME_NULL:
2375 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2376 struct timeval now = ast_tvnow();
2377 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2378 chan->emulate_dtmf_duration = 0;
2381 f->frametype = AST_FRAME_DTMF_END;
2382 f->subclass = chan->emulate_dtmf_digit;
2383 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2384 chan->dtmf_tv = now;
2385 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2386 chan->emulate_dtmf_digit = 0;
2387 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2391 case AST_FRAME_VOICE:
2392 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2393 * is reached , because we want to make sure we pass at least one
2394 * voice frame through before starting the next digit, to ensure a gap
2395 * between DTMF digits. */
2396 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2397 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2398 chan->emulate_dtmf_digit = 0;
2401 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2403 ast_read_generator_actions(chan, f);
2405 f = &ast_null_frame;
2408 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2409 struct timeval now = ast_tvnow();
2410 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2411 chan->emulate_dtmf_duration = 0;
2414 f->frametype = AST_FRAME_DTMF_END;
2415 f->subclass = chan->emulate_dtmf_digit;
2416 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2417 chan->dtmf_tv = now;
2418 if (chan->audiohooks) {
2419 struct ast_frame *old_frame = f;
2420 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2422 ast_frfree(old_frame);
2424 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2426 /* Drop voice frames while we're still in the middle of the digit */
2428 f = &ast_null_frame;
2430 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2431 /* This frame can't be from the current native formats -- drop it on the
2433 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2434 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2436 f = &ast_null_frame;
2437 } else if ((f->frametype == AST_FRAME_VOICE)) {
2438 /* Send frame to audiohooks if present */
2439 if (chan->audiohooks) {
2440 struct ast_frame *old_frame = f;
2441 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2443 ast_frfree(old_frame);
2445 if (chan->monitor && chan->monitor->read_stream ) {
2446 /* XXX what does this do ? */
2447 #ifndef MONITOR_CONSTANT_DELAY
2448 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2450 jump = chan->outsmpl - chan->insmpl;
2451 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2452 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2453 chan->insmpl += jump + f->samples;
2455 chan->insmpl+= f->samples;
2457 int jump = chan->outsmpl - chan->insmpl;
2458 if (jump - MONITOR_DELAY >= 0) {
2459 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2460 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2461 chan->insmpl += jump;
2463 chan->insmpl += f->samples;
2465 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2466 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2467 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2471 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2472 f = &ast_null_frame;
2474 /* Run generator sitting on the line if timing device not available
2475 * and synchronous generation of outgoing frames is necessary */
2476 ast_read_generator_actions(chan, f);
2479 /* Just pass it on! */
2483 /* Make sure we always return NULL in the future */
2484 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2485 if (chan->generator)
2486 ast_deactivate_generator(chan);
2487 /* End the CDR if appropriate */
2489 ast_cdr_end(chan->cdr);
2492 /* High bit prints debugging */
2493 if (chan->fin & DEBUGCHAN_FLAG)
2494 ast_frame_dump(chan->name, f, "<<");
2495 chan->fin = FRAMECOUNT_INC(chan->fin);
2498 if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2499 chan->generator->digit(chan, f->subclass);
2501 ast_channel_unlock(chan);
2505 int ast_internal_timing_enabled(struct ast_channel *chan)
2507 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2508 ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2512 struct ast_frame *ast_read(struct ast_channel *chan)
2514 return __ast_read(chan, 0);
2517 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2519 return __ast_read(chan, 1);
2522 int ast_indicate(struct ast_channel *chan, int condition)
2524 return ast_indicate_data(chan, condition, NULL, 0);
2527 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2531 ast_channel_lock(chan);
2532 /* Stop if we're a zombie or need a soft hangup */
2533 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2534 ast_channel_unlock(chan);
2537 if (chan->tech->indicate)
2538 res = chan->tech->indicate(chan, condition, data, datalen);
2539 ast_channel_unlock(chan);
2540 if (!chan->tech->indicate || res) {
2542 * Device does not support (that) indication, lets fake
2543 * it by doing our own tone generation. (PM2002)
2546 ast_playtones_stop(chan);
2548 const struct ind_tone_zone_sound *ts = NULL;
2549 switch (condition) {
2550 case AST_CONTROL_RINGING:
2551 ts = ast_get_indication_tone(chan->zone, "ring");
2553 case AST_CONTROL_BUSY:
2554 ts = ast_get_indication_tone(chan->zone, "busy");
2556 case AST_CONTROL_CONGESTION:
2557 ts = ast_get_indication_tone(chan->zone, "congestion");
2560 if (ts && ts->data[0]) {
2561 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2562 ast_playtones_start(chan,0,ts->data, 1);
2564 } else if (condition == AST_CONTROL_PROGRESS) {
2565 /* ast_playtones_stop(chan); */
2566 } else if (condition == AST_CONTROL_PROCEEDING) {
2567 /* Do nothing, really */
2568 } else if (condition == AST_CONTROL_HOLD) {
2569 /* Do nothing.... */
2570 } else if (condition == AST_CONTROL_UNHOLD) {
2571 /* Do nothing.... */
2572 } else if (condition == AST_CONTROL_VIDUPDATE) {
2573 /* Do nothing.... */
2576 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2584 int ast_recvchar(struct ast_channel *chan, int timeout)
2587 char *buf = ast_recvtext(chan, timeout);
2589 return -1; /* error or timeout */
2590 c = *(unsigned char *)buf;
2595 char *ast_recvtext(struct ast_channel *chan, int timeout)
2601 struct ast_frame *f;
2602 if (ast_check_hangup(chan))
2604 res = ast_waitfor(chan, timeout);
2605 if (res <= 0) /* timeout or error */
2607 timeout = res; /* update timeout */
2610 break; /* no frame */
2611 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2612 done = 1; /* force a break */
2613 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2614 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2622 int ast_sendtext(struct ast_channel *chan, const char *text)
2625 /* Stop if we're a zombie or need a soft hangup */
2626 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2628 CHECK_BLOCKING(chan);
2629 if (chan->tech->send_text)
2630 res = chan->tech->send_text(chan, text);
2631 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2635 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2637 /* Device does not support DTMF tones, lets fake
2638 * it by doing our own generation. */
2639 static const char* dtmf_tones[] = {
2658 if (!chan->tech->send_digit_begin)
2661 if (!chan->tech->send_digit_begin(chan, digit))
2664 if (digit >= '0' && digit <='9')
2665 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2666 else if (digit >= 'A' && digit <= 'D')
2667 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2668 else if (digit == '*')
2669 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2670 else if (digit == '#')
2671 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2674 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2680 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2684 if (chan->tech->send_digit_end)
2685 res = chan->tech->send_digit_end(chan, digit, duration);
2687 if (res && chan->generator)
2688 ast_playtones_stop(chan);
2693 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
2695 if (chan->tech->send_digit_begin) {
2696 ast_senddigit_begin(chan, digit);
2697 ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2700 return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2703 int ast_prod(struct ast_channel *chan)
2705 struct ast_frame a = { AST_FRAME_VOICE };
2708 /* Send an empty audio frame to get things moving */
2709 if (chan->_state != AST_STATE_UP) {
2710 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2711 a.subclass = chan->rawwriteformat;
2712 a.data = nothing + AST_FRIENDLY_OFFSET;
2714 if (ast_write(chan, &a))
2715 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2720 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2723 if (!chan->tech->write_video)
2725 res = ast_write(chan, fr);
2731 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2734 struct ast_frame *f = NULL, *f2 = NULL;
2736 /* Stop if we're a zombie or need a soft hangup */
2737 ast_channel_lock(chan);
2738 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2741 /* Handle any pending masquerades */
2742 if (chan->masq && ast_do_masquerade(chan)) {
2743 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2747 res = 0; /* XXX explain, why 0 ? */
2750 if (chan->generatordata) {
2751 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2752 ast_deactivate_generator(chan);
2754 if (fr->frametype == AST_FRAME_DTMF_END) {
2755 /* There is a generator running while we're in the middle of a digit.
2756 * It's probably inband DTMF, so go ahead and pass it so it can
2757 * stop the generator */
2758 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2759 ast_channel_unlock(chan);
2760 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2761 ast_channel_lock(chan);
2762 CHECK_BLOCKING(chan);
2763 } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2764 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2765 res = (chan->tech->indicate == NULL) ? 0 :
2766 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2768 res = 0; /* XXX explain, why 0 ? */
2772 /* High bit prints debugging */
2773 if (chan->fout & DEBUGCHAN_FLAG)
2774 ast_frame_dump(chan->name, fr, ">>");
2775 CHECK_BLOCKING(chan);
2776 switch (fr->frametype) {
2777 case AST_FRAME_CONTROL:
2778 res = (chan->tech->indicate == NULL) ? 0 :
2779 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2781 case AST_FRAME_DTMF_BEGIN:
2782 if (chan->audiohooks) {
2783 struct ast_frame *old_frame = fr;
2784 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2785 if (old_frame != fr)
2788 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
2789 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2790 ast_channel_unlock(chan);
2791 res = ast_senddigit_begin(chan, fr->subclass);
2792 ast_channel_lock(chan);
2793 CHECK_BLOCKING(chan);
2795 case AST_FRAME_DTMF_END:
2796 if (chan->audiohooks) {
2797 struct ast_frame *old_frame = fr;
2798 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2799 if (old_frame != fr)
2802 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
2803 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2804 ast_channel_unlock(chan);
2805 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2806 ast_channel_lock(chan);
2807 CHECK_BLOCKING(chan);
2809 case AST_FRAME_TEXT:
2810 if (fr->subclass == AST_FORMAT_T140) {
2811 res = (chan->tech->write_text == NULL) ? 0 :
2812 chan->tech->write_text(chan, fr);
2814 res = (chan->tech->send_text == NULL) ? 0 :
2815 chan->tech->send_text(chan, (char *) fr->data);
2818 case AST_FRAME_HTML:
2819 res = (chan->tech->send_html == NULL) ? 0 :
2820 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2822 case AST_FRAME_VIDEO:
2823 /* XXX Handle translation of video codecs one day XXX */
2824 res = (chan->tech->write_video == NULL) ? 0 :
2825 chan->tech->write_video(chan, fr);
2827 case AST_FRAME_MODEM:
2828 res = (chan->tech->write == NULL) ? 0 :
2829 chan->tech->write(chan, fr);
2831 case AST_FRAME_VOICE:
2832 if (chan->tech->write == NULL)
2833 break; /*! \todo XXX should return 0 maybe ? */
2835 /* If audiohooks are present, write the frame out */
2836 if (chan->audiohooks) {
2837 struct ast_frame *old_frame = fr;
2838 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2839 if (old_frame != fr)
2843 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2844 if (fr->subclass == chan->rawwriteformat)
2847 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2854 /* If Monitor is running on this channel, then we have to write frames out there too */
2855 if (chan->monitor && chan->monitor->write_stream) {
2856 /* XXX must explain this code */
2857 #ifndef MONITOR_CONSTANT_DELAY
2858 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2860 jump = chan->insmpl - chan->outsmpl;
2861 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2862 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2863 chan->outsmpl += jump + f->samples;
2865 chan->outsmpl += f->samples;
2867 int jump = chan->insmpl - chan->outsmpl;
2868 if (jump - MONITOR_DELAY >= 0) {
2869 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2870 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2871 chan->outsmpl += jump;
2873 chan->outsmpl += f->samples;
2875 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2876 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2877 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2882 struct ast_channel *base = NULL;
2883 if (!chan->tech->get_base_channel || chan == chan->tech->get_base_channel(chan))
2884 res = chan->tech->write(chan, f);
2886 while (chan->tech->get_base_channel && (((base = chan->tech->get_base_channel(chan)) && ast_mutex_trylock(&base->lock)) || base == NULL)) {
2887 ast_mutex_unlock(&chan->lock);
2889 ast_mutex_lock(&chan->lock);
2891 res = base->tech->write(base, f);
2892 ast_mutex_unlock(&base->lock);
2897 case AST_FRAME_NULL:
2903 /* At this point, fr is the incoming frame and f is NULL. Channels do
2904 * not expect to get NULL as a frame pointer and will segfault. Hence,
2905 * we output the original frame passed in. */
2906 res = chan->tech->write(chan, fr);
2914 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2915 /* Consider a write failure to force a soft hangup */
2917 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2919 chan->fout = FRAMECOUNT_INC(chan->fout);
2922 ast_channel_unlock(chan);
2926 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2927 struct ast_trans_pvt **trans, const int direction)
2932 /* Make sure we only consider audio */
2933 fmt &= AST_FORMAT_AUDIO_MASK;
2935 native = chan->nativeformats;
2936 /* Find a translation path from the native format to one of the desired formats */
2939 res = ast_translator_best_choice(&fmt, &native);
2942 res = ast_translator_best_choice(&native, &fmt);
2945 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2946 ast_getformatname(native), ast_getformatname(fmt));
2950 /* Now we have a good choice for both. */
2951 ast_channel_lock(chan);
2953 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2954 /* the channel is already in these formats, so nothing to do */
2955 ast_channel_unlock(chan);
2959 *rawformat = native;
2960 /* User perspective is fmt */
2962 /* Free any read translation we have right now */
2964 ast_translator_free_path(*trans);
2965 /* Build a translation path from the raw format to the desired format */
2968 *trans = ast_translator_build_path(*format, *rawformat);
2971 *trans = ast_translator_build_path(*rawformat, *format);
2972 ast_channel_unlock(chan);
2973 ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
2974 direction ? "write" : "read", ast_getformatname(fmt));
2978 int ast_set_read_format(struct ast_channel *chan, int fmt)
2980 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2981 &chan->readtrans, 0);
2984 int ast_set_write_format(struct ast_channel *chan, int fmt)
2986 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2987 &chan->writetrans, 1);
2990 const char *ast_channel_reason2str(int reason)
2992 switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
2995 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
2996 case AST_CONTROL_HANGUP:
2998 case AST_CONTROL_RING:
2999 return "Local Ring";
3000 case AST_CONTROL_RINGING:
3001 return "Remote end Ringing";
3002 case AST_CONTROL_ANSWER:
3003 return "Remote end has Answered";
3004 case AST_CONTROL_BUSY:
3005 return "Remote end is Busy";
3006 case AST_CONTROL_CONGESTION:
3007 return "Congestion (circuits busy)";
3009 return "Unknown Reason!!";
3013 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)
3017 struct ast_channel *chan;
3023 outstate = &dummy_outstate; /* make outstate always a valid pointer */
3025 chan = ast_request(type, format, data, &cause);
3027 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
3028 /* compute error and return */
3029 if (cause == AST_CAUSE_BUSY)
3030 *outstate = AST_CONTROL_BUSY;
3031 else if (cause == AST_CAUSE_CONGESTION)
3032 *outstate = AST_CONTROL_CONGESTION;
3038 ast_set_variables(chan, oh->vars);
3039 /* XXX why is this necessary, for the parent_channel perhaps ? */
3040 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
3041 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
3042 if (oh->parent_channel) {
3043 ast_channel_inherit_variables(oh->parent_channel, chan);
3044 ast_channel_datastore_inherit(oh->parent_channel, chan);
3047 ast_cdr_setaccount(chan, oh->account);
3049 ast_set_callerid(chan, cid_num, cid_name, cid_num);
3053 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
3054 to keep from throwing off the basic order of the universe,
3055 we will try to keep this cdr from getting posted. */
3056 chan->cdr = ast_cdr_alloc();
3057 ast_cdr_init(chan->cdr, chan);
3058 ast_cdr_start(chan->cdr);
3060 if (ast_call(chan, data, 0)) { /* ast_call failed... */
3061 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
3063 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
3064 while (timeout && chan->_state != AST_STATE_UP) {
3065 struct ast_frame *f;
3066 res = ast_waitfor(chan, timeout);
3067 if (res <= 0) /* error, timeout, or done */
3073 *outstate = AST_CONTROL_HANGUP;