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 */
38 #include <sys/ioctl.h>
40 #include <linux/zaptel.h>
43 #endif /* __linux__ */
45 #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 {
122 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
123 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
124 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
125 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
126 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
127 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
128 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
129 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
130 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
131 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
132 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
133 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
134 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
135 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
136 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
137 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
138 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
139 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
140 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
141 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
142 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
143 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
144 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
145 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
146 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
147 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
148 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
149 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
150 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
151 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
152 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
153 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
154 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
155 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
156 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
157 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
158 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
159 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
160 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
161 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
162 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
163 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
164 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
165 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
169 struct ast_variable *ast_channeltype_list(void)
172 struct ast_variable *var=NULL, *prev = NULL;
173 AST_LIST_TRAVERSE(&backends, cl, list) {
175 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description)))
178 var = ast_variable_new(cl->tech->type, cl->tech->description);
185 static int show_channeltypes(int fd, int argc, char *argv[])
187 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
191 ast_cli(fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
192 ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
193 if (AST_LIST_LOCK(&channels)) {
194 ast_log(LOG_WARNING, "Unable to lock channel list\n");
197 AST_LIST_TRAVERSE(&backends, cl, list) {
198 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description,
199 (cl->tech->devicestate) ? "yes" : "no",
200 (cl->tech->indicate) ? "yes" : "no",
201 (cl->tech->transfer) ? "yes" : "no");
204 AST_LIST_UNLOCK(&channels);
205 ast_cli(fd, "----------\n%d channel drivers registered.\n", count_chan);
206 return RESULT_SUCCESS;
212 static int show_channeltype(int fd, int argc, char *argv[])
214 struct chanlist *cl = NULL;
217 return RESULT_SHOWUSAGE;
219 if (AST_LIST_LOCK(&channels)) {
220 ast_log(LOG_WARNING, "Unable to lock channel list\n");
221 return RESULT_FAILURE;
224 AST_LIST_TRAVERSE(&backends, cl, list) {
225 if (!strncasecmp(cl->tech->type, argv[2], strlen(cl->tech->type))) {
232 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[2]);
233 AST_LIST_UNLOCK(&channels);
234 return RESULT_FAILURE;
238 "-- Info about channel driver: %s --\n"
239 " Device State: %s\n"
242 " Capabilities: %d\n"
245 " Image Support: %s\n"
246 " Text Support: %s\n",
248 (cl->tech->devicestate) ? "yes" : "no",
249 (cl->tech->indicate) ? "yes" : "no",
250 (cl->tech->transfer) ? "yes" : "no",
251 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
252 (cl->tech->send_digit) ? "yes" : "no",
253 (cl->tech->send_html) ? "yes" : "no",
254 (cl->tech->send_image) ? "yes" : "no",
255 (cl->tech->send_text) ? "yes" : "no"
259 AST_LIST_UNLOCK(&channels);
260 return RESULT_SUCCESS;
263 static char *complete_channeltypes(const char *line, const char *word, int pos, int state)
273 wordlen = strlen(word);
275 AST_LIST_TRAVERSE(&backends, cl, list) {
276 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
277 ret = strdup(cl->tech->type);
285 static char show_channeltypes_usage[] =
286 "Usage: show channeltypes\n"
287 " Shows available channel types registered in your Asterisk server.\n";
289 static char show_channeltype_usage[] =
290 "Usage: show channeltype <name>\n"
291 " Show details about the specified channel type, <name>.\n";
293 static struct ast_cli_entry cli_show_channeltypes =
294 { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
296 static struct ast_cli_entry cli_show_channeltype =
297 { { "show", "channeltype", NULL }, show_channeltype, "Give more details on that channel type", show_channeltype_usage, complete_channeltypes };
299 /*! \brief Checks to see if a channel is needing hang up */
300 int ast_check_hangup(struct ast_channel *chan)
302 if (chan->_softhangup) /* yes if soft hangup flag set */
304 if (!chan->tech_pvt) /* yes if no technology private data */
306 if (!chan->whentohangup) /* no if no hangup scheduled */
308 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
310 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
314 static int ast_check_hangup_locked(struct ast_channel *chan)
317 ast_channel_lock(chan);
318 res = ast_check_hangup(chan);
319 ast_channel_unlock(chan);
323 /*! \brief Initiate system shutdown */
324 void ast_begin_shutdown(int hangup)
326 struct ast_channel *c;
329 AST_LIST_LOCK(&channels);
330 AST_LIST_TRAVERSE(&channels, c, chan_list)
331 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
332 AST_LIST_UNLOCK(&channels);
336 /*! \brief returns number of active/allocated channels */
337 int ast_active_channels(void)
339 struct ast_channel *c;
341 AST_LIST_LOCK(&channels);
342 AST_LIST_TRAVERSE(&channels, c, chan_list)
344 AST_LIST_UNLOCK(&channels);
348 /*! \brief Cancel a shutdown in progress */
349 void ast_cancel_shutdown(void)
354 /*! \brief Returns non-zero if Asterisk is being shut down */
355 int ast_shutting_down(void)
357 return shutting_down;
360 /*! \brief Set when to hangup channel */
361 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
363 chan->whentohangup = offset ? time(NULL) + offset : 0;
364 ast_queue_frame(chan, &ast_null_frame);
368 /*! \brief Compare a offset with when to hangup channel */
369 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
373 if (chan->whentohangup == 0) {
374 return (offset == 0) ? 0 : -1;
376 if (offset == 0) /* XXX why is this special ? */
379 whentohangup = offset + time (NULL);
380 if (chan->whentohangup < whentohangup)
382 else if (chan->whentohangup == whentohangup)
390 /*! \brief Register a new telephony channel in Asterisk */
391 int ast_channel_register(const struct ast_channel_tech *tech)
393 struct chanlist *chan;
395 AST_LIST_LOCK(&channels);
397 AST_LIST_TRAVERSE(&backends, chan, list) {
398 if (!strcasecmp(tech->type, chan->tech->type)) {
399 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
400 AST_LIST_UNLOCK(&channels);
405 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
406 AST_LIST_UNLOCK(&channels);
410 AST_LIST_INSERT_HEAD(&backends, chan, list);
413 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
415 if (option_verbose > 1)
416 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
417 chan->tech->description);
419 AST_LIST_UNLOCK(&channels);
423 void ast_channel_unregister(const struct ast_channel_tech *tech)
425 struct chanlist *chan;
428 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
430 AST_LIST_LOCK(&channels);
432 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
433 if (chan->tech == tech) {
434 AST_LIST_REMOVE_CURRENT(&backends, list);
436 if (option_verbose > 1)
437 ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
441 AST_LIST_TRAVERSE_SAFE_END
443 AST_LIST_UNLOCK(&channels);
446 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
448 struct chanlist *chanls;
449 const struct ast_channel_tech *ret = NULL;
451 if (AST_LIST_LOCK(&channels)) {
452 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
456 AST_LIST_TRAVERSE(&backends, chanls, list) {
457 if (!strcasecmp(name, chanls->tech->type)) {
463 AST_LIST_UNLOCK(&channels);
468 /*! \brief Gives the string form of a given hangup cause */
469 const char *ast_cause2str(int cause)
473 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
474 if (causes[x].cause == cause)
475 return causes[x].desc;
481 /*! \brief Convert a symbolic hangup cause to number */
482 int ast_str2cause(const char *name)
486 for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
487 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
488 return causes[x].cause;
493 /*! \brief Gives the string form of a given channel state */
494 char *ast_state2str(int state)
496 /* XXX Not reentrant XXX */
497 static char localtmp[256];
501 case AST_STATE_RESERVED:
503 case AST_STATE_OFFHOOK:
505 case AST_STATE_DIALING:
509 case AST_STATE_RINGING:
516 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
521 /*! \brief Gives the string form of a given transfer capability */
522 char *ast_transfercapability2str(int transfercapability)
524 switch(transfercapability) {
525 case AST_TRANS_CAP_SPEECH:
527 case AST_TRANS_CAP_DIGITAL:
529 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
530 return "RESTRICTED_DIGITAL";
531 case AST_TRANS_CAP_3_1K_AUDIO:
533 case AST_TRANS_CAP_DIGITAL_W_TONES:
534 return "DIGITAL_W_TONES";
535 case AST_TRANS_CAP_VIDEO:
542 /*! \brief Pick the best codec */
543 int ast_best_codec(int fmts)
545 /* This just our opinion, expressed in code. We are asked to choose
546 the best codec to use, given no information */
550 /*! Okay, ulaw is used by all telephony equipment, so start with it */
552 /*! Unless of course, you're a silly European, so then prefer ALAW */
554 /*! Okay, well, signed linear is easy to translate into other stuff */
556 /*! G.726 is standard ADPCM */
558 /*! ADPCM has great sound quality and is still pretty easy to translate */
560 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
561 translate and sounds pretty good */
563 /*! iLBC is not too bad */
565 /*! Speex is free, but computationally more expensive than GSM */
567 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
570 /*! G.729a is faster than 723 and slightly less expensive */
572 /*! Down to G.723.1 which is proprietary but at least designed for voice */
577 /* Find the first preferred codec in the format given */
578 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
581 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
585 static const struct ast_channel_tech null_tech = {
587 .description = "Null channel (should not see this)",
590 /*! \brief Create a new channel structure */
591 struct ast_channel *ast_channel_alloc(int needqueue)
593 struct ast_channel *tmp;
596 struct varshead *headp;
598 /* If shutting down, don't allocate any new channels */
600 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
604 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
607 if (!(tmp->sched = sched_context_create())) {
608 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
613 ast_string_field_init(tmp, 128);
615 /* Don't bother initializing the last two FD here, because they
616 will *always* be set just a few lines down (AST_TIMING_FD,
618 for (x=0; x<AST_MAX_FDS - 2; x++)
622 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
623 if (tmp->timingfd > -1) {
624 /* Check if timing interface supports new
627 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
635 if (pipe(tmp->alertpipe)) {
636 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
640 flags = fcntl(tmp->alertpipe[0], F_GETFL);
641 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
642 flags = fcntl(tmp->alertpipe[1], F_GETFL);
643 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
645 } else /* Make sure we've got it done right if they don't */
646 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
648 /* Always watch the alertpipe */
649 tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
650 /* And timing pipe */
651 tmp->fds[AST_TIMING_FD] = tmp->timingfd;
652 ast_string_field_set(tmp, name, "**Unknown**");
654 tmp->_state = AST_STATE_DOWN;
658 tmp->fin = global_fin;
659 tmp->fout = global_fout;
660 ast_mutex_lock(&uniquelock);
661 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
662 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), uniqueint++);
664 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, (long) time(NULL), uniqueint++);
665 ast_mutex_unlock(&uniquelock);
666 headp = &tmp->varshead;
667 ast_mutex_init(&tmp->lock);
668 AST_LIST_HEAD_INIT_NOLOCK(headp);
669 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
670 strcpy(tmp->context, "default");
671 ast_string_field_set(tmp, language, defaultlanguage);
672 strcpy(tmp->exten, "s");
674 tmp->amaflags = ast_default_amaflags;
675 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
677 tmp->tech = &null_tech;
679 AST_LIST_LOCK(&channels);
680 AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
681 AST_LIST_UNLOCK(&channels);
685 /*! \brief Queue an outgoing media frame */
686 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
689 struct ast_frame *prev, *cur;
693 /* Build us a copy and free the original one */
694 if (!(f = ast_frdup(fin))) {
695 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
698 ast_channel_lock(chan);
700 for (cur = chan->readq; cur; cur = cur->next) {
701 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
702 /* Don't bother actually queueing anything after a hangup */
704 ast_channel_unlock(chan);
710 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
711 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
712 if (fin->frametype != AST_FRAME_VOICE) {
713 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
716 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
718 ast_channel_unlock(chan);
726 if (chan->alertpipe[1] > -1) {
727 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
728 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
729 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
731 } else if (chan->timingfd > -1) {
732 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
734 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
735 pthread_kill(chan->blocker, SIGURG);
737 ast_channel_unlock(chan);
741 /*! \brief Queue a hangup frame for channel */
742 int ast_queue_hangup(struct ast_channel *chan)
744 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
745 /* Yeah, let's not change a lock-critical value without locking */
746 if (!ast_channel_trylock(chan)) {
747 chan->_softhangup |= AST_SOFTHANGUP_DEV;
748 ast_channel_unlock(chan);
750 return ast_queue_frame(chan, &f);
753 /*! \brief Queue a control frame */
754 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
756 struct ast_frame f = { AST_FRAME_CONTROL, };
758 f.subclass = control;
760 return ast_queue_frame(chan, &f);
763 /*! \brief Queue a control frame with payload */
764 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
765 const void *data, size_t datalen)
767 struct ast_frame f = { AST_FRAME_CONTROL, };
769 f.subclass = control;
770 f.data = (void *) data;
773 return ast_queue_frame(chan, &f);
776 /*! \brief Set defer DTMF flag on channel */
777 int ast_channel_defer_dtmf(struct ast_channel *chan)
782 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
783 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
788 /*! \brief Unset defer DTMF flag on channel */
789 void ast_channel_undefer_dtmf(struct ast_channel *chan)
792 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
796 * \brief Helper function to find channels.
798 * It supports these modes:
800 * prev != NULL : get channel next in list after prev
801 * name != NULL : get channel with matching name
802 * name != NULL && namelen != 0 : get channel whose name starts with prefix
803 * exten != NULL : get channel whose exten or macroexten matches
804 * context != NULL && exten != NULL : get channel whose context or macrocontext
806 * It returns with the channel's lock held. If getting the individual lock fails,
807 * unlock and retry quickly up to 10 times, then give up.
809 * \note XXX Note that this code has cost O(N) because of the need to verify
810 * that the object is still on the global list.
812 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
813 * can only be done with the lock held or someone could delete the
814 * object while we work on it. This causes some ugliness in the code.
815 * Note that removing the first ast_log() may be harmful, as it would
816 * shorten the retry period and possibly cause failures.
817 * We should definitely go for a better scheme that is deadlock-free.
819 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
820 const char *name, const int namelen,
821 const char *context, const char *exten)
823 const char *msg = prev ? "deadlock" : "initial deadlock";
825 struct ast_channel *c;
827 for (retries = 0; retries < 10; retries++) {
829 AST_LIST_LOCK(&channels);
830 AST_LIST_TRAVERSE(&channels, c, chan_list) {
831 if (prev) { /* look for next item */
832 if (c != prev) /* not this one */
834 /* found, prepare to return c->next */
835 c = AST_LIST_NEXT(c, chan_list);
836 } else if (name) { /* want match by name */
837 if ( (!namelen && strcasecmp(c->name, name)) ||
838 (namelen && strncasecmp(c->name, name, namelen)) )
839 continue; /* name match failed */
841 if (context && strcasecmp(c->context, context) &&
842 strcasecmp(c->macrocontext, context))
843 continue; /* context match failed */
844 if (strcasecmp(c->exten, exten) &&
845 strcasecmp(c->macroexten, exten))
846 continue; /* exten match failed */
848 /* if we get here, c points to the desired record */
851 /* exit if chan not found or mutex acquired successfully */
852 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
853 done = c == NULL || ast_channel_trylock(c) == 0;
855 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
856 AST_LIST_UNLOCK(&channels);
859 usleep(1); /* give other threads a chance before retrying */
862 * c is surely not null, but we don't have the lock so cannot
865 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n",
871 /*! \brief Browse channels in use */
872 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
874 return channel_find_locked(prev, NULL, 0, NULL, NULL);
877 /*! \brief Get channel by name and lock it */
878 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
880 return channel_find_locked(NULL, name, 0, NULL, NULL);
883 /*! \brief Get channel by name prefix and lock it */
884 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
886 return channel_find_locked(NULL, name, namelen, NULL, NULL);
889 /*! \brief Get next channel by name prefix and lock it */
890 struct ast_channel *ast_walk_channel_by_name_prefix_locked(struct ast_channel *chan, const char *name, const int namelen)
892 return channel_find_locked(chan, name, namelen, NULL, NULL);
895 /*! \brief Get channel by exten (and optionally context) and lock it */
896 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
898 return channel_find_locked(NULL, NULL, 0, context, exten);
901 /*! \brief Wait, look for hangups and condition arg */
902 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
907 if (cond && ((*cond)(data) == 0))
909 ms = ast_waitfor(chan, ms);
922 /*! \brief Wait, look for hangups */
923 int ast_safe_sleep(struct ast_channel *chan, int ms)
925 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
928 static void free_cid(struct ast_callerid *cid)
939 free(cid->cid_rdnis);
942 /*! \brief Free a channel structure */
943 void ast_channel_free(struct ast_channel *chan)
946 struct ast_var_t *vardata;
947 struct ast_frame *f, *fp;
948 struct varshead *headp;
949 struct ast_datastore *datastore = NULL;
950 char name[AST_CHANNEL_NAME];
952 headp=&chan->varshead;
954 AST_LIST_LOCK(&channels);
955 AST_LIST_REMOVE(&channels, chan, chan_list);
956 /* Lock and unlock the channel just to be sure nobody
957 has it locked still */
958 ast_channel_lock(chan);
959 ast_channel_unlock(chan);
960 if (chan->tech_pvt) {
961 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
962 free(chan->tech_pvt);
966 sched_context_destroy(chan->sched);
968 ast_copy_string(name, chan->name, sizeof(name));
970 /* Stop monitoring */
972 chan->monitor->stop( chan, 0 );
975 /* If there is native format music-on-hold state, free it */
976 if(chan->music_state)
977 ast_moh_cleanup(chan);
979 /* Free translators */
981 ast_translator_free_path(chan->readtrans);
982 if (chan->writetrans)
983 ast_translator_free_path(chan->writetrans);
985 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
986 free_cid(&chan->cid);
987 ast_mutex_destroy(&chan->lock);
988 /* Close pipes if appropriate */
989 if ((fd = chan->alertpipe[0]) > -1)
991 if ((fd = chan->alertpipe[1]) > -1)
993 if ((fd = chan->timingfd) > -1)
1003 /* Get rid of each of the data stores on the channel */
1004 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1005 /* Free the data store */
1006 ast_channel_datastore_free(datastore);
1007 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1009 /* loop over the variables list, freeing all data and deleting list items */
1010 /* no need to lock the list, as the channel is already locked */
1012 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1013 ast_var_delete(vardata);
1015 ast_string_field_free_all(chan);
1017 AST_LIST_UNLOCK(&channels);
1019 ast_device_state_changed_literal(name);
1022 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1024 struct ast_datastore *datastore = NULL;
1026 /* Make sure we at least have type so we can identify this */
1031 /* Allocate memory for datastore and clear it */
1032 datastore = ast_calloc(1, sizeof(*datastore));
1033 if (datastore == NULL) {
1037 datastore->info = info;
1039 datastore->uid = ast_strdup(uid);
1044 int ast_channel_datastore_free(struct ast_datastore *datastore)
1048 /* Using the destroy function (if present) destroy the data */
1049 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1050 datastore->info->destroy(datastore->data);
1051 datastore->data = NULL;
1054 /* Free allocated UID memory */
1055 if (datastore->uid != NULL) {
1056 free(datastore->uid);
1057 datastore->uid = NULL;
1060 /* Finally free memory used by ourselves */
1066 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1070 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1075 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1077 struct ast_datastore *datastore2 = NULL;
1080 /* Find our position and remove ourselves */
1081 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1082 if (datastore2 == datastore) {
1083 AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1088 AST_LIST_TRAVERSE_SAFE_END
1093 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1095 struct ast_datastore *datastore = NULL;
1100 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1101 if (datastore->info == info) {
1102 if (uid != NULL && datastore->uid != NULL) {
1103 if (!strcasecmp(uid, datastore->uid)) {
1104 /* Matched by type AND uid */
1108 /* Matched by type at least */
1113 AST_LIST_TRAVERSE_SAFE_END
1118 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1120 if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1121 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1122 spy->type, chan->name);
1126 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1127 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1128 ast_getformatname(spy->read_queue.format));
1132 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1133 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1134 ast_getformatname(spy->write_queue.format));
1138 if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1139 ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1140 (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1141 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1142 ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1147 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1151 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1152 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1154 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1157 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1158 ast_cond_init(&spy->trigger, NULL);
1159 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1160 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1163 ast_log(LOG_DEBUG, "Spy %s added to channel %s\n",
1164 spy->type, chan->name);
1169 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1171 struct ast_channel_spy *spy;
1176 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1177 ast_mutex_lock(&spy->lock);
1178 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1179 spy->status = CHANSPY_STOP;
1180 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1181 ast_cond_signal(&spy->trigger);
1183 ast_mutex_unlock(&spy->lock);
1187 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1189 ast_cond_wait(&spy->trigger, &spy->lock);
1192 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1194 struct ast_frame *f;
1199 AST_LIST_REMOVE(&chan->spies->list, spy, list);
1201 ast_mutex_lock(&spy->lock);
1203 for (f = spy->read_queue.head; f; f = spy->read_queue.head) {
1204 spy->read_queue.head = f->next;
1207 for (f = spy->write_queue.head; f; f = spy->write_queue.head) {
1208 spy->write_queue.head = f->next;
1212 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1213 ast_cond_destroy(&spy->trigger);
1215 ast_mutex_unlock(&spy->lock);
1217 ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n",
1218 spy->type, chan->name);
1220 if (AST_LIST_EMPTY(&chan->spies->list)) {
1221 if (chan->spies->read_translator.path)
1222 ast_translator_free_path(chan->spies->read_translator.path);
1223 if (chan->spies->write_translator.path)
1224 ast_translator_free_path(chan->spies->write_translator.path);
1230 static void detach_spies(struct ast_channel *chan)
1232 struct ast_channel_spy *spy;
1237 /* Marking the spies as done is sufficient. Chanspy or spy users will get the picture. */
1238 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1239 ast_mutex_lock(&spy->lock);
1240 if (spy->status == CHANSPY_RUNNING)
1241 spy->status = CHANSPY_DONE;
1242 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1243 ast_cond_signal(&spy->trigger);
1244 ast_mutex_unlock(&spy->lock);
1247 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list)
1248 ast_channel_spy_remove(chan, spy);
1249 AST_LIST_TRAVERSE_SAFE_END;
1252 /*! \brief Softly hangup a channel, don't lock */
1253 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1256 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1257 /* Inform channel driver that we need to be hung up, if it cares */
1258 chan->_softhangup |= cause;
1259 ast_queue_frame(chan, &ast_null_frame);
1260 /* Interrupt any poll call or such */
1261 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1262 pthread_kill(chan->blocker, SIGURG);
1266 /*! \brief Softly hangup a channel, lock */
1267 int ast_softhangup(struct ast_channel *chan, int cause)
1270 ast_channel_lock(chan);
1271 res = ast_softhangup_nolock(chan, cause);
1272 ast_channel_unlock(chan);
1276 enum spy_direction {
1281 #define SPY_QUEUE_SAMPLE_LIMIT 4000 /* half of one second */
1283 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1285 struct ast_frame *translated_frame = NULL;
1286 struct ast_channel_spy *spy;
1287 struct channel_spy_trans *trans;
1289 trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1291 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1292 struct ast_frame *last;
1293 struct ast_frame *f1; /* the frame to append */
1294 struct ast_channel_spy_queue *queue;
1296 ast_mutex_lock(&spy->lock);
1298 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1300 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1301 if (!translated_frame) {
1302 if (trans->path && (trans->last_format != f->subclass)) {
1303 ast_translator_free_path(trans->path);
1307 ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1308 ast_getformatname(f->subclass), chan->name);
1309 if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1310 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1311 ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1312 ast_mutex_unlock(&spy->lock);
1315 trans->last_format = f->subclass;
1318 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1319 ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1320 ast_getformatname(AST_FORMAT_SLINEAR));
1321 ast_mutex_unlock(&spy->lock);
1325 f1 = translated_frame;
1327 if (f->subclass != queue->format) {
1328 ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1329 spy->type, chan->name,
1330 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1331 ast_mutex_unlock(&spy->lock);
1336 /* duplicate and append f1 to the tail */
1339 for (last = queue->head; last && last->next; last = last->next)
1346 queue->samples += f->samples;
1348 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1349 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1350 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1351 case CHANSPY_TRIGGER_READ:
1352 if (dir == SPY_WRITE) {
1353 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1354 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1356 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1357 spy->type, chan->name);
1360 case CHANSPY_TRIGGER_WRITE:
1361 if (dir == SPY_READ) {
1362 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1363 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1365 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1366 spy->type, chan->name);
1371 ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1372 spy->type, chan->name);
1373 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1374 ast_cond_signal(&spy->trigger);
1377 ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1378 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1379 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1380 struct ast_frame *drop = queue->head;
1382 queue->samples -= drop->samples;
1383 queue->head = drop->next;
1388 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1389 case CHANSPY_TRIGGER_READ:
1390 if (dir == SPY_READ)
1391 ast_cond_signal(&spy->trigger);
1393 case CHANSPY_TRIGGER_WRITE:
1394 if (dir == SPY_WRITE)
1395 ast_cond_signal(&spy->trigger);
1400 ast_mutex_unlock(&spy->lock);
1403 if (translated_frame)
1404 ast_frfree(translated_frame);
1407 static void free_translation(struct ast_channel *clone)
1409 if (clone->writetrans)
1410 ast_translator_free_path(clone->writetrans);
1411 if (clone->readtrans)
1412 ast_translator_free_path(clone->readtrans);
1413 clone->writetrans = NULL;
1414 clone->readtrans = NULL;
1415 clone->rawwriteformat = clone->nativeformats;
1416 clone->rawreadformat = clone->nativeformats;
1419 /*! \brief Hangup a channel */
1420 int ast_hangup(struct ast_channel *chan)
1424 /* Don't actually hang up a channel that will masquerade as someone else, or
1425 if someone is going to masquerade as us */
1426 ast_channel_lock(chan);
1428 detach_spies(chan); /* get rid of spies */
1431 if (ast_do_masquerade(chan))
1432 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1436 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1437 ast_channel_unlock(chan);
1440 /* If this channel is one which will be masqueraded into something,
1441 mark it as a zombie already, so we know to free it later */
1443 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1444 ast_channel_unlock(chan);
1447 free_translation(chan);
1448 if (chan->stream) /* Close audio stream */
1449 ast_closestream(chan->stream);
1450 if (chan->vstream) /* Close video stream */
1451 ast_closestream(chan->vstream);
1453 sched_context_destroy(chan->sched);
1457 if (chan->generatordata) /* Clear any tone stuff remaining */
1458 chan->generator->release(chan, chan->generatordata);
1459 chan->generatordata = NULL;
1460 chan->generator = NULL;
1461 if (chan->cdr) { /* End the CDR if it hasn't already */
1462 ast_cdr_end(chan->cdr);
1463 ast_cdr_detach(chan->cdr); /* Post and Free the CDR */
1466 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1467 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1468 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1469 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1472 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1474 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1475 if (chan->tech->hangup)
1476 res = chan->tech->hangup(chan);
1479 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1482 ast_channel_unlock(chan);
1483 manager_event(EVENT_FLAG_CALL, "Hangup",
1487 "Cause-txt: %s\r\n",
1491 ast_cause2str(chan->hangupcause)
1493 ast_channel_free(chan);
1497 int ast_answer(struct ast_channel *chan)
1500 ast_channel_lock(chan);
1501 /* You can't answer an outbound call */
1502 if (ast_test_flag(chan, AST_FLAG_OUTGOING))
1504 /* Stop if we're a zombie or need a soft hangup */
1505 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1506 ast_channel_unlock(chan);
1509 switch(chan->_state) {
1510 case AST_STATE_RINGING:
1511 case AST_STATE_RING:
1512 if (chan->tech->answer)
1513 res = chan->tech->answer(chan);
1514 ast_setstate(chan, AST_STATE_UP);
1515 ast_cdr_answer(chan->cdr);
1518 ast_cdr_answer(chan->cdr);
1521 ast_channel_unlock(chan);
1525 void ast_deactivate_generator(struct ast_channel *chan)
1527 ast_channel_lock(chan);
1528 if (chan->generatordata) {
1529 if (chan->generator && chan->generator->release)
1530 chan->generator->release(chan, chan->generatordata);
1531 chan->generatordata = NULL;
1532 chan->generator = NULL;
1533 chan->fds[AST_GENERATOR_FD] = -1;
1534 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1535 ast_settimeout(chan, 0, NULL, NULL);
1537 ast_channel_unlock(chan);
1540 static int generator_force(void *data)
1542 /* Called if generator doesn't have data */
1545 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1546 struct ast_channel *chan = data;
1547 tmp = chan->generatordata;
1548 chan->generatordata = NULL;
1549 generate = chan->generator->generate;
1550 res = generate(chan, tmp, 0, 160);
1551 chan->generatordata = tmp;
1553 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1554 ast_deactivate_generator(chan);
1559 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1563 ast_channel_lock(chan);
1565 if (chan->generatordata) {
1566 if (chan->generator && chan->generator->release)
1567 chan->generator->release(chan, chan->generatordata);
1568 chan->generatordata = NULL;
1572 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1577 ast_settimeout(chan, 160, generator_force, chan);
1578 chan->generator = gen;
1581 ast_channel_unlock(chan);
1586 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1587 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1590 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1594 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1595 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1596 int *exception, int *outfd, int *ms)
1598 struct timeval start = { 0 , 0 };
1599 struct pollfd *pfds;
1605 long whentohangup = 0, diff;
1606 struct ast_channel *winner = NULL;
1612 sz = n * AST_MAX_FDS + nfds;
1613 pfds = alloca(sizeof(*pfds) * sz);
1614 fdmap = alloca(sizeof(*fdmap) * sz);
1621 /* Perform any pending masquerades */
1622 for (x=0; x < n; x++) {
1623 ast_channel_lock(c[x]);
1625 if (ast_do_masquerade(c[x])) {
1626 ast_log(LOG_WARNING, "Masquerade failed\n");
1628 ast_channel_unlock(c[x]);
1632 if (c[x]->whentohangup) {
1635 diff = c[x]->whentohangup - now;
1637 /* Should already be hungup */
1638 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1639 ast_channel_unlock(c[x]);
1642 if (!whentohangup || (diff < whentohangup))
1643 whentohangup = diff;
1645 ast_channel_unlock(c[x]);
1647 /* Wait full interval */
1650 rms = (whentohangup - now) * 1000; /* timeout in milliseconds */
1651 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1655 * Build the pollfd array, putting the channels' fds first,
1656 * followed by individual fds. Order is important because
1657 * individual fd's must have priority over channel fds.
1660 for (x=0; x<n; x++) {
1661 for (y=0; y<AST_MAX_FDS; y++) {
1662 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1663 fdmap[max].chan = x; /* channel x is linked to this pfds */
1664 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1666 CHECK_BLOCKING(c[x]);
1668 /* Add the individual fds */
1669 for (x=0; x<nfds; x++) {
1670 fdmap[max].chan = -1;
1671 max += ast_add_fd(&pfds[max], fds[x]);
1675 start = ast_tvnow();
1677 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1682 res = poll(pfds, max, kbrms);
1685 } while (!res && (rms > 0));
1687 res = poll(pfds, max, rms);
1690 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1691 if (res < 0) { /* Simulate a timeout if we were interrupted */
1696 if (whentohangup) { /* if we have a timeout, check who expired */
1698 for (x=0; x<n; x++) {
1699 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1700 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1706 if (res == 0) { /* no fd ready, reset timeout and done */
1707 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1711 * Then check if any channel or fd has a pending event.
1712 * Remember to check channels first and fds last, as they
1713 * must have priority on setting 'winner'
1715 for (x = 0; x < max; x++) {
1716 res = pfds[x].revents;
1719 if (fdmap[x].chan >= 0) { /* this is a channel */
1720 winner = c[fdmap[x].chan]; /* override previous winners */
1722 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1724 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1725 winner->fdno = fdmap[x].fdno;
1726 } else { /* this is an fd */
1728 *outfd = pfds[x].fd;
1730 *exception = (res & POLLPRI) ? -1 : 0;
1735 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1742 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1744 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1747 int ast_waitfor(struct ast_channel *c, int ms)
1749 int oldms = ms; /* -1 if no timeout */
1751 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1752 if ((ms < 0) && (oldms < 0))
1757 /* XXX never to be called with ms = -1 */
1758 int ast_waitfordigit(struct ast_channel *c, int ms)
1760 return ast_waitfordigit_full(c, ms, -1, -1);
1763 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1767 if (c->timingfd > -1) {
1772 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1773 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1774 c->timingfunc = func;
1775 c->timingdata = data;
1781 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1784 /* Stop if we're a zombie or need a soft hangup */
1785 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1787 /* Wait for a digit, no more than ms milliseconds total. */
1789 struct ast_channel *rchan;
1793 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1794 if (!rchan && outfd < 0 && ms) {
1795 if (errno == 0 || errno == EINTR)
1797 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1799 } else if (outfd > -1) {
1800 /* The FD we were watching has something waiting */
1804 struct ast_frame *f = ast_read(c);
1808 switch(f->frametype) {
1809 case AST_FRAME_DTMF:
1813 case AST_FRAME_CONTROL:
1814 switch(f->subclass) {
1815 case AST_CONTROL_HANGUP:
1818 case AST_CONTROL_RINGING:
1819 case AST_CONTROL_ANSWER:
1823 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1825 case AST_FRAME_VOICE:
1826 /* Write audio if appropriate */
1828 write(audiofd, f->data, f->datalen);
1834 return 0; /* Time is up */
1837 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1839 struct ast_frame *f = NULL; /* the return value */
1843 /* this function is very long so make sure there is only one return
1844 * point at the end (there is only one exception to this).
1846 ast_channel_lock(chan);
1848 if (ast_do_masquerade(chan)) {
1849 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1851 f = &ast_null_frame;
1856 /* Stop if we're a zombie or need a soft hangup */
1857 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1858 if (chan->generator)
1859 ast_deactivate_generator(chan);
1862 prestate = chan->_state;
1864 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1865 /* We have DTMF that has been deferred. Return it now */
1866 chan->dtmff.frametype = AST_FRAME_DTMF;
1867 chan->dtmff.subclass = chan->dtmfq[0];
1868 /* Drop first digit from the buffer */
1869 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1874 /* Read and ignore anything on the alertpipe, but read only
1875 one sizeof(blah) per frame that we send from it */
1876 if (chan->alertpipe[0] > -1)
1877 read(chan->alertpipe[0], &blah, sizeof(blah));
1880 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1883 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1885 /* IF we can't get event, assume it's an expired as-per the old interface */
1886 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1888 blah = ZT_EVENT_TIMER_EXPIRED;
1890 if (blah == ZT_EVENT_TIMER_PING) {
1891 if (!chan->readq || !chan->readq->next) {
1892 /* Acknowledge PONG unless we need it again */
1893 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1894 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1897 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1898 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1899 if (chan->timingfunc) {
1900 /* save a copy of func/data before unlocking the channel */
1901 int (*func)(void *) = chan->timingfunc;
1902 void *data = chan->timingdata;
1903 ast_channel_unlock(chan);
1907 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1908 chan->timingdata = NULL;
1909 ast_channel_unlock(chan);
1911 /* cannot 'goto done' because the channel is already unlocked */
1912 return &ast_null_frame;
1914 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1917 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
1918 /* if the AST_GENERATOR_FD is set, call the generator with args
1919 * set to -1 so it can do whatever it needs to.
1921 void *tmp = chan->generatordata;
1922 chan->generatordata = NULL; /* reset to let ast_write get through */
1923 chan->generator->generate(chan, tmp, -1, -1);
1924 chan->generatordata = tmp;
1925 f = &ast_null_frame;
1929 /* Check for pending read queue */
1932 chan->readq = f->next;
1934 /* Interpret hangup and return NULL */
1935 /* XXX why not the same for frames from the channel ? */
1936 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
1941 chan->blocker = pthread_self();
1942 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1943 if (chan->tech->exception)
1944 f = chan->tech->exception(chan);
1946 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1947 f = &ast_null_frame;
1949 /* Clear the exception flag */
1950 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1951 } else if (chan->tech->read)
1952 f = chan->tech->read(chan);
1954 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1958 /* if the channel driver returned more than one frame, stuff the excess
1959 into the readq for the next ast_read call
1962 chan->readq = f->next;
1966 switch (f->frametype) {
1967 case AST_FRAME_CONTROL:
1968 if (f->subclass == AST_CONTROL_ANSWER) {
1969 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1970 ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
1972 f = &ast_null_frame;
1973 } else if (prestate == AST_STATE_UP) {
1974 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1976 f = &ast_null_frame;
1978 /* Answer the CDR */
1979 ast_setstate(chan, AST_STATE_UP);
1980 ast_cdr_answer(chan->cdr);
1984 case AST_FRAME_DTMF:
1985 ast_log(LOG_DTMF, "DTMF '%c' received on %s\n", f->subclass, chan->name);
1986 if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF)) {
1987 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1988 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1990 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1992 f = &ast_null_frame;
1995 case AST_FRAME_DTMF_BEGIN:
1996 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
1998 case AST_FRAME_DTMF_END:
1999 ast_log(LOG_DTMF, "DTMF end '%c' received on %s\n", f->subclass, chan->name);
2001 case AST_FRAME_VOICE:
2004 f = &ast_null_frame;
2005 } else if (!(f->subclass & chan->nativeformats)) {
2006 /* This frame can't be from the current native formats -- drop it on the
2008 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2009 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2011 f = &ast_null_frame;
2014 queue_frame_to_spies(chan, f, SPY_READ);
2016 if (chan->monitor && chan->monitor->read_stream ) {
2017 /* XXX what does this do ? */
2018 #ifndef MONITOR_CONSTANT_DELAY
2019 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2021 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2022 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2023 chan->insmpl += jump + 4 * f->samples;
2025 chan->insmpl+= f->samples;
2027 int jump = chan->outsmpl - chan->insmpl;
2028 if (jump - MONITOR_DELAY >= 0) {
2029 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2030 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2031 chan->insmpl += jump;
2033 chan->insmpl += f->samples;
2035 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2036 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2037 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2041 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2042 f = &ast_null_frame;
2044 /* Run generator sitting on the line if timing device not available
2045 * and synchronous generation of outgoing frames is necessary */
2046 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2047 void *tmp = chan->generatordata;
2050 if (chan->timingfunc) {
2051 if (option_debug > 1)
2052 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2053 ast_settimeout(chan, 0, NULL, NULL);
2056 chan->generatordata = NULL; /* reset, to let writes go through */
2057 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2058 chan->generatordata = tmp;
2060 if (option_debug > 1)
2061 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2062 ast_deactivate_generator(chan);
2065 } else if (f->frametype == AST_FRAME_CNG) {
2066 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2067 if (option_debug > 1)
2068 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2069 ast_settimeout(chan, 160, generator_force, chan);
2075 /* Make sure we always return NULL in the future */
2076 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2077 if (chan->generator)
2078 ast_deactivate_generator(chan);
2079 /* End the CDR if appropriate */
2081 ast_cdr_end(chan->cdr);
2084 /* High bit prints debugging */
2085 if (chan->fin & DEBUGCHAN_FLAG)
2086 ast_frame_dump(chan->name, f, "<<");
2087 chan->fin = FRAMECOUNT_INC(chan->fin);
2090 ast_channel_unlock(chan);
2094 int ast_internal_timing_enabled(struct ast_channel *chan)
2096 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2097 if (option_debug > 3)
2098 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);
2102 struct ast_frame *ast_read(struct ast_channel *chan)
2104 return __ast_read(chan, 0);
2107 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2109 return __ast_read(chan, 1);
2112 int ast_indicate(struct ast_channel *chan, int condition)
2114 return ast_indicate_data(chan, condition, NULL, 0);
2117 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2121 ast_channel_lock(chan);
2122 /* Stop if we're a zombie or need a soft hangup */
2123 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2124 ast_channel_unlock(chan);
2127 if (chan->tech->indicate)
2128 res = chan->tech->indicate(chan, condition, data, datalen);
2129 ast_channel_unlock(chan);
2130 if (!chan->tech->indicate || res) {
2132 * Device does not support (that) indication, lets fake
2133 * it by doing our own tone generation. (PM2002)
2136 ast_playtones_stop(chan);
2138 const struct tone_zone_sound *ts = NULL;
2139 switch (condition) {
2140 case AST_CONTROL_RINGING:
2141 ts = ast_get_indication_tone(chan->zone, "ring");
2143 case AST_CONTROL_BUSY:
2144 ts = ast_get_indication_tone(chan->zone, "busy");
2146 case AST_CONTROL_CONGESTION:
2147 ts = ast_get_indication_tone(chan->zone, "congestion");
2150 if (ts && ts->data[0]) {
2151 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2152 ast_playtones_start(chan,0,ts->data, 1);
2154 } else if (condition == AST_CONTROL_PROGRESS) {
2155 /* ast_playtones_stop(chan); */
2156 } else if (condition == AST_CONTROL_PROCEEDING) {
2157 /* Do nothing, really */
2158 } else if (condition == AST_CONTROL_HOLD) {
2159 /* Do nothing.... */
2160 } else if (condition == AST_CONTROL_UNHOLD) {
2161 /* Do nothing.... */
2162 } else if (condition == AST_CONTROL_VIDUPDATE) {
2163 /* Do nothing.... */
2166 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2174 int ast_recvchar(struct ast_channel *chan, int timeout)
2177 char *buf = ast_recvtext(chan, timeout);
2179 return -1; /* error or timeout */
2180 c = *(unsigned char *)buf;
2185 char *ast_recvtext(struct ast_channel *chan, int timeout)
2191 struct ast_frame *f;
2192 if (ast_check_hangup(chan))
2194 res = ast_waitfor(chan, timeout);
2195 if (res <= 0) /* timeout or error */
2197 timeout = res; /* update timeout */
2200 break; /* no frame */
2201 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2202 done = 1; /* force a break */
2203 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2204 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2212 int ast_sendtext(struct ast_channel *chan, const char *text)
2215 /* Stop if we're a zombie or need a soft hangup */
2216 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2218 CHECK_BLOCKING(chan);
2219 if (chan->tech->send_text)
2220 res = chan->tech->send_text(chan, text);
2221 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2225 static int do_senddigit(struct ast_channel *chan, char digit)
2229 if (chan->tech->send_digit)
2230 res = chan->tech->send_digit(chan, digit);
2233 * Device does not support DTMF tones, lets fake
2234 * it by doing our own generation. (PM2002)
2236 static const char* dtmf_tones[] = {
2237 "!941+1336/100,!0/100", /* 0 */
2238 "!697+1209/100,!0/100", /* 1 */
2239 "!697+1336/100,!0/100", /* 2 */
2240 "!697+1477/100,!0/100", /* 3 */
2241 "!770+1209/100,!0/100", /* 4 */
2242 "!770+1336/100,!0/100", /* 5 */
2243 "!770+1477/100,!0/100", /* 6 */
2244 "!852+1209/100,!0/100", /* 7 */
2245 "!852+1336/100,!0/100", /* 8 */
2246 "!852+1477/100,!0/100", /* 9 */
2247 "!697+1633/100,!0/100", /* A */
2248 "!770+1633/100,!0/100", /* B */
2249 "!852+1633/100,!0/100", /* C */
2250 "!941+1633/100,!0/100", /* D */
2251 "!941+1209/100,!0/100", /* * */
2252 "!941+1477/100,!0/100" }; /* # */
2253 if (digit >= '0' && digit <='9')
2254 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2255 else if (digit >= 'A' && digit <= 'D')
2256 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2257 else if (digit == '*')
2258 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2259 else if (digit == '#')
2260 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2263 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2269 int ast_senddigit(struct ast_channel *chan, char digit)
2271 return do_senddigit(chan, digit);
2274 int ast_prod(struct ast_channel *chan)
2276 struct ast_frame a = { AST_FRAME_VOICE };
2279 /* Send an empty audio frame to get things moving */
2280 if (chan->_state != AST_STATE_UP) {
2281 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2282 a.subclass = chan->rawwriteformat;
2283 a.data = nothing + AST_FRIENDLY_OFFSET;
2285 if (ast_write(chan, &a))
2286 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2291 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2294 if (!chan->tech->write_video)
2296 res = ast_write(chan, fr);
2302 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2305 struct ast_frame *f = NULL;
2307 /* Stop if we're a zombie or need a soft hangup */
2308 ast_channel_lock(chan);
2309 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2312 /* Handle any pending masquerades */
2313 if (chan->masq && ast_do_masquerade(chan)) {
2314 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2318 res = 0; /* XXX explain, why 0 ? */
2321 if (chan->generatordata) {
2322 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2323 ast_deactivate_generator(chan);
2325 res = 0; /* XXX explain, why 0 ? */
2329 /* High bit prints debugging */
2330 if (chan->fout & DEBUGCHAN_FLAG)
2331 ast_frame_dump(chan->name, fr, ">>");
2332 CHECK_BLOCKING(chan);
2333 switch(fr->frametype) {
2334 case AST_FRAME_CONTROL:
2335 /* XXX Interpret control frames XXX */
2336 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
2338 case AST_FRAME_DTMF_BEGIN:
2339 res = (chan->tech->send_digit_begin == NULL) ? 0 :
2340 chan->tech->send_digit_begin(chan, fr->subclass);
2342 case AST_FRAME_DTMF_END:
2343 res = (chan->tech->send_digit_end == NULL) ? 0 :
2344 chan->tech->send_digit_end(chan);
2346 case AST_FRAME_DTMF:
2347 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2348 ast_channel_unlock(chan);
2349 res = do_senddigit(chan,fr->subclass);
2350 ast_channel_lock(chan);
2351 CHECK_BLOCKING(chan);
2353 case AST_FRAME_TEXT:
2354 res = (chan->tech->send_text == NULL) ? 0 :
2355 chan->tech->send_text(chan, (char *) fr->data);
2357 case AST_FRAME_HTML:
2358 res = (chan->tech->send_html == NULL) ? 0 :
2359 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2361 case AST_FRAME_VIDEO:
2362 /* XXX Handle translation of video codecs one day XXX */
2363 res = (chan->tech->write_video == NULL) ? 0 :
2364 chan->tech->write_video(chan, fr);
2366 case AST_FRAME_VOICE:
2367 if (chan->tech->write == NULL)
2368 break; /*! \todo XXX should return 0 maybe ? */
2370 /* Bypass translator if we're writing format in the raw write format. This
2371 allows mixing of native / non-native formats */
2372 if (fr->subclass == chan->rawwriteformat)
2375 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2380 queue_frame_to_spies(chan, f, SPY_WRITE);
2382 if (chan->monitor && chan->monitor->write_stream) {
2383 /* XXX must explain this code */
2384 #ifndef MONITOR_CONSTANT_DELAY
2385 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2387 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2388 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2389 chan->outsmpl += jump + 4 * f->samples;
2391 chan->outsmpl += f->samples;
2393 int jump = chan->insmpl - chan->outsmpl;
2394 if (jump - MONITOR_DELAY >= 0) {
2395 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2396 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2397 chan->outsmpl += jump;
2399 chan->outsmpl += f->samples;
2401 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2402 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2403 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2407 res = chan->tech->write(chan, f);
2414 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2415 /* Consider a write failure to force a soft hangup */
2417 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2419 chan->fout = FRAMECOUNT_INC(chan->fout);
2422 ast_channel_unlock(chan);
2426 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2427 struct ast_trans_pvt **trans, const int direction)
2432 /* Make sure we only consider audio */
2433 fmt &= AST_FORMAT_AUDIO_MASK;
2435 native = chan->nativeformats;
2436 /* Find a translation path from the native format to one of the desired formats */
2439 res = ast_translator_best_choice(&fmt, &native);
2442 res = ast_translator_best_choice(&native, &fmt);
2445 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2446 ast_getformatname(native), ast_getformatname(fmt));
2450 /* Now we have a good choice for both. */
2451 ast_channel_lock(chan);
2452 *rawformat = native;
2453 /* User perspective is fmt */
2455 /* Free any read translation we have right now */
2457 ast_translator_free_path(*trans);
2458 /* Build a translation path from the raw format to the desired format */
2461 *trans = ast_translator_build_path(*format, *rawformat);
2464 *trans = ast_translator_build_path(*rawformat, *format);
2465 ast_channel_unlock(chan);
2467 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2468 direction ? "write" : "read", ast_getformatname(fmt));
2472 int ast_set_read_format(struct ast_channel *chan, int fmt)
2474 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2475 &chan->readtrans, 0);
2478 int ast_set_write_format(struct ast_channel *chan, int fmt)
2480 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2481 &chan->writetrans, 1);
2484 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)
2488 struct ast_channel *chan;
2494 outstate = &dummy_outstate; /* make outstate always a valid pointer */
2496 chan = ast_request(type, format, data, &cause);
2498 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2499 /* compute error and return */
2500 if (cause == AST_CAUSE_BUSY)
2501 *outstate = AST_CONTROL_BUSY;
2502 else if (cause == AST_CAUSE_CONGESTION)
2503 *outstate = AST_CONTROL_CONGESTION;
2509 ast_set_variables(chan, oh->vars);
2510 /* XXX why is this necessary, for the parent_channel perhaps ? */
2511 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2512 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2513 if (oh->parent_channel)
2514 ast_channel_inherit_variables(oh->parent_channel, chan);
2516 ast_cdr_setaccount(chan, oh->account);
2518 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2520 if (ast_call(chan, data, 0)) { /* ast_call failed... */
2521 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2523 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
2524 while (timeout && chan->_state != AST_STATE_UP) {
2525 struct ast_frame *f;
2526 res = ast_waitfor(chan, timeout);
2527 if (res <= 0) /* error, timeout, or done */
2533 *outstate = AST_CONTROL_HANGUP;
2537 if (f->frametype == AST_FRAME_CONTROL) {
2538 switch (f->subclass) {
2539 case AST_CONTROL_RINGING: /* record but keep going */
2540 *outstate = f->subclass;
2543 case AST_CONTROL_BUSY:
2544 case AST_CONTROL_CONGESTION:
2545 case AST_CONTROL_ANSWER:
2546 *outstate = f->subclass;
2547 timeout = 0; /* trick to force exit from the while() */
2550 case AST_CONTROL_PROGRESS: /* Ignore */
2551 case -1: /* Ignore -- just stopping indications */
2555 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2564 if (!ast_strlen_zero(oh->context))
2565 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2566 if (!ast_strlen_zero(oh->exten))
2567 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2569 chan->priority = oh->priority;
2571 if (chan->_state == AST_STATE_UP)
2572 *outstate = AST_CONTROL_ANSWER;
2575 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2576 ast_cdr_init(chan->cdr, chan);
2579 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2580 ast_cdr_setapp(chan->cdr,"Dial",tmp);
2581 ast_cdr_update(chan);
2582 ast_cdr_start(chan->cdr);
2583 ast_cdr_end(chan->cdr);
2584 /* If the cause wasn't handled properly */
2585 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2586 ast_cdr_failed(chan->cdr);
2594 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2596 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2599 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2601 struct chanlist *chan;
2602 struct ast_channel *c;
2610 *cause = AST_CAUSE_NOTDEFINED;
2612 if (AST_LIST_LOCK(&channels)) {
2613 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2617 AST_LIST_TRAVERSE(&backends, chan, list) {
2618 if (strcasecmp(type, chan->tech->type))
2621 capabilities = chan->tech->capabilities;
2623 res = ast_translator_best_choice(&fmt, &capabilities);
2625 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2626 AST_LIST_UNLOCK(&channels);
2629 AST_LIST_UNLOCK(&channels);
2630 if (!chan->tech->requester)
2633 if (!(c = chan->tech->requester(type, capabilities, data, cause)))
2636 if (c->_state == AST_STATE_DOWN) {
2637 manager_event(EVENT_FLAG_CALL, "Newchannel",
2641 "CallerIDName: %s\r\n"
2643 c->name, ast_state2str(c->_state),
2644 S_OR(c->cid.cid_num, "<unknown>"),
2645 S_OR(c->cid.cid_name, "<unknown>"),
2651 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2652 *cause = AST_CAUSE_NOSUCHDRIVER;
2653 AST_LIST_UNLOCK(&channels);
2658 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2660 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2661 If the remote end does not answer within the timeout, then do NOT hang up, but
2664 /* Stop if we're a zombie or need a soft hangup */
2665 ast_channel_lock(chan);
2666 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2667 if (chan->tech->call)
2668 res = chan->tech->call(chan, addr, timeout);
2669 ast_set_flag(chan, AST_FLAG_OUTGOING);
2671 ast_channel_unlock(chan);
2676 \brief Transfer a call to dest, if the channel supports transfer
2680 \arg the manager interface
2682 int ast_transfer(struct ast_channel *chan, char *dest)
2686 /* Stop if we're a zombie or need a soft hangup */
2687 ast_channel_lock(chan);
2688 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2689 if (chan->tech->transfer) {
2690 res = chan->tech->transfer(chan, dest);
2696 ast_channel_unlock(chan);
2700 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2702 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
2705 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2707 int pos = 0; /* index in the buffer where we accumulate digits */
2710 /* Stop if we're a zombie or need a soft hangup */
2711 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2718 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2722 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2724 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2736 if (!strchr(enders, d))
2738 if (strchr(enders, d) || (pos >= len)) {
2748 int ast_channel_supports_html(struct ast_channel *chan)
2750 return (chan->tech->send_html) ? 1 : 0;
2753 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2755 if (chan->tech->send_html)
2756 return chan->tech->send_html(chan, subclass, data, datalen);
2760 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2762 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
2765 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2770 /* Set up translation from the chan to the peer */
2771 src = chan->nativeformats;
2772 dst = peer->nativeformats;
2773 if (ast_translator_best_choice(&dst, &src) < 0) {
2774 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2778 /* if the best path is not 'pass through', then
2779 transcoding is needed; if desired, force transcode path
2780 to use SLINEAR between channels, but only if there is
2781 no direct conversion available */
2782 if ((src != dst) && ast_opt_transcode_via_slin &&
2783 (ast_translate_path_steps(dst, src) != 1))
2784 dst = AST_FORMAT_SLINEAR;
2785 if (ast_set_read_format(chan, dst) < 0) {
2786 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2789 if (ast_set_write_format(peer, dst) < 0) {
2790 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2794 /* Set up translation from the peer to the chan */
2795 src = peer->nativeformats;
2796 dst = chan->nativeformats;
2797 if (ast_translator_best_choice(&dst, &src) < 0) {
2798 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2802 /* if the best path is not 'pass through', then
2803 transcoding is needed; if desired, force transcode path
2804 to use SLINEAR between channels, but only if there is
2805 no direct conversion available */
2806 if ((src != dst) && ast_opt_transcode_via_slin &&
2807 (ast_translate_path_steps(dst, src) != 1))
2808 dst = AST_FORMAT_SLINEAR;
2809 if (ast_set_read_format(peer, dst) < 0) {
2810 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2813 if (ast_set_write_format(chan, dst) < 0) {
2814 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2820 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2824 if (original == clone) {
2825 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2828 ast_channel_lock(original);
2829 while(ast_channel_trylock(clone)) {
2830 ast_channel_unlock(original);
2832 ast_channel_lock(original);
2834 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
2835 clone->name, original->name);
2836 if (original->masq) {
2837 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2838 original->masq->name, original->name);
2839 } else if (clone->masqr) {
2840 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2841 clone->name, clone->masqr->name);
2843 original->masq = clone;
2844 clone->masqr = original;
2845 ast_queue_frame(original, &ast_null_frame);
2846 ast_queue_frame(clone, &ast_null_frame);
2847 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
2850 ast_channel_unlock(clone);
2851 ast_channel_unlock(original);
2855 void ast_change_name(struct ast_channel *chan, char *newname)
2857 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
2858 ast_string_field_set(chan, name, newname);
2861 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2863 struct ast_var_t *current, *newvar;
2864 const char *varname;
2866 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2869 varname = ast_var_full_name(current);
2873 if (varname[0] == '_') {
2875 if (varname[1] == '_')
2881 newvar = ast_var_assign(&varname[1], ast_var_value(current));
2883 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2885 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2889 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2891 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2893 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2898 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2905 \brief Clone channel variables from 'clone' channel into 'original' channel
2907 All variables except those related to app_groupcount are cloned.
2908 Variables are actually _removed_ from 'clone' channel, presumably
2909 because it will subsequently be destroyed.
2911 \note Assumes locks will be in place on both channels when called.
2913 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2915 struct ast_var_t *varptr;
2917 /* we need to remove all app_groupcount related variables from the original
2918 channel before merging in the clone's variables; any groups assigned to the
2919 original channel should be released, only those assigned to the clone
2923 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2924 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2925 AST_LIST_REMOVE(&original->varshead, varptr, entries);
2926 ast_var_delete(varptr);
2929 AST_LIST_TRAVERSE_SAFE_END;
2931 /* Append variables from clone channel into original channel */
2932 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2933 if (AST_LIST_FIRST(&clone->varshead))
2934 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2938 \brief Masquerade a channel
2940 \note Assumes channel will be locked when called
2942 int ast_do_masquerade(struct ast_channel *original)
2947 struct ast_frame *cur, *prev;
2948 const struct ast_channel_tech *t;
2950 struct ast_callerid tmpcid;
2951 struct ast_channel *clone = original->masq;
2952 int rformat = original->readformat;
2953 int wformat = original->writeformat;
2959 if (option_debug > 3)
2960 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2961 clone->name, clone->_state, original->name, original->_state);
2963 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
2964 the clone channel into the original channel. Start by killing off the original
2965 channel's backend. I'm not sure we're going to keep this function, because
2966 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2968 /* We need the clone's lock, too */
2969 ast_channel_lock(clone);
2971 if (option_debug > 1)
2972 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
2974 /* Having remembered the original read/write formats, we turn off any translation on either
2976 free_translation(clone);
2977 free_translation(original);
2980 /* Unlink the masquerade */
2981 original->masq = NULL;
2982 clone->masqr = NULL;
2984 /* Save the original name */
2985 ast_copy_string(orig, original->name, sizeof(orig));
2986 /* Save the new name */
2987 ast_copy_string(newn, clone->name, sizeof(newn));
2988 /* Create the masq name */
2989 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2991 /* Copy the name from the clone channel */
2992 ast_string_field_set(original, name, newn);
2994 /* Mangle the name of the clone channel */
2995 ast_string_field_set(clone, name, masqn);
2997 /* Notify any managers of the change, first the masq then the other */
2998 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2999 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3001 /* Swap the technologies */
3003 original->tech = clone->tech;
3006 t_pvt = original->tech_pvt;
3007 original->tech_pvt = clone->tech_pvt;
3008 clone->tech_pvt = t_pvt;
3010 /* Swap the readq's */
3011 cur = original->readq;
3012 original->readq = clone->readq;
3015 /* Swap the alertpipes */
3016 for (i = 0; i < 2; i++) {
3017 x = original->alertpipe[i];
3018 original->alertpipe[i] = clone->alertpipe[i];
3019 clone->alertpipe[i] = x;
3022 /* Swap the raw formats */
3023 x = original->rawreadformat;
3024 original->rawreadformat = clone->rawreadformat;
3025 clone->rawreadformat = x;
3026 x = original->rawwriteformat;
3027 original->rawwriteformat = clone->rawwriteformat;
3028 clone->rawwriteformat = x;
3030 /* Save any pending frames on both sides. Start by counting
3031 * how many we're going to need... */
3034 for (cur = clone->readq; cur; cur = cur->next) {
3038 /* If we had any, prepend them to the ones already in the queue, and
3039 * load up the alertpipe */
3041 prev->next = original->readq;
3042 original->readq = clone->readq;
3043 clone->readq = NULL;
3044 if (original->alertpipe[1] > -1) {
3045 for (i = 0; i < x; i++)
3046 write(original->alertpipe[1], &x, sizeof(x));
3049 clone->_softhangup = AST_SOFTHANGUP_DEV;
3052 /* And of course, so does our current state. Note we need not
3053 call ast_setstate since the event manager doesn't really consider
3054 these separate. We do this early so that the clone has the proper
3055 state of the original channel. */
3056 origstate = original->_state;
3057 original->_state = clone->_state;
3058 clone->_state = origstate;
3060 if (clone->tech->fixup){
3061 res = clone->tech->fixup(original, clone);
3063 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3066 /* Start by disconnecting the original's physical side */
3067 if (clone->tech->hangup)
3068 res = clone->tech->hangup(clone);
3070 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
3071 ast_channel_unlock(clone);
3075 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3076 /* Mangle the name of the clone channel */
3077 ast_string_field_set(clone, name, zombn);
3078 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3080 /* Update the type. */
3081 t_pvt = original->monitor;
3082 original->monitor = clone->monitor;
3083 clone->monitor = t_pvt;
3085 /* Keep the same language. */
3086 ast_string_field_set(original, language, clone->language);
3087 /* Copy the FD's other than the generator fd */
3088 for (x = 0; x < AST_MAX_FDS; x++) {
3089 if (x != AST_GENERATOR_FD)
3090 original->fds[x] = clone->fds[x];
3092 /* Move data stores over */
3093 if (AST_LIST_FIRST(&clone->datastores))
3094 AST_LIST_INSERT_TAIL(&original->datastores, AST_LIST_FIRST(&clone->datastores), entry);
3095 AST_LIST_HEAD_INIT_NOLOCK(&clone->datastores);
3097 clone_variables(original, clone);
3098 AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3099 /* Presense of ADSI capable CPE follows clone */
3100 original->adsicpe = clone->adsicpe;
3101 /* Bridge remains the same */
3102 /* CDR fields remain the same */
3103 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3104 /* Application and data remain the same */
3105 /* Clone exception becomes real one, as with fdno */
3106 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3107 original->fdno = clone->fdno;
3108 /* Schedule context remains the same */
3109 /* Stream stuff stays the same */
3110 /* Keep the original state. The fixup code will need to work with it most likely */
3112 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3114 tmpcid = original->cid;
3115 original->cid = clone->cid;
3116 clone->cid = tmpcid;
3118 /* Restore original timing file descriptor */
3119 original->fds[AST_TIMING_FD] = original->timingfd;
3121 /* Our native formats are different now */
3122 original->nativeformats = clone->nativeformats;
3124 /* Context, extension, priority, app data, jump table, remain the same */
3125 /* pvt switches. pbx stays the same, as does next */
3127 /* Set the write format */
3128 ast_set_write_format(original, wformat);
3130 /* Set the read format */
3131 ast_set_read_format(original, rformat);
3133 /* Copy the music class */
3134 ast_string_field_set(original, musicclass, clone->musicclass);
3137 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3139 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3140 can fix up everything as best as possible */
3141 if (original->tech->fixup) {
3142 res = original->tech->fixup(clone, original);
3144 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3145 original->tech->type, original->name);
3146 ast_channel_unlock(clone);
3150 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3151 original->tech->type, original->name);
3153 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3154 a zombie so nothing tries to touch it. If it's already been marked as a
3155 zombie, then free it now (since it already is considered invalid). */
3156 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3158 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3159 ast_channel_unlock(clone);
3160 manager_event(EVENT_FLAG_CALL, "Hangup",
3164 "Cause-txt: %s\r\n",