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>
33 #include <math.h> /* For PI */
35 #ifdef ZAPTEL_OPTIMIZATIONS
36 #include <sys/ioctl.h>
38 #include <linux/zaptel.h>
41 #endif /* __linux__ */
43 #error "You need newer zaptel! Please cvs update zaptel"
49 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
51 #include "asterisk/pbx.h"
52 #include "asterisk/frame.h"
53 #include "asterisk/sched.h"
54 #include "asterisk/options.h"
55 #include "asterisk/channel.h"
56 #include "asterisk/chanspy.h"
57 #include "asterisk/musiconhold.h"
58 #include "asterisk/logger.h"
59 #include "asterisk/say.h"
60 #include "asterisk/file.h"
61 #include "asterisk/cli.h"
62 #include "asterisk/translate.h"
63 #include "asterisk/manager.h"
64 #include "asterisk/chanvars.h"
65 #include "asterisk/linkedlists.h"
66 #include "asterisk/indications.h"
67 #include "asterisk/monitor.h"
68 #include "asterisk/causes.h"
69 #include "asterisk/callerid.h"
70 #include "asterisk/utils.h"
71 #include "asterisk/lock.h"
72 #include "asterisk/app.h"
73 #include "asterisk/transcap.h"
74 #include "asterisk/devicestate.h"
75 #include "asterisk/sha1.h"
77 struct channel_spy_trans {
79 struct ast_trans_pvt *path;
82 struct ast_channel_spy_list {
83 struct channel_spy_trans read_translator;
84 struct channel_spy_trans write_translator;
85 AST_LIST_HEAD_NOLOCK(, ast_channel_spy) list;
88 /* uncomment if you have problems with 'monitoring' synchronized files */
90 #define MONITOR_CONSTANT_DELAY
91 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
94 /*! Prevent new channel allocation if shutting down. */
95 static int shutting_down = 0;
97 AST_MUTEX_DEFINE_STATIC(uniquelock);
98 static int uniqueint = 0;
100 unsigned long global_fin = 0, global_fout = 0;
102 /* XXX Lock appropriately in more functions XXX */
105 const struct ast_channel_tech *tech;
106 AST_LIST_ENTRY(chanlist) list;
109 /*! the list of registered channel types */
110 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
112 /*! the list of channels we have. Note that the lock for this list is used for
113 both the channels list and the backends list. */
114 static AST_LIST_HEAD_STATIC(channels, ast_channel);
116 /*! map AST_CAUSE's to readable string representations */
117 const struct ast_cause {
121 { AST_CAUSE_UNALLOCATED, "Unallocated (unassigned) number" },
122 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "No route to specified transmit network" },
123 { AST_CAUSE_NO_ROUTE_DESTINATION, "No route to destination" },
124 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "Channel unacceptable" },
125 { AST_CAUSE_CALL_AWARDED_DELIVERED, "Call awarded and being delivered in an established channel" },
126 { AST_CAUSE_NORMAL_CLEARING, "Normal Clearing" },
127 { AST_CAUSE_USER_BUSY, "User busy" },
128 { AST_CAUSE_NO_USER_RESPONSE, "No user responding" },
129 { AST_CAUSE_NO_ANSWER, "User alerting, no answer" },
130 { AST_CAUSE_CALL_REJECTED, "Call Rejected" },
131 { AST_CAUSE_NUMBER_CHANGED, "Number changed" },
132 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "Destination out of order" },
133 { AST_CAUSE_INVALID_NUMBER_FORMAT, "Invalid number format" },
134 { AST_CAUSE_FACILITY_REJECTED, "Facility rejected" },
135 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "Response to STATus ENQuiry" },
136 { AST_CAUSE_NORMAL_UNSPECIFIED, "Normal, unspecified" },
137 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "Circuit/channel congestion" },
138 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "Network out of order" },
139 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "Temporary failure" },
140 { AST_CAUSE_SWITCH_CONGESTION, "Switching equipment congestion" },
141 { AST_CAUSE_ACCESS_INFO_DISCARDED, "Access information discarded" },
142 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "Requested channel not available" },
143 { AST_CAUSE_PRE_EMPTED, "Pre-empted" },
144 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "Facility not subscribed" },
145 { AST_CAUSE_OUTGOING_CALL_BARRED, "Outgoing call barred" },
146 { AST_CAUSE_INCOMING_CALL_BARRED, "Incoming call barred" },
147 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "Bearer capability not authorized" },
148 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "Bearer capability not available" },
149 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "Bearer capability not implemented" },
150 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "Channel not implemented" },
151 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "Facility not implemented" },
152 { AST_CAUSE_INVALID_CALL_REFERENCE, "Invalid call reference value" },
153 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "Incompatible destination" },
154 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "Invalid message unspecified" },
155 { AST_CAUSE_MANDATORY_IE_MISSING, "Mandatory information element is missing" },
156 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "Message type nonexist." },
157 { AST_CAUSE_WRONG_MESSAGE, "Wrong message" },
158 { AST_CAUSE_IE_NONEXIST, "Info. element nonexist or not implemented" },
159 { AST_CAUSE_INVALID_IE_CONTENTS, "Invalid information element contents" },
160 { AST_CAUSE_WRONG_CALL_STATE, "Message not compatible with call state" },
161 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "Recover on timer expiry" },
162 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "Mandatory IE length error" },
163 { AST_CAUSE_PROTOCOL_ERROR, "Protocol error, unspecified" },
164 { AST_CAUSE_INTERWORKING, "Interworking, unspecified" },
168 struct ast_variable *ast_channeltype_list(void)
171 struct ast_variable *var=NULL, *prev = NULL;
172 AST_LIST_TRAVERSE(&backends, cl, list) {
174 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description)))
177 var = ast_variable_new(cl->tech->type, cl->tech->description);
184 static int show_channeltypes(int fd, int argc, char *argv[])
186 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
190 ast_cli(fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
191 ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
192 if (AST_LIST_LOCK(&channels)) {
193 ast_log(LOG_WARNING, "Unable to lock channel list\n");
196 AST_LIST_TRAVERSE(&backends, cl, list) {
197 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description,
198 (cl->tech->devicestate) ? "yes" : "no",
199 (cl->tech->indicate) ? "yes" : "no",
200 (cl->tech->transfer) ? "yes" : "no");
203 AST_LIST_UNLOCK(&channels);
204 ast_cli(fd, "----------\n%d channel drivers registered.\n", count_chan);
205 return RESULT_SUCCESS;
211 static int show_channeltype(int fd, int argc, char *argv[])
213 struct chanlist *cl = NULL;
216 return RESULT_SHOWUSAGE;
218 if (AST_LIST_LOCK(&channels)) {
219 ast_log(LOG_WARNING, "Unable to lock channel list\n");
220 return RESULT_FAILURE;
223 AST_LIST_TRAVERSE(&backends, cl, list) {
224 if (!strncasecmp(cl->tech->type, argv[2], strlen(cl->tech->type))) {
231 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[2]);
232 AST_LIST_UNLOCK(&channels);
233 return RESULT_FAILURE;
237 "-- Info about channel driver: %s --\n"
238 " Device State: %s\n"
241 " Capabilities: %d\n"
244 " Image Support: %s\n"
245 " Text Support: %s\n",
247 (cl->tech->devicestate) ? "yes" : "no",
248 (cl->tech->indicate) ? "yes" : "no",
249 (cl->tech->transfer) ? "yes" : "no",
250 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
251 (cl->tech->send_digit) ? "yes" : "no",
252 (cl->tech->send_html) ? "yes" : "no",
253 (cl->tech->send_image) ? "yes" : "no",
254 (cl->tech->send_text) ? "yes" : "no"
258 AST_LIST_UNLOCK(&channels);
259 return RESULT_SUCCESS;
262 static char *complete_channeltypes(const char *line, const char *word, int pos, int state)
272 wordlen = strlen(word);
274 AST_LIST_TRAVERSE(&backends, cl, list) {
275 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
276 ret = strdup(cl->tech->type);
284 static char show_channeltypes_usage[] =
285 "Usage: show channeltypes\n"
286 " Shows available channel types registered in your Asterisk server.\n";
288 static char show_channeltype_usage[] =
289 "Usage: show channeltype <name>\n"
290 " Show details about the specified channel type, <name>.\n";
292 static struct ast_cli_entry cli_show_channeltypes =
293 { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
295 static struct ast_cli_entry cli_show_channeltype =
296 { { "show", "channeltype", NULL }, show_channeltype, "Give more details on that channel type", show_channeltype_usage, complete_channeltypes };
298 /*! \brief Checks to see if a channel is needing hang up */
299 int ast_check_hangup(struct ast_channel *chan)
301 if (chan->_softhangup) /* yes if soft hangup flag set */
303 if (!chan->tech_pvt) /* yes if no technology private data */
305 if (!chan->whentohangup) /* no if no hangup scheduled */
307 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
309 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
313 static int ast_check_hangup_locked(struct ast_channel *chan)
316 ast_mutex_lock(&chan->lock);
317 res = ast_check_hangup(chan);
318 ast_mutex_unlock(&chan->lock);
322 /*! \brief Initiate system shutdown */
323 void ast_begin_shutdown(int hangup)
325 struct ast_channel *c;
328 AST_LIST_LOCK(&channels);
329 AST_LIST_TRAVERSE(&channels, c, chan_list)
330 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
331 AST_LIST_UNLOCK(&channels);
335 /*! \brief returns number of active/allocated channels */
336 int ast_active_channels(void)
338 struct ast_channel *c;
340 AST_LIST_LOCK(&channels);
341 AST_LIST_TRAVERSE(&channels, c, chan_list)
343 AST_LIST_UNLOCK(&channels);
347 /*! \brief Cancel a shutdown in progress */
348 void ast_cancel_shutdown(void)
353 /*! \brief Returns non-zero if Asterisk is being shut down */
354 int ast_shutting_down(void)
356 return shutting_down;
359 /*! \brief Set when to hangup channel */
360 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
362 chan->whentohangup = offset ? time(NULL) + offset : 0;
363 ast_queue_frame(chan, &ast_null_frame);
367 /*! \brief Compare a offset with when to hangup channel */
368 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
372 if (chan->whentohangup == 0) {
373 return (offset == 0) ? 0 : -1;
375 if (offset == 0) /* XXX why is this special ? */
378 whentohangup = offset + time (NULL);
379 if (chan->whentohangup < whentohangup)
381 else if (chan->whentohangup == whentohangup)
389 /*! \brief Register a new telephony channel in Asterisk */
390 int ast_channel_register(const struct ast_channel_tech *tech)
392 struct chanlist *chan;
394 AST_LIST_LOCK(&channels);
396 AST_LIST_TRAVERSE(&backends, chan, list) {
397 if (!strcasecmp(tech->type, chan->tech->type)) {
398 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
399 AST_LIST_UNLOCK(&channels);
404 if (!(chan = ast_malloc(sizeof(*chan)))) {
405 AST_LIST_UNLOCK(&channels);
409 AST_LIST_INSERT_HEAD(&backends, chan, list);
412 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
414 if (option_verbose > 1)
415 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
416 chan->tech->description);
418 AST_LIST_UNLOCK(&channels);
422 void ast_channel_unregister(const struct ast_channel_tech *tech)
424 struct chanlist *chan;
427 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
429 AST_LIST_LOCK(&channels);
431 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
432 if (chan->tech == tech) {
433 AST_LIST_REMOVE_CURRENT(&backends, list);
435 if (option_verbose > 1)
436 ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
440 AST_LIST_TRAVERSE_SAFE_END
442 AST_LIST_UNLOCK(&channels);
445 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
447 struct chanlist *chanls;
448 const struct ast_channel_tech *ret = NULL;
450 if (AST_LIST_LOCK(&channels)) {
451 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
455 AST_LIST_TRAVERSE(&backends, chanls, list) {
456 if (!strcasecmp(name, chanls->tech->type)) {
462 AST_LIST_UNLOCK(&channels);
467 /*! \brief Gives the string form of a given hangup cause */
468 const char *ast_cause2str(int cause)
472 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
473 if (causes[x].cause == cause)
474 return causes[x].desc;
480 /*! \brief Gives the string form of a given channel state */
481 char *ast_state2str(int state)
483 /* XXX Not reentrant XXX */
484 static char localtmp[256];
488 case AST_STATE_RESERVED:
490 case AST_STATE_OFFHOOK:
492 case AST_STATE_DIALING:
496 case AST_STATE_RINGING:
503 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
508 /*! \brief Gives the string form of a given transfer capability */
509 char *ast_transfercapability2str(int transfercapability)
511 switch(transfercapability) {
512 case AST_TRANS_CAP_SPEECH:
514 case AST_TRANS_CAP_DIGITAL:
516 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
517 return "RESTRICTED_DIGITAL";
518 case AST_TRANS_CAP_3_1K_AUDIO:
520 case AST_TRANS_CAP_DIGITAL_W_TONES:
521 return "DIGITAL_W_TONES";
522 case AST_TRANS_CAP_VIDEO:
529 /*! \brief Pick the best codec */
530 int ast_best_codec(int fmts)
532 /* This just our opinion, expressed in code. We are asked to choose
533 the best codec to use, given no information */
537 /*! Okay, ulaw is used by all telephony equipment, so start with it */
539 /*! Unless of course, you're a silly European, so then prefer ALAW */
541 /*! Okay, well, signed linear is easy to translate into other stuff */
543 /*! G.726 is standard ADPCM */
545 /*! ADPCM has great sound quality and is still pretty easy to translate */
547 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
548 translate and sounds pretty good */
550 /*! iLBC is not too bad */
552 /*! Speex is free, but computationally more expensive than GSM */
554 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
557 /*! G.729a is faster than 723 and slightly less expensive */
559 /*! Down to G.723.1 which is proprietary but at least designed for voice */
564 /* Find the first preferred codec in the format given */
565 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
568 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
572 static const struct ast_channel_tech null_tech = {
574 .description = "Null channel (should not see this)",
577 /*! \brief Create a new channel structure */
578 struct ast_channel *ast_channel_alloc(int needqueue)
580 struct ast_channel *tmp;
583 struct varshead *headp;
585 /* If shutting down, don't allocate any new channels */
587 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
591 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
594 if (!(tmp->sched = sched_context_create())) {
595 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
600 ast_string_field_init(tmp, 128);
602 /* Don't bother initializing the last two FD here, because they
603 will *always* be set just a few lines down (AST_TIMING_FD,
605 for (x=0; x<AST_MAX_FDS - 2; x++)
608 #ifdef ZAPTEL_OPTIMIZATIONS
609 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
610 if (tmp->timingfd > -1) {
611 /* Check if timing interface supports new
614 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
622 if (pipe(tmp->alertpipe)) {
623 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
627 flags = fcntl(tmp->alertpipe[0], F_GETFL);
628 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
629 flags = fcntl(tmp->alertpipe[1], F_GETFL);
630 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
632 } else /* Make sure we've got it done right if they don't */
633 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
635 /* Always watch the alertpipe */
636 tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
637 /* And timing pipe */
638 tmp->fds[AST_TIMING_FD] = tmp->timingfd;
639 ast_string_field_set(tmp, name, "**Unknown**");
641 tmp->_state = AST_STATE_DOWN;
645 tmp->fin = global_fin;
646 tmp->fout = global_fout;
647 ast_mutex_lock(&uniquelock);
648 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
649 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), uniqueint++);
651 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, (long) time(NULL), uniqueint++);
652 ast_mutex_unlock(&uniquelock);
653 headp = &tmp->varshead;
654 ast_mutex_init(&tmp->lock);
655 AST_LIST_HEAD_INIT_NOLOCK(headp);
656 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
657 strcpy(tmp->context, "default");
658 ast_string_field_set(tmp, language, defaultlanguage);
659 strcpy(tmp->exten, "s");
661 tmp->amaflags = ast_default_amaflags;
662 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
664 tmp->tech = &null_tech;
666 AST_LIST_LOCK(&channels);
667 AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
668 AST_LIST_UNLOCK(&channels);
672 /*! \brief Queue an outgoing media frame */
673 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
676 struct ast_frame *prev, *cur;
680 /* Build us a copy and free the original one */
681 if (!(f = ast_frdup(fin))) {
682 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
685 ast_mutex_lock(&chan->lock);
687 for (cur = chan->readq; cur; cur = cur->next) {
688 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
689 /* Don't bother actually queueing anything after a hangup */
691 ast_mutex_unlock(&chan->lock);
697 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
698 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
699 if (fin->frametype != AST_FRAME_VOICE) {
700 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
703 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
705 ast_mutex_unlock(&chan->lock);
713 if (chan->alertpipe[1] > -1) {
714 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
715 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
716 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
717 #ifdef ZAPTEL_OPTIMIZATIONS
718 } else if (chan->timingfd > -1) {
719 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
721 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
722 pthread_kill(chan->blocker, SIGURG);
724 ast_mutex_unlock(&chan->lock);
728 /*! \brief Queue a hangup frame for channel */
729 int ast_queue_hangup(struct ast_channel *chan)
731 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
732 /* Yeah, let's not change a lock-critical value without locking */
733 if (!ast_mutex_trylock(&chan->lock)) {
734 chan->_softhangup |= AST_SOFTHANGUP_DEV;
735 ast_mutex_unlock(&chan->lock);
737 return ast_queue_frame(chan, &f);
740 /*! \brief Queue a control frame */
741 int ast_queue_control(struct ast_channel *chan, int control)
743 struct ast_frame f = { AST_FRAME_CONTROL, };
744 f.subclass = control;
745 return ast_queue_frame(chan, &f);
748 /*! \brief Set defer DTMF flag on channel */
749 int ast_channel_defer_dtmf(struct ast_channel *chan)
754 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
755 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
760 /*! \brief Unset defer DTMF flag on channel */
761 void ast_channel_undefer_dtmf(struct ast_channel *chan)
764 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
768 * \brief Helper function to find channels.
770 * It supports these modes:
772 * prev != NULL : get channel next in list after prev
773 * name != NULL : get channel with matching name
774 * name != NULL && namelen != 0 : get channel whose name starts with prefix
775 * exten != NULL : get channel whose exten or macroexten matches
776 * context != NULL && exten != NULL : get channel whose context or macrocontext
778 * It returns with the channel's lock held. If getting the individual lock fails,
779 * unlock and retry quickly up to 10 times, then give up.
781 * \note XXX Note that this code has cost O(N) because of the need to verify
782 * that the object is still on the global list.
784 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
785 * can only be done with the lock held or someone could delete the
786 * object while we work on it. This causes some ugliness in the code.
787 * Note that removing the first ast_log() may be harmful, as it would
788 * shorten the retry period and possibly cause failures.
789 * We should definitely go for a better scheme that is deadlock-free.
791 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
792 const char *name, const int namelen,
793 const char *context, const char *exten)
795 const char *msg = prev ? "deadlock" : "initial deadlock";
797 struct ast_channel *c;
799 for (retries = 0; retries < 10; retries++) {
800 AST_LIST_LOCK(&channels);
801 AST_LIST_TRAVERSE(&channels, c, chan_list) {
803 /* want head of list */
807 /* want match by full name */
809 if (!strcasecmp(c->name, name))
814 /* want match by name prefix */
815 if (!strncasecmp(c->name, name, namelen))
818 /* want match by context and exten */
819 if (context && (strcasecmp(c->context, context) &&
820 strcasecmp(c->macrocontext, context)))
823 if (strcasecmp(c->exten, exten) &&
824 strcasecmp(c->macroexten, exten))
829 } else if (c == prev) { /* found, return c->next */
830 c = AST_LIST_NEXT(c, chan_list);
834 /* exit if chan not found or mutex acquired successfully */
835 done = (c == NULL) || (ast_mutex_trylock(&c->lock) == 0);
836 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
838 ast_log(LOG_DEBUG, "Avoiding %s for '%s'\n", msg, c->name);
839 AST_LIST_UNLOCK(&channels);
845 * c is surely not null, but we don't have the lock so cannot
848 ast_log(LOG_WARNING, "Avoided %s for '%p', %d retries!\n",
854 /*! \brief Browse channels in use */
855 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
857 return channel_find_locked(prev, NULL, 0, NULL, NULL);
860 /*! \brief Get channel by name and lock it */
861 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
863 return channel_find_locked(NULL, name, 0, NULL, NULL);
866 /*! \brief Get channel by name prefix and lock it */
867 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
869 return channel_find_locked(NULL, name, namelen, NULL, NULL);
872 /*! \brief Get next channel by name prefix and lock it */
873 struct ast_channel *ast_walk_channel_by_name_prefix_locked(struct ast_channel *chan, const char *name, const int namelen)
875 return channel_find_locked(chan, name, namelen, NULL, NULL);
878 /*! \brief Get channel by exten (and optionally context) and lock it */
879 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
881 return channel_find_locked(NULL, NULL, 0, context, exten);
884 /*! \brief Wait, look for hangups and condition arg */
885 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
890 if (cond && ((*cond)(data) == 0))
892 ms = ast_waitfor(chan, ms);
905 /*! \brief Wait, look for hangups */
906 int ast_safe_sleep(struct ast_channel *chan, int ms)
908 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
911 static void free_cid(struct ast_callerid *cid)
922 free(cid->cid_rdnis);
925 /*! \brief Free a channel structure */
926 void ast_channel_free(struct ast_channel *chan)
929 struct ast_var_t *vardata;
930 struct ast_frame *f, *fp;
931 struct varshead *headp;
932 struct ast_datastore *datastore = NULL;
933 char name[AST_CHANNEL_NAME];
935 headp=&chan->varshead;
937 AST_LIST_LOCK(&channels);
938 AST_LIST_REMOVE(&channels, chan, chan_list);
939 /* Lock and unlock the channel just to be sure nobody
940 has it locked still */
941 ast_mutex_lock(&chan->lock);
942 ast_mutex_unlock(&chan->lock);
943 if (chan->tech_pvt) {
944 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
945 free(chan->tech_pvt);
949 sched_context_destroy(chan->sched);
951 ast_copy_string(name, chan->name, sizeof(name));
953 /* Stop monitoring */
955 chan->monitor->stop( chan, 0 );
958 /* If there is native format music-on-hold state, free it */
959 if(chan->music_state)
960 ast_moh_cleanup(chan);
962 /* Free translators */
964 ast_translator_free_path(chan->readtrans);
965 if (chan->writetrans)
966 ast_translator_free_path(chan->writetrans);
968 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
969 free_cid(&chan->cid);
970 ast_mutex_destroy(&chan->lock);
971 /* Close pipes if appropriate */
972 if ((fd = chan->alertpipe[0]) > -1)
974 if ((fd = chan->alertpipe[1]) > -1)
976 if ((fd = chan->timingfd) > -1)
986 /* Get rid of each of the data stores on the channel */
987 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
988 /* Free the data store */
989 ast_channel_datastore_free(datastore);
990 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
992 /* loop over the variables list, freeing all data and deleting list items */
993 /* no need to lock the list, as the channel is already locked */
995 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
996 ast_var_delete(vardata);
998 ast_string_field_free_all(chan);
1000 AST_LIST_UNLOCK(&channels);
1002 ast_device_state_changed_literal(name);
1005 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1007 struct ast_datastore *datastore = NULL;
1009 /* Make sure we at least have type so we can identify this */
1014 /* Allocate memory for datastore and clear it */
1015 datastore = ast_calloc(1, sizeof(*datastore));
1016 if (datastore == NULL) {
1020 datastore->info = info;
1023 datastore->uid = ast_strdup(uid);
1029 int ast_channel_datastore_free(struct ast_datastore *datastore)
1033 /* Using the destroy function (if present) destroy the data */
1034 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1035 datastore->info->destroy(datastore->data);
1036 datastore->data = NULL;
1039 /* Free allocated UID memory */
1040 if (datastore->uid != NULL) {
1041 free(datastore->uid);
1042 datastore->uid = NULL;
1045 /* Finally free memory used by ourselves */
1052 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1056 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1061 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1063 struct ast_datastore *datastore2 = NULL;
1066 /* Find our position and remove ourselves */
1067 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1068 if (datastore2 == datastore) {
1069 AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1074 AST_LIST_TRAVERSE_SAFE_END
1079 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1081 struct ast_datastore *datastore = NULL;
1086 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1087 if (datastore->info == info) {
1088 if (uid != NULL && datastore->uid != NULL) {
1089 if (!strcasecmp(uid, datastore->uid)) {
1090 /* Matched by type AND uid */
1094 /* Matched by type at least */
1099 AST_LIST_TRAVERSE_SAFE_END
1104 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1106 if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1107 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1108 spy->type, chan->name);
1112 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1113 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1114 ast_getformatname(spy->read_queue.format));
1118 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1119 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1120 ast_getformatname(spy->write_queue.format));
1124 if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1125 ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1126 (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1127 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1128 ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1133 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1137 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1138 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1140 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1143 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1144 ast_cond_init(&spy->trigger, NULL);
1145 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1146 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1149 ast_log(LOG_DEBUG, "Spy %s added to channel %s\n",
1150 spy->type, chan->name);
1155 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1157 struct ast_channel_spy *spy;
1162 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1163 ast_mutex_lock(&spy->lock);
1164 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1165 spy->status = CHANSPY_STOP;
1166 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1167 ast_cond_signal(&spy->trigger);
1169 ast_mutex_unlock(&spy->lock);
1173 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1175 ast_cond_wait(&spy->trigger, &spy->lock);
1178 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1180 struct ast_frame *f;
1185 AST_LIST_REMOVE(&chan->spies->list, spy, list);
1187 ast_mutex_lock(&spy->lock);
1189 for (f = spy->read_queue.head; f; f = spy->read_queue.head) {
1190 spy->read_queue.head = f->next;
1193 for (f = spy->write_queue.head; f; f = spy->write_queue.head) {
1194 spy->write_queue.head = f->next;
1198 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1199 ast_cond_destroy(&spy->trigger);
1201 ast_mutex_unlock(&spy->lock);
1203 ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n",
1204 spy->type, chan->name);
1206 if (AST_LIST_EMPTY(&chan->spies->list)) {
1207 if (chan->spies->read_translator.path)
1208 ast_translator_free_path(chan->spies->read_translator.path);
1209 if (chan->spies->write_translator.path)
1210 ast_translator_free_path(chan->spies->write_translator.path);
1216 static void detach_spies(struct ast_channel *chan)
1218 struct ast_channel_spy *spy;
1223 /* Marking the spies as done is sufficient. Chanspy or spy users will get the picture. */
1224 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1225 ast_mutex_lock(&spy->lock);
1226 if (spy->status == CHANSPY_RUNNING)
1227 spy->status = CHANSPY_DONE;
1228 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1229 ast_cond_signal(&spy->trigger);
1230 ast_mutex_unlock(&spy->lock);
1233 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list)
1234 ast_channel_spy_remove(chan, spy);
1235 AST_LIST_TRAVERSE_SAFE_END;
1238 /*! \brief Softly hangup a channel, don't lock */
1239 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1242 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1243 /* Inform channel driver that we need to be hung up, if it cares */
1244 chan->_softhangup |= cause;
1245 ast_queue_frame(chan, &ast_null_frame);
1246 /* Interrupt any poll call or such */
1247 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1248 pthread_kill(chan->blocker, SIGURG);
1252 /*! \brief Softly hangup a channel, lock */
1253 int ast_softhangup(struct ast_channel *chan, int cause)
1256 ast_mutex_lock(&chan->lock);
1257 res = ast_softhangup_nolock(chan, cause);
1258 ast_mutex_unlock(&chan->lock);
1262 enum spy_direction {
1267 #define SPY_QUEUE_SAMPLE_LIMIT 4000 /* half of one second */
1269 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1271 struct ast_frame *translated_frame = NULL;
1272 struct ast_channel_spy *spy;
1273 struct ast_channel_spy_queue *queue;
1274 struct channel_spy_trans *trans;
1275 struct ast_frame *last;
1277 trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1279 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1280 ast_mutex_lock(&spy->lock);
1282 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1284 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1285 if (!translated_frame) {
1286 if (trans->path && (trans->last_format != f->subclass)) {
1287 ast_translator_free_path(trans->path);
1291 ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1292 ast_getformatname(f->subclass), chan->name);
1293 if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1294 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1295 ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1296 ast_mutex_unlock(&spy->lock);
1299 trans->last_format = f->subclass;
1302 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1303 ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1304 ast_getformatname(AST_FORMAT_SLINEAR));
1305 ast_mutex_unlock(&spy->lock);
1310 for (last = queue->head; last && last->next; last = last->next);
1312 last->next = ast_frdup(translated_frame);
1314 queue->head = ast_frdup(translated_frame);
1316 if (f->subclass != queue->format) {
1317 ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1318 spy->type, chan->name,
1319 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1320 ast_mutex_unlock(&spy->lock);
1324 for (last = queue->head; last && last->next; last = last->next);
1326 last->next = ast_frdup(f);
1328 queue->head = ast_frdup(f);
1331 queue->samples += f->samples;
1333 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1334 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1335 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1336 case CHANSPY_TRIGGER_READ:
1337 if (dir == SPY_WRITE) {
1338 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1339 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1341 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1342 spy->type, chan->name);
1345 case CHANSPY_TRIGGER_WRITE:
1346 if (dir == SPY_READ) {
1347 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1348 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1350 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1351 spy->type, chan->name);
1356 ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1357 spy->type, chan->name);
1358 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1359 ast_cond_signal(&spy->trigger);
1362 ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1363 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1364 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1365 struct ast_frame *drop = queue->head;
1367 queue->samples -= drop->samples;
1368 queue->head = drop->next;
1373 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1374 case CHANSPY_TRIGGER_READ:
1375 if (dir == SPY_READ)
1376 ast_cond_signal(&spy->trigger);
1378 case CHANSPY_TRIGGER_WRITE:
1379 if (dir == SPY_WRITE)
1380 ast_cond_signal(&spy->trigger);
1385 ast_mutex_unlock(&spy->lock);
1388 if (translated_frame)
1389 ast_frfree(translated_frame);
1392 static void free_translation(struct ast_channel *clone)
1394 if (clone->writetrans)
1395 ast_translator_free_path(clone->writetrans);
1396 if (clone->readtrans)
1397 ast_translator_free_path(clone->readtrans);
1398 clone->writetrans = NULL;
1399 clone->readtrans = NULL;
1400 clone->rawwriteformat = clone->nativeformats;
1401 clone->rawreadformat = clone->nativeformats;
1404 /*! \brief Hangup a channel */
1405 int ast_hangup(struct ast_channel *chan)
1409 /* Don't actually hang up a channel that will masquerade as someone else, or
1410 if someone is going to masquerade as us */
1411 ast_mutex_lock(&chan->lock);
1413 detach_spies(chan); /* get rid of spies */
1416 if (ast_do_masquerade(chan))
1417 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1421 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1422 ast_mutex_unlock(&chan->lock);
1425 /* If this channel is one which will be masqueraded into something,
1426 mark it as a zombie already, so we know to free it later */
1428 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1429 ast_mutex_unlock(&chan->lock);
1432 free_translation(chan);
1433 if (chan->stream) /* Close audio stream */
1434 ast_closestream(chan->stream);
1435 if (chan->vstream) /* Close video stream */
1436 ast_closestream(chan->vstream);
1438 sched_context_destroy(chan->sched);
1442 if (chan->generatordata) /* Clear any tone stuff remaining */
1443 chan->generator->release(chan, chan->generatordata);
1444 chan->generatordata = NULL;
1445 chan->generator = NULL;
1446 if (chan->cdr) { /* End the CDR if it hasn't already */
1447 ast_cdr_end(chan->cdr);
1448 ast_cdr_detach(chan->cdr); /* Post and Free the CDR */
1451 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1452 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1453 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1454 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1457 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1459 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1460 if (chan->tech->hangup)
1461 res = chan->tech->hangup(chan);
1464 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1467 ast_mutex_unlock(&chan->lock);
1468 manager_event(EVENT_FLAG_CALL, "Hangup",
1472 "Cause-txt: %s\r\n",
1476 ast_cause2str(chan->hangupcause)
1478 ast_channel_free(chan);
1482 int ast_answer(struct ast_channel *chan)
1485 ast_mutex_lock(&chan->lock);
1486 /* Stop if we're a zombie or need a soft hangup */
1487 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1488 ast_mutex_unlock(&chan->lock);
1491 switch(chan->_state) {
1492 case AST_STATE_RINGING:
1493 case AST_STATE_RING:
1494 if (chan->tech->answer)
1495 res = chan->tech->answer(chan);
1496 ast_setstate(chan, AST_STATE_UP);
1498 ast_cdr_answer(chan->cdr);
1499 ast_mutex_unlock(&chan->lock);
1504 ast_cdr_answer(chan->cdr);
1507 ast_mutex_unlock(&chan->lock);
1511 void ast_deactivate_generator(struct ast_channel *chan)
1513 ast_mutex_lock(&chan->lock);
1514 if (chan->generatordata) {
1515 if (chan->generator && chan->generator->release)
1516 chan->generator->release(chan, chan->generatordata);
1517 chan->generatordata = NULL;
1518 chan->generator = NULL;
1519 chan->fds[AST_GENERATOR_FD] = -1;
1520 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1521 ast_settimeout(chan, 0, NULL, NULL);
1523 ast_mutex_unlock(&chan->lock);
1526 static int generator_force(void *data)
1528 /* Called if generator doesn't have data */
1531 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1532 struct ast_channel *chan = data;
1533 tmp = chan->generatordata;
1534 chan->generatordata = NULL;
1535 generate = chan->generator->generate;
1536 res = generate(chan, tmp, 0, 160);
1537 chan->generatordata = tmp;
1539 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1540 ast_deactivate_generator(chan);
1545 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1549 ast_mutex_lock(&chan->lock);
1551 if (chan->generatordata) {
1552 if (chan->generator && chan->generator->release)
1553 chan->generator->release(chan, chan->generatordata);
1554 chan->generatordata = NULL;
1558 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1563 ast_settimeout(chan, 160, generator_force, chan);
1564 chan->generator = gen;
1567 ast_mutex_unlock(&chan->lock);
1572 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1573 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1576 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1580 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1581 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1582 int *exception, int *outfd, int *ms)
1584 struct timeval start = { 0 , 0 };
1585 struct pollfd *pfds;
1591 long whentohangup = 0, diff;
1592 struct ast_channel *winner = NULL;
1598 sz = n * AST_MAX_FDS + nfds;
1599 if (!(pfds = alloca(sizeof(*pfds) * sz)) || !(fdmap = alloca(sizeof(*fdmap) * sz))) {
1600 ast_log(LOG_ERROR, "Out of memory\n");
1610 /* Perform any pending masquerades */
1611 for (x=0; x < n; x++) {
1612 ast_mutex_lock(&c[x]->lock);
1614 if (ast_do_masquerade(c[x])) {
1615 ast_log(LOG_WARNING, "Masquerade failed\n");
1617 ast_mutex_unlock(&c[x]->lock);
1621 if (c[x]->whentohangup) {
1624 diff = c[x]->whentohangup - now;
1626 /* Should already be hungup */
1627 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1628 ast_mutex_unlock(&c[x]->lock);
1631 if (!whentohangup || (diff < whentohangup))
1632 whentohangup = diff;
1634 ast_mutex_unlock(&c[x]->lock);
1636 /* Wait full interval */
1639 rms = (whentohangup - now) * 1000; /* timeout in milliseconds */
1640 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1644 * Build the pollfd array, putting the channels' fds first,
1645 * followed by individual fds. Order is important because
1646 * individual fd's must have priority over channel fds.
1649 for (x=0; x<n; x++) {
1650 for (y=0; y<AST_MAX_FDS; y++) {
1651 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1652 fdmap[max].chan = x; /* channel x is linked to this pfds */
1653 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1655 CHECK_BLOCKING(c[x]);
1657 /* Add the individual fds */
1658 for (x=0; x<nfds; x++) {
1659 fdmap[max].chan = -1;
1660 max += ast_add_fd(&pfds[max], fds[x]);
1664 start = ast_tvnow();
1666 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1671 res = poll(pfds, max, kbrms);
1674 } while (!res && (rms > 0));
1676 res = poll(pfds, max, rms);
1679 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1680 if (res < 0) { /* Simulate a timeout if we were interrupted */
1685 if (whentohangup) { /* if we have a timeout, check who expired */
1687 for (x=0; x<n; x++) {
1688 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1689 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1695 if (res == 0) { /* no fd ready, reset timeout and done */
1696 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1700 * Then check if any channel or fd has a pending event.
1701 * Remember to check channels first and fds last, as they
1702 * must have priority on setting 'winner'
1704 for (x = 0; x < max; x++) {
1705 res = pfds[x].revents;
1708 if (fdmap[x].chan >= 0) { /* this is a channel */
1709 winner = c[fdmap[x].chan]; /* override previous winners */
1711 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1713 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1714 winner->fdno = fdmap[x].fdno;
1715 } else { /* this is an fd */
1717 *outfd = pfds[x].fd;
1719 *exception = (res & POLLPRI) ? -1 : 0;
1724 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1731 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1733 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1736 int ast_waitfor(struct ast_channel *c, int ms)
1740 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1741 if ((ms < 0) && (oldms < 0))
1746 int ast_waitfordigit(struct ast_channel *c, int ms)
1748 /* XXX Should I be merged with waitfordigit_full XXX */
1749 struct ast_frame *f;
1752 /* Stop if we're a zombie or need a soft hangup */
1753 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1756 /* Wait for a digit, no more than ms milliseconds total. */
1757 while(ms && !result) {
1758 ms = ast_waitfor(c, ms);
1759 if (ms < 0) /* Error */
1762 /* Read something */
1765 if (f->frametype == AST_FRAME_DTMF)
1766 result = f->subclass;
1775 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1778 #ifdef ZAPTEL_OPTIMIZATIONS
1779 if (c->timingfd > -1) {
1784 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1785 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1786 c->timingfunc = func;
1787 c->timingdata = data;
1793 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1795 struct ast_frame *f;
1796 struct ast_channel *rchan;
1800 /* Stop if we're a zombie or need a soft hangup */
1801 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1803 /* Wait for a digit, no more than ms milliseconds total. */
1806 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1807 if ((!rchan) && (outfd < 0) && (ms)) {
1808 if (errno == 0 || errno == EINTR)
1810 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1812 } else if (outfd > -1) {
1813 /* The FD we were watching has something waiting */
1821 switch(f->frametype) {
1822 case AST_FRAME_DTMF:
1826 case AST_FRAME_CONTROL:
1827 switch(f->subclass) {
1828 case AST_CONTROL_HANGUP:
1831 case AST_CONTROL_RINGING:
1832 case AST_CONTROL_ANSWER:
1836 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1838 case AST_FRAME_VOICE:
1839 /* Write audio if appropriate */
1841 write(audiofd, f->data, f->datalen);
1847 return 0; /* Time is up */
1850 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1852 struct ast_frame *f = NULL;
1855 #ifdef ZAPTEL_OPTIMIZATIONS
1856 int (*func)(void *);
1860 ast_mutex_lock(&chan->lock);
1862 if (ast_do_masquerade(chan)) {
1863 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1866 f = &ast_null_frame;
1867 ast_mutex_unlock(&chan->lock);
1871 /* Stop if we're a zombie or need a soft hangup */
1872 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1873 if (chan->generator)
1874 ast_deactivate_generator(chan);
1875 ast_mutex_unlock(&chan->lock);
1878 prestate = chan->_state;
1880 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1881 /* We have DTMF that has been deferred. Return it now */
1882 chan->dtmff.frametype = AST_FRAME_DTMF;
1883 chan->dtmff.subclass = chan->dtmfq[0];
1884 /* Drop first digit */
1885 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1886 ast_mutex_unlock(&chan->lock);
1887 return &chan->dtmff;
1890 /* Read and ignore anything on the alertpipe, but read only
1891 one sizeof(blah) per frame that we send from it */
1892 if (chan->alertpipe[0] > -1) {
1893 read(chan->alertpipe[0], &blah, sizeof(blah));
1895 #ifdef ZAPTEL_OPTIMIZATIONS
1896 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1897 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1899 /* IF we can't get event, assume it's an expired as-per the old interface */
1900 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1902 blah = ZT_EVENT_TIMER_EXPIRED;
1904 if (blah == ZT_EVENT_TIMER_PING) {
1906 ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1908 if (!chan->readq || !chan->readq->next) {
1909 /* Acknowledge PONG unless we need it again */
1911 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1913 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1914 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1917 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1918 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1919 func = chan->timingfunc;
1920 data = chan->timingdata;
1921 ast_mutex_unlock(&chan->lock);
1924 ast_log(LOG_DEBUG, "Calling private function\n");
1929 ast_mutex_lock(&chan->lock);
1930 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1931 chan->timingdata = NULL;
1932 ast_mutex_unlock(&chan->lock);
1934 return &ast_null_frame;
1936 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1939 /* Check for AST_GENERATOR_FD if not null. If so, call generator with -1
1940 arguments now so it can do whatever it needs to. */
1941 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
1942 void *tmp = chan->generatordata;
1943 chan->generatordata = NULL; /* reset to let ast_write get through */
1944 chan->generator->generate(chan, tmp, -1, -1);
1945 chan->generatordata = tmp;
1946 return &ast_null_frame;
1949 /* Check for pending read queue */
1952 chan->readq = f->next;
1954 /* Interpret hangup and return NULL */
1955 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1960 chan->blocker = pthread_self();
1961 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1962 if (chan->tech->exception)
1963 f = chan->tech->exception(chan);
1965 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1966 f = &ast_null_frame;
1968 /* Clear the exception flag */
1969 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1971 if (chan->tech->read)
1972 f = chan->tech->read(chan);
1974 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1979 /* if the channel driver returned more than one frame, stuff the excess
1980 into the readq for the next ast_read call
1983 chan->readq = f->next;
1987 switch (f->frametype) {
1988 case AST_FRAME_CONTROL:
1989 if (f->subclass == AST_CONTROL_ANSWER) {
1990 if (prestate == AST_STATE_UP) {
1991 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1992 f = &ast_null_frame;
1994 /* Answer the CDR */
1995 ast_setstate(chan, AST_STATE_UP);
1996 ast_cdr_answer(chan->cdr);
1999 case AST_FRAME_DTMF:
2000 ast_log(LOG_DTMF, "DTMF '%c' received on %s\n", f->subclass, chan->name);
2001 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF)) {
2002 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2003 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2005 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2006 f = &ast_null_frame;
2009 case AST_FRAME_DTMF_BEGIN:
2010 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2012 case AST_FRAME_DTMF_END:
2013 ast_log(LOG_DTMF, "DTMF end '%c' received on %s\n", f->subclass, chan->name);
2015 case AST_FRAME_VOICE:
2018 f = &ast_null_frame;
2019 } else if (!(f->subclass & chan->nativeformats)) {
2020 /* This frame can't be from the current native formats -- drop it on the
2022 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2023 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2025 f = &ast_null_frame;
2028 queue_frame_to_spies(chan, f, SPY_READ);
2030 if (chan->monitor && chan->monitor->read_stream ) {
2031 #ifndef MONITOR_CONSTANT_DELAY
2032 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2034 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2035 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2036 chan->insmpl += jump + 4 * f->samples;
2038 chan->insmpl+= f->samples;
2040 int jump = chan->outsmpl - chan->insmpl;
2041 if (jump - MONITOR_DELAY >= 0) {
2042 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2043 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2044 chan->insmpl += jump;
2046 chan->insmpl += f->samples;
2048 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2049 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2050 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2054 if (chan->readtrans) {
2055 if (!(f = ast_translate(chan->readtrans, f, 1)))
2056 f = &ast_null_frame;
2059 /* Run generator sitting on the line if timing device not available
2060 * and synchronous generation of outgoing frames is necessary */
2061 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2064 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
2066 if (chan->timingfunc) {
2067 if (option_debug > 1)
2068 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2069 ast_settimeout(chan, 0, NULL, NULL);
2072 tmp = chan->generatordata;
2073 chan->generatordata = NULL;
2074 generate = chan->generator->generate;
2075 res = generate(chan, tmp, f->datalen, f->samples);
2076 chan->generatordata = tmp;
2078 if (option_debug > 1)
2079 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2080 ast_deactivate_generator(chan);
2083 } else if (f->frametype == AST_FRAME_CNG) {
2084 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2085 if (option_debug > 1)
2086 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2087 ast_settimeout(chan, 160, generator_force, chan);
2093 /* Make sure we always return NULL in the future */
2094 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2095 if (chan->generator)
2096 ast_deactivate_generator(chan);
2097 /* End the CDR if appropriate */
2099 ast_cdr_end(chan->cdr);
2102 /* High bit prints debugging */
2103 if (chan->fin & 0x80000000)
2104 ast_frame_dump(chan->name, f, "<<");
2105 if ((chan->fin & 0x7fffffff) == 0x7fffffff)
2106 chan->fin &= 0x80000000;
2109 ast_mutex_unlock(&chan->lock);
2114 int ast_internal_timing_enabled(struct ast_channel *chan)
2116 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2117 if (option_debug > 3)
2118 ast_log(LOG_DEBUG, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2122 struct ast_frame *ast_read(struct ast_channel *chan)
2124 return __ast_read(chan, 0);
2127 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2129 return __ast_read(chan, 1);
2132 int ast_indicate(struct ast_channel *chan, int condition)
2136 ast_mutex_lock(&chan->lock);
2137 /* Stop if we're a zombie or need a soft hangup */
2138 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2139 ast_mutex_unlock(&chan->lock);
2142 if (chan->tech->indicate)
2143 res = chan->tech->indicate(chan, condition);
2144 ast_mutex_unlock(&chan->lock);
2145 if (!chan->tech->indicate || res) {
2147 * Device does not support (that) indication, lets fake
2148 * it by doing our own tone generation. (PM2002)
2150 if (condition >= 0) {
2151 const struct tone_zone_sound *ts = NULL;
2152 switch (condition) {
2153 case AST_CONTROL_RINGING:
2154 ts = ast_get_indication_tone(chan->zone, "ring");
2156 case AST_CONTROL_BUSY:
2157 ts = ast_get_indication_tone(chan->zone, "busy");
2159 case AST_CONTROL_CONGESTION:
2160 ts = ast_get_indication_tone(chan->zone, "congestion");
2163 if (ts && ts->data[0]) {
2164 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2165 ast_playtones_start(chan,0,ts->data, 1);
2167 } else if (condition == AST_CONTROL_PROGRESS) {
2168 /* ast_playtones_stop(chan); */
2169 } else if (condition == AST_CONTROL_PROCEEDING) {
2170 /* Do nothing, really */
2171 } else if (condition == AST_CONTROL_HOLD) {
2172 /* Do nothing.... */
2173 } else if (condition == AST_CONTROL_UNHOLD) {
2174 /* Do nothing.... */
2175 } else if (condition == AST_CONTROL_VIDUPDATE) {
2176 /* Do nothing.... */
2179 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2183 else ast_playtones_stop(chan);
2188 int ast_recvchar(struct ast_channel *chan, int timeout)
2191 char *buf = ast_recvtext(chan, timeout);
2193 return -1; /* error or timeout */
2194 c = *(unsigned char *)buf;
2199 char *ast_recvtext(struct ast_channel *chan, int timeout)
2205 struct ast_frame *f;
2206 if (ast_check_hangup(chan))
2208 res = ast_waitfor(chan, timeout);
2209 if (res <= 0) /* timeout or error */
2211 timeout = res; /* update timeout */
2214 break; /* no frame */
2215 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2216 done = 1; /* force a break */
2217 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2218 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2226 int ast_sendtext(struct ast_channel *chan, const char *text)
2229 /* Stop if we're a zombie or need a soft hangup */
2230 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2232 CHECK_BLOCKING(chan);
2233 if (chan->tech->send_text)
2234 res = chan->tech->send_text(chan, text);
2235 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2239 static int do_senddigit(struct ast_channel *chan, char digit)
2243 if (chan->tech->send_digit)
2244 res = chan->tech->send_digit(chan, digit);
2245 if (!(chan->tech->send_digit && chan->tech->send_digit_begin) ||
2248 * Device does not support DTMF tones, lets fake
2249 * it by doing our own generation. (PM2002)
2251 static const char* dtmf_tones[] = {
2252 "!941+1336/100,!0/100", /* 0 */
2253 "!697+1209/100,!0/100", /* 1 */
2254 "!697+1336/100,!0/100", /* 2 */
2255 "!697+1477/100,!0/100", /* 3 */
2256 "!770+1209/100,!0/100", /* 4 */
2257 "!770+1336/100,!0/100", /* 5 */
2258 "!770+1477/100,!0/100", /* 6 */
2259 "!852+1209/100,!0/100", /* 7 */
2260 "!852+1336/100,!0/100", /* 8 */
2261 "!852+1477/100,!0/100", /* 9 */
2262 "!697+1633/100,!0/100", /* A */
2263 "!770+1633/100,!0/100", /* B */
2264 "!852+1633/100,!0/100", /* C */
2265 "!941+1633/100,!0/100", /* D */
2266 "!941+1209/100,!0/100", /* * */
2267 "!941+1477/100,!0/100" }; /* # */
2268 if (digit >= '0' && digit <='9')
2269 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2270 else if (digit >= 'A' && digit <= 'D')
2271 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2272 else if (digit == '*')
2273 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2274 else if (digit == '#')
2275 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2278 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2284 int ast_senddigit(struct ast_channel *chan, char digit)
2286 return do_senddigit(chan, digit);
2289 int ast_prod(struct ast_channel *chan)
2291 struct ast_frame a = { AST_FRAME_VOICE };
2294 /* Send an empty audio frame to get things moving */
2295 if (chan->_state != AST_STATE_UP) {
2296 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2297 a.subclass = chan->rawwriteformat;
2298 a.data = nothing + AST_FRIENDLY_OFFSET;
2300 if (ast_write(chan, &a))
2301 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2306 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2309 if (!chan->tech->write_video)
2311 res = ast_write(chan, fr);
2317 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2320 struct ast_frame *f = NULL;
2321 /* Stop if we're a zombie or need a soft hangup */
2322 ast_mutex_lock(&chan->lock);
2323 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2324 ast_mutex_unlock(&chan->lock);
2327 /* Handle any pending masquerades */
2329 if (ast_do_masquerade(chan)) {
2330 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2331 ast_mutex_unlock(&chan->lock);
2336 ast_mutex_unlock(&chan->lock);
2339 if (chan->generatordata) {
2340 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2341 ast_deactivate_generator(chan);
2343 ast_mutex_unlock(&chan->lock);
2347 /* High bit prints debugging */
2348 if (chan->fout & 0x80000000)
2349 ast_frame_dump(chan->name, fr, ">>");
2350 CHECK_BLOCKING(chan);
2351 switch(fr->frametype) {
2352 case AST_FRAME_CONTROL:
2353 /* XXX Interpret control frames XXX */
2354 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
2356 case AST_FRAME_DTMF_BEGIN:
2357 if (chan->tech->send_digit_begin)
2358 res = chan->tech->send_digit_begin(chan, fr->subclass);
2362 case AST_FRAME_DTMF_END:
2363 if (chan->tech->send_digit_end)
2364 res = chan->tech->send_digit_end(chan);
2368 case AST_FRAME_DTMF:
2369 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2370 ast_mutex_unlock(&chan->lock);
2371 res = do_senddigit(chan,fr->subclass);
2372 ast_mutex_lock(&chan->lock);
2373 CHECK_BLOCKING(chan);
2375 case AST_FRAME_TEXT:
2376 if (chan->tech->send_text)
2377 res = chan->tech->send_text(chan, (char *) fr->data);
2381 case AST_FRAME_HTML:
2382 if (chan->tech->send_html)
2383 res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2387 case AST_FRAME_VIDEO:
2388 /* XXX Handle translation of video codecs one day XXX */
2389 if (chan->tech->write_video)
2390 res = chan->tech->write_video(chan, fr);
2394 case AST_FRAME_VOICE:
2395 if (chan->tech->write) {
2396 /* Bypass translator if we're writing format in the raw write format. This
2397 allows mixing of native / non-native formats */
2398 if (fr->subclass == chan->rawwriteformat)
2401 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2404 queue_frame_to_spies(chan, f, SPY_WRITE);
2406 if (chan->monitor && chan->monitor->write_stream) {
2407 #ifndef MONITOR_CONSTANT_DELAY
2408 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2410 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2411 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2412 chan->outsmpl += jump + 4 * f->samples;
2414 chan->outsmpl += f->samples;
2416 int jump = chan->insmpl - chan->outsmpl;
2417 if (jump - MONITOR_DELAY >= 0) {
2418 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2419 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2420 chan->outsmpl += jump;
2422 chan->outsmpl += f->samples;
2424 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2425 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2426 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2430 res = chan->tech->write(chan, f);
2438 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2439 /* Consider a write failure to force a soft hangup */
2441 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2443 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
2444 chan->fout &= 0x80000000;
2448 ast_mutex_unlock(&chan->lock);
2452 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2453 struct ast_trans_pvt **trans, const int direction)
2458 /* Make sure we only consider audio */
2459 fmt &= AST_FORMAT_AUDIO_MASK;
2461 native = chan->nativeformats;
2462 /* Find a translation path from the native format to one of the desired formats */
2465 res = ast_translator_best_choice(&fmt, &native);
2468 res = ast_translator_best_choice(&native, &fmt);
2471 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2472 ast_getformatname(native), ast_getformatname(fmt));
2476 /* Now we have a good choice for both. */
2477 ast_mutex_lock(&chan->lock);
2478 *rawformat = native;
2479 /* User perspective is fmt */
2481 /* Free any read translation we have right now */
2483 ast_translator_free_path(*trans);
2484 /* Build a translation path from the raw format to the desired format */
2487 *trans = ast_translator_build_path(*format, *rawformat);
2490 *trans = ast_translator_build_path(*rawformat, *format);
2491 ast_mutex_unlock(&chan->lock);
2493 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2494 direction ? "write" : "read", ast_getformatname(fmt));
2498 int ast_set_read_format(struct ast_channel *chan, int fmt)
2500 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2501 &chan->readtrans, 0);
2504 int ast_set_write_format(struct ast_channel *chan, int fmt)
2506 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2507 &chan->writetrans, 1);
2510 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)
2514 struct ast_channel *chan;
2515 struct ast_frame *f;
2518 chan = ast_request(type, format, data, &cause);
2522 ast_set_variables(chan, oh->vars);
2523 if (oh->cid_num && *oh->cid_num && oh->cid_name && *oh->cid_name)
2524 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2525 if (oh->parent_channel)
2526 ast_channel_inherit_variables(oh->parent_channel, chan);
2528 ast_cdr_setaccount(chan, oh->account);
2530 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2532 if (!ast_call(chan, data, 0)) {
2533 res = 1; /* in case chan->_state is already AST_STATE_UP */
2534 while (timeout && (chan->_state != AST_STATE_UP)) {
2535 res = ast_waitfor(chan, timeout);
2537 /* Something not cool, or timed out */
2540 /* If done, break out */
2547 state = AST_CONTROL_HANGUP;
2551 if (f->frametype == AST_FRAME_CONTROL) {
2552 if (f->subclass == AST_CONTROL_RINGING)
2553 state = AST_CONTROL_RINGING;
2554 else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
2555 state = f->subclass;
2558 } else if (f->subclass == AST_CONTROL_ANSWER) {
2559 state = f->subclass;
2562 } else if (f->subclass == AST_CONTROL_PROGRESS) {
2564 } else if (f->subclass == -1) {
2565 /* Ignore -- just stopping indications */
2567 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2573 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2575 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2577 case AST_CAUSE_BUSY:
2578 state = AST_CONTROL_BUSY;
2580 case AST_CAUSE_CONGESTION:
2581 state = AST_CONTROL_CONGESTION;
2588 if (oh->context && *oh->context)
2589 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2590 if (oh->exten && *oh->exten)
2591 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2593 chan->priority = oh->priority;
2595 if (chan->_state == AST_STATE_UP)
2596 state = AST_CONTROL_ANSWER;
2600 if (chan && res <= 0) {
2601 if (!chan->cdr && (chan->cdr = ast_cdr_alloc())) {
2602 ast_cdr_init(chan->cdr, chan);
2606 snprintf(tmp, 256, "%s/%s", type, (char *)data);
2607 ast_cdr_setapp(chan->cdr,"Dial",tmp);
2608 ast_cdr_update(chan);
2609 ast_cdr_start(chan->cdr);
2610 ast_cdr_end(chan->cdr);
2611 /* If the cause wasn't handled properly */
2612 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2613 ast_cdr_failed(chan->cdr);
2621 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2623 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2626 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2628 struct chanlist *chan;
2629 struct ast_channel *c;
2637 *cause = AST_CAUSE_NOTDEFINED;
2639 if (AST_LIST_LOCK(&channels)) {
2640 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2644 AST_LIST_TRAVERSE(&backends, chan, list) {
2645 if (strcasecmp(type, chan->tech->type))
2648 capabilities = chan->tech->capabilities;
2650 res = ast_translator_best_choice(&fmt, &capabilities);
2652 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2653 AST_LIST_UNLOCK(&channels);
2656 AST_LIST_UNLOCK(&channels);
2657 if (!chan->tech->requester)
2660 if (!(c = chan->tech->requester(type, capabilities, data, cause)))
2663 if (c->_state == AST_STATE_DOWN) {
2664 manager_event(EVENT_FLAG_CALL, "Newchannel",
2668 "CallerIDName: %s\r\n"
2670 c->name, ast_state2str(c->_state),
2671 c->cid.cid_num ? c->cid.cid_num : "<unknown>",
2672 c->cid.cid_name ? c->cid.cid_name : "<unknown>",
2678 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2679 *cause = AST_CAUSE_NOSUCHDRIVER;
2680 AST_LIST_UNLOCK(&channels);
2685 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2687 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2688 If the remote end does not answer within the timeout, then do NOT hang up, but
2691 /* Stop if we're a zombie or need a soft hangup */
2692 ast_mutex_lock(&chan->lock);
2693 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan))
2694 if (chan->tech->call)
2695 res = chan->tech->call(chan, addr, timeout);
2696 ast_mutex_unlock(&chan->lock);
2701 \brief Transfer a call to dest, if the channel supports transfer
2705 \arg the manager interface
2707 int ast_transfer(struct ast_channel *chan, char *dest)
2711 /* Stop if we're a zombie or need a soft hangup */
2712 ast_mutex_lock(&chan->lock);
2713 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2714 if (chan->tech->transfer) {
2715 res = chan->tech->transfer(chan, dest);
2721 ast_mutex_unlock(&chan->lock);
2725 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2731 /* XXX Merge with full version? XXX */
2732 /* Stop if we're a zombie or need a soft hangup */
2733 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2739 d = ast_waitstream(c, AST_DIGIT_ANY);
2743 d = ast_waitfordigit(c, to);
2745 d = ast_waitfordigit(c, to);
2753 if (!strchr(enders, d))
2755 if (strchr(enders, d) || (pos >= len)) {
2765 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2771 /* Stop if we're a zombie or need a soft hangup */
2772 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2778 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2782 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2784 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2796 if (!strchr(enders, d))
2798 if (strchr(enders, d) || (pos >= len)) {
2808 int ast_channel_supports_html(struct ast_channel *chan)
2810 if (chan->tech->send_html)
2815 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2817 if (chan->tech->send_html)
2818 return chan->tech->send_html(chan, subclass, data, datalen);
2822 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2824 if (chan->tech->send_html)
2825 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2829 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2834 /* Set up translation from the chan to the peer */
2835 src = chan->nativeformats;
2836 dst = peer->nativeformats;
2837 if (ast_translator_best_choice(&dst, &src) < 0) {
2838 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2842 /* if the best path is not 'pass through', then
2843 transcoding is needed; if desired, force transcode path
2844 to use SLINEAR between channels */
2845 if ((src != dst) && ast_opt_transcode_via_slin)
2846 dst = AST_FORMAT_SLINEAR;
2847 if (ast_set_read_format(chan, dst) < 0) {
2848 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2851 if (ast_set_write_format(peer, dst) < 0) {
2852 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2856 /* Set up translation from the peer to the chan */
2857 src = peer->nativeformats;
2858 dst = chan->nativeformats;
2859 if (ast_translator_best_choice(&dst, &src) < 0) {
2860 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2863 /* if the best path is not 'pass through', then
2864 transcoding is needed; if desired, force transcode path
2865 to use SLINEAR between channels */
2866 if ((src != dst) && ast_opt_transcode_via_slin)
2867 dst = AST_FORMAT_SLINEAR;
2868 if (ast_set_read_format(peer, dst) < 0) {
2869 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2872 if (ast_set_write_format(chan, dst) < 0) {
2873 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2879 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2881 struct ast_frame null = { AST_FRAME_NULL, };
2884 if (original == clone) {
2885 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2888 ast_mutex_lock(&original->lock);
2889 while(ast_mutex_trylock(&clone->lock)) {
2890 ast_mutex_unlock(&original->lock);
2892 ast_mutex_lock(&original->lock);
2894 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
2895 clone->name, original->name);
2896 if (original->masq) {
2897 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2898 original->masq->name, original->name);
2899 } else if (clone->masqr) {
2900 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2901 clone->name, clone->masqr->name);
2903 original->masq = clone;
2904 clone->masqr = original;
2905 ast_queue_frame(original, &null);
2906 ast_queue_frame(clone, &null);
2907 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
2910 ast_mutex_unlock(&clone->lock);
2911 ast_mutex_unlock(&original->lock);
2915 void ast_change_name(struct ast_channel *chan, char *newname)
2917 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
2918 ast_string_field_set(chan, name, newname);
2921 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2923 struct ast_var_t *current, *newvar;
2924 const char *varname;
2926 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2929 varname = ast_var_full_name(current);
2933 if (varname[0] == '_') {
2935 if (varname[1] == '_')
2941 newvar = ast_var_assign(&varname[1], ast_var_value(current));
2943 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2945 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2949 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2951 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2953 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2958 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2965 \brief Clone channel variables from 'clone' channel into 'original' channel
2967 All variables except those related to app_groupcount are cloned.
2968 Variables are actually _removed_ from 'clone' channel, presumably
2969 because it will subsequently be destroyed.
2971 \note Assumes locks will be in place on both channels when called.
2973 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2975 struct ast_var_t *varptr;
2977 /* we need to remove all app_groupcount related variables from the original
2978 channel before merging in the clone's variables; any groups assigned to the
2979 original channel should be released, only those assigned to the clone
2983 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2984 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2985 AST_LIST_REMOVE(&original->varshead, varptr, entries);
2986 ast_var_delete(varptr);
2989 AST_LIST_TRAVERSE_SAFE_END;
2991 /* Append variables from clone channel into original channel */
2992 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2993 if (AST_LIST_FIRST(&clone->varshead))
2994 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2998 \brief Masquerade a channel
3000 \note Assumes channel will be locked when called
3002 int ast_do_masquerade(struct ast_channel *original)
3007 struct ast_frame *cur, *prev;
3008 const struct ast_channel_tech *t;
3010 struct ast_callerid tmpcid;
3011 struct ast_channel *clone = original->masq;
3012 int rformat = original->readformat;
3013 int wformat = original->writeformat;
3019 if (option_debug > 3)
3020 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3021 clone->name, clone->_state, original->name, original->_state);
3023 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3024 the clone channel into the original channel. Start by killing off the original
3025 channel's backend. I'm not sure we're going to keep this function, because
3026 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3028 /* We need the clone's lock, too */
3029 ast_mutex_lock(&clone->lock);
3031 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3033 /* Having remembered the original read/write formats, we turn off any translation on either
3035 free_translation(clone);
3036 free_translation(original);
3039 /* Unlink the masquerade */
3040 original->masq = NULL;
3041 clone->masqr = NULL;
3043 /* Save the original name */
3044 ast_copy_string(orig, original->name, sizeof(orig));
3045 /* Save the new name */
3046 ast_copy_string(newn, clone->name, sizeof(newn));
3047 /* Create the masq name */
3048 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3050 /* Copy the name from the clone channel */
3051 ast_string_field_set(original, name, newn);
3053 /* Mangle the name of the clone channel */
3054 ast_string_field_set(clone, name, masqn);
3056 /* Notify any managers of the change, first the masq then the other */
3057 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3058 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3060 /* Swap the technologies */
3062 original->tech = clone->tech;
3065 t_pvt = original->tech_pvt;
3066 original->tech_pvt = clone->tech_pvt;
3067 clone->tech_pvt = t_pvt;
3069 /* Swap the readq's */
3070 cur = original->readq;
3071 original->readq = clone->readq;
3074 /* Swap the alertpipes */
3075 for (i = 0; i < 2; i++) {
3076 x = original->alertpipe[i];
3077 original->alertpipe[i] = clone->alertpipe[i];
3078 clone->alertpipe[i] = x;
3081 /* Swap the raw formats */
3082 x = original->rawreadformat;
3083 original->rawreadformat = clone->rawreadformat;
3084 clone->rawreadformat = x;
3085 x = original->rawwriteformat;
3086 original->rawwriteformat = clone->rawwriteformat;
3087 clone->rawwriteformat = x;
3089 /* Save any pending frames on both sides. Start by counting
3090 * how many we're going to need... */
3093 for (cur = clone->readq; cur; cur = cur->next) {
3097 /* If we had any, prepend them to the ones already in the queue, and
3098 * load up the alertpipe */
3100 prev->next = original->readq;
3101 original->readq = clone->readq;
3102 clone->readq = NULL;
3103 if (original->alertpipe[1] > -1) {
3104 for (i = 0; i < x; i++)
3105 write(original->alertpipe[1], &x, sizeof(x));
3108 clone->_softhangup = AST_SOFTHANGUP_DEV;
3111 /* And of course, so does our current state. Note we need not
3112 call ast_setstate since the event manager doesn't really consider
3113 these separate. We do this early so that the clone has the proper
3114 state of the original channel. */
3115 origstate = original->_state;
3116 original->_state = clone->_state;
3117 clone->_state = origstate;
3119 if (clone->tech->fixup){
3120 res = clone->tech->fixup(original, clone);
3122 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3125 /* Start by disconnecting the original's physical side */
3126 if (clone->tech->hangup)
3127 res = clone->tech->hangup(clone);
3129 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
3130 ast_mutex_unlock(&clone->lock);
3134 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3135 /* Mangle the name of the clone channel */
3136 ast_string_field_set(clone, name, zombn);
3137 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3139 /* Update the type. */
3140 t_pvt = original->monitor;
3141 original->monitor = clone->monitor;
3142 clone->monitor = t_pvt;
3144 /* Keep the same language. */
3145 ast_string_field_set(original, language, clone->language);
3146 /* Copy the FD's other than the generator fd */
3147 for (x = 0; x < AST_MAX_FDS; x++) {
3148 if (x != AST_GENERATOR_FD)
3149 original->fds[x] = clone->fds[x];
3151 /* Move data stores over */
3152 if (AST_LIST_FIRST(&clone->datastores))
3153 AST_LIST_INSERT_TAIL(&original->datastores, AST_LIST_FIRST(&clone->datastores), entry);
3154 AST_LIST_HEAD_INIT_NOLOCK(&clone->datastores);
3156 clone_variables(original, clone);
3157 AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3158 /* Presense of ADSI capable CPE follows clone */
3159 original->adsicpe = clone->adsicpe;
3160 /* Bridge remains the same */
3161 /* CDR fields remain the same */
3162 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3163 /* Application and data remain the same */
3164 /* Clone exception becomes real one, as with fdno */
3165 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3166 original->fdno = clone->fdno;
3167 /* Schedule context remains the same */
3168 /* Stream stuff stays the same */
3169 /* Keep the original state. The fixup code will need to work with it most likely */
3171 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3173 tmpcid = original->cid;
3174 original->cid = clone->cid;
3175 clone->cid = tmpcid;
3177 /* Restore original timing file descriptor */
3178 original->fds[AST_TIMING_FD] = original->timingfd;
3180 /* Our native formats are different now */
3181 original->nativeformats = clone->nativeformats;
3183 /* Context, extension, priority, app data, jump table, remain the same */
3184 /* pvt switches. pbx stays the same, as does next */
3186 /* Set the write format */
3187 ast_set_write_format(original, wformat);
3189 /* Set the read format */
3190 ast_set_read_format(original, rformat);
3192 /* Copy the music class */
3193 ast_string_field_set(original, musicclass, clone->musicclass);
3195 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3197 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3198 can fix up everything as best as possible */
3199 if (original->tech->fixup) {
3200 res = original->tech->fixup(clone, original);
3202 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3203 original->tech->type, original->name);
3204 ast_mutex_unlock(&clone->lock);
3208 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3209 original->tech->type, original->name);
3211 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3212 a zombie so nothing tries to touch it. If it's already been marked as a
3213 zombie, then free it now (since it already is considered invalid). */
3214 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3215 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3216 ast_mutex_unlock(&clone->lock);
3217 manager_event(EVENT_FLAG_CALL, "Hangup",
3221 "Cause-txt: %s\r\n",
3225 ast_cause2str(clone->hangupcause)
3227 ast_channel_free(clone);
3229 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3230 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3231 ast_queue_frame(clone, &ast_null_frame);
3232 ast_mutex_unlock(&clone->lock);
3235 /* Signal any blocker */
3236 if (ast_test_flag(original, AST_FLAG_BLOCKING))
3237 pthread_kill(original->blocker, SIGURG);
3238 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3242 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3245 if (chan->cid.cid_num)
3246 free(chan->cid.cid_num);
3247 if (ast_strlen_zero(callerid))
3248 chan->cid.cid_num = NULL;
3250 chan->cid.cid_num = strdup(callerid);
3253 if (chan->cid.cid_name)
3254 free(chan->cid.cid_name);
3255 if (ast_strlen_zero(calleridname))
3256 chan->cid.cid_name = NULL;
3258 chan->cid.cid_name = strdup(calleridname);
3261 if (chan->cid.cid_ani)
3262 free(chan->cid.cid_ani);
3263 if (ast_strlen_zero(ani))
3264 chan->cid.cid_ani = NULL;
3266 chan->cid.cid_ani = strdup(ani);
3269 ast_cdr_setcid(chan->cdr, chan);
3270 manager_event(EVENT_FLAG_CALL, "Newcallerid",
3273 "CallerIDName: %s\r\n"
3275 "CID-CallingPres: %d (%s)\r\n",
3276 chan->name, chan->cid.cid_num ?
3277 chan->cid.cid_num : "<Unknown>",
3278 chan->cid.cid_name ?
3279 chan->cid.cid_name : "<Unknown>",
3282 ast_describe_caller_presentation(chan->cid.cid_pres)
3286 int ast_setstate(struct ast_channel *chan, int state)
3288 int oldstate = chan->_state;
3290 if (oldstate == state)
3293 chan->_state = state;
3294 ast_device_state_changed_literal(chan->name);
3295 manager_event(EVENT_FLAG_CALL,
3296 (oldstate == AST_STATE_DOWN) ? "Newchannel" : "Newstate",
3300 "CallerIDName: %s\r\n"
3302 chan->name, ast_state2str(chan->_state),
3303 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
3304 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
3310 /*! \brief Find bridged channel */
3311 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3313 struct ast_channel *bridged;
3314 bridged = chan->_bridge;
3315 if (bridged && bridged->tech->bridged_channel)
3316 bridged = bridged->tech->bridged_channel(chan, bridged);
3320 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3322 int min = 0, sec = 0, check;
3324 check = ast_autoservice_start(peer);
3329 if (remain / 60 > 1) {
3337 if (!strcmp(sound,"timeleft")) { /* Queue support */
3338 ast_streamfile(chan, "vm-youhave", chan->language);
3339 ast_waitstream(chan, "");
3341 ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
3342 ast_streamfile(chan, "queue-minutes", chan->language);
3343 ast_waitstream(chan, "");
3346 ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
3347 ast_streamfile(chan, "queue-seconds", chan->language);
3348 ast_waitstream(chan, "");
3351 ast_streamfile(chan, sound, chan->language);
3352 ast_waitstream(chan, "");
3355 check = ast_autoservice_stop(peer);
3358 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3359 struct ast_bridge_config *config, struct ast_frame **fo,
3360 struct ast_channel **rc, struct timeval bridge_end)
3362 /* Copy voice back and forth between the two channels. */
3363 struct ast_channel *cs[3];
3364 struct ast_frame *f;
3365 struct ast_channel *who = NULL;
3366 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3367 int o0nativeformats;
3368 int o1nativeformats;
3376 pvt0 = c0->tech_pvt;
3377 pvt1 = c1->tech_pvt;
3378 o0nativeformats = c0->nativeformats;
3379 o1nativeformats = c1->nativeformats;
3380 watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3381 watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3384 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3385 (o0nativeformats != c0->nativeformats) ||
3386 (o1nativeformats != c1->nativeformats)) {
3387 /* Check for Masquerade, codec changes, etc */
3388 res = AST_BRIDGE_RETRY;
3391 if (bridge_end.tv_sec) {
3392 to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3394 res = AST_BRIDGE_RETRY;
3399 who = ast_waitfor_n(cs, 2, &to);
3401 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
3402 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3403 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3404 c0->_softhangup = 0;
3405 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3406 c1->_softhangup = 0;
3416 res = AST_BRIDGE_COMPLETE;
3417 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3421 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3422 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
3423 (f->subclass == AST_CONTROL_VIDUPDATE)) {
3424 ast_indicate(who == c0 ? c1 : c0, f->subclass);
3428 res = AST_BRIDGE_COMPLETE;
3429 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3433 if ((f->frametype == AST_FRAME_VOICE) ||
3434 (f->frametype == AST_FRAME_DTMF) ||
3435 (f->frametype == AST_FRAME_VIDEO) ||
3436 (f->frametype == AST_FRAME_IMAGE) ||
3437 (f->frametype == AST_FRAME_HTML) ||
3438 #if defined(T38_SUPPORT)
3439 (f->frametype == AST_FRAME_MODEM) ||
3441 (f->frametype == AST_FRAME_TEXT)) {
3442 if (f->frametype == AST_FRAME_DTMF) {
3443 if (((who == c0) && watch_c0_dtmf) ||
3444 ((who == c1) && watch_c1_dtmf)) {
3447 res = AST_BRIDGE_COMPLETE;
3448 ast_log(LOG_DEBUG, "Got DTMF on channel (%s)\n", who->name);
3455 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
3457 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
3461 ast_write((who == c0) ? c1 : c0, f);
3466 /* Swap who gets priority */
3474 /*! \brief Bridge two channels together */
3475 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3476 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
3478 struct ast_channel *who = NULL;
3479 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3482 int o0nativeformats;
3483 int o1nativeformats;
3484 long time_left_ms=0;
3485 struct timeval nexteventts = { 0, };
3486 char caller_warning = 0;
3487 char callee_warning = 0;
3491 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3492 c0->name, c0->_bridge->name);
3496 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3497 c1->name, c1->_bridge->name);
3501 /* Stop if we're a zombie or need a soft hangup */
3502 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3503 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3507 firstpass = config->firstpass;
3508 config->firstpass = 0;
3510 if (ast_tvzero(config->start_time))
3511 config->start_time = ast_tvnow();
3512 time_left_ms = config->timelimit;
3514 caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3515 callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3517 if (config->start_sound && firstpass) {
3519 bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3521 bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3524 /* Keep track of bridge */
3528 manager_event(EVENT_FLAG_CALL, "Link",
3534 "CallerID2: %s\r\n",
3535 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3537 o0nativeformats = c0->nativeformats;
3538 o1nativeformats = c1->nativeformats;
3540 if (config->timelimit) {
3541 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3542 if (caller_warning || callee_warning)
3543 nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
3546 for (/* ever */;;) {
3548 if (config->timelimit) {
3551 to = ast_tvdiff_ms(nexteventts, now);
3554 time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
3555 if (time_left_ms < to)
3558 if (time_left_ms <= 0) {
3559 if (caller_warning && config->end_sound)
3560 bridge_playfile(c0, c1, config->end_sound, 0);
3561 if (callee_warning && config->end_sound)
3562 bridge_playfile(c1, c0, config->end_sound, 0);
3571 if (time_left_ms >= 5000) {
3572 /* force the time left to round up if appropriate */
3573 if (caller_warning && config->warning_sound && config->play_warning)
3574 bridge_playfile(c0, c1, config->warning_sound,
3575 (time_left_ms + 500) / 1000);
3576 if (callee_warning && config->warning_sound && config->play_warning)
3577 bridge_playfile(c1, c0, config->warning_sound,
3578 (time_left_ms + 500) / 1000);
3580 if (config->warning_freq) {
3581 nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
3583 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3587 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3588 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3589 c0->_softhangup = 0;