use LDFLAGS and LIBS properly, and allow dependencies to provide LDFLAGS if needed...
[asterisk-bristuff.git] / channel.c
blobc14c47ce6bc8f4e90746dd9de8f55269855bba73
1 /*
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.
19 /*! \file
21 * \brief Channel Management
23 * \author Mark Spencer <markster@digium.com>
26 #include "asterisk.h"
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/time.h>
34 #include <signal.h>
35 #include <errno.h>
36 #include <unistd.h>
37 #include <math.h>
39 #ifdef HAVE_ZAPTEL
40 #include <sys/ioctl.h>
41 #include <zaptel/zaptel.h>
42 #endif
44 #include "asterisk/pbx.h"
45 #include "asterisk/frame.h"
46 #include "asterisk/sched.h"
47 #include "asterisk/options.h"
48 #include "asterisk/channel.h"
49 #include "asterisk/chanspy.h"
50 #include "asterisk/musiconhold.h"
51 #include "asterisk/logger.h"
52 #include "asterisk/say.h"
53 #include "asterisk/file.h"
54 #include "asterisk/cli.h"
55 #include "asterisk/translate.h"
56 #include "asterisk/manager.h"
57 #include "asterisk/chanvars.h"
58 #include "asterisk/linkedlists.h"
59 #include "asterisk/indications.h"
60 #include "asterisk/monitor.h"
61 #include "asterisk/causes.h"
62 #include "asterisk/callerid.h"
63 #include "asterisk/utils.h"
64 #include "asterisk/lock.h"
65 #include "asterisk/app.h"
66 #include "asterisk/transcap.h"
67 #include "asterisk/devicestate.h"
68 #include "asterisk/sha1.h"
70 struct channel_spy_trans {
71 int last_format;
72 struct ast_trans_pvt *path;
75 struct ast_channel_spy_list {
76 struct channel_spy_trans read_translator;
77 struct channel_spy_trans write_translator;
78 AST_LIST_HEAD_NOLOCK(, ast_channel_spy) list;
81 /* uncomment if you have problems with 'monitoring' synchronized files */
82 #if 0
83 #define MONITOR_CONSTANT_DELAY
84 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
85 #endif
87 /*! Prevent new channel allocation if shutting down. */
88 static int shutting_down = 0;
90 AST_MUTEX_DEFINE_STATIC(uniquelock);
91 static int uniqueint = 0;
93 unsigned long global_fin = 0, global_fout = 0;
95 /* XXX Lock appropriately in more functions XXX */
97 struct chanlist {
98 const struct ast_channel_tech *tech;
99 AST_LIST_ENTRY(chanlist) list;
102 /*! the list of registered channel types */
103 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
105 /*! the list of channels we have. Note that the lock for this list is used for
106 both the channels list and the backends list. */
107 static AST_LIST_HEAD_STATIC(channels, ast_channel);
109 /*! map AST_CAUSE's to readable string representations */
110 const struct ast_cause {
111 int cause;
112 const char *name;
113 const char *desc;
114 } causes[] = {
115 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
116 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
117 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
118 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
119 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
120 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
121 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
122 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
123 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
124 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
125 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
126 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
127 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
128 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
129 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
130 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
131 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
132 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
133 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
134 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
135 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
136 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
137 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
138 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
139 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
140 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
141 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
142 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
143 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
144 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
145 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
146 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
147 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
148 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
149 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
150 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
151 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
152 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
153 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
154 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
155 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
156 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
157 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
158 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
162 struct ast_variable *ast_channeltype_list(void)
164 struct chanlist *cl;
165 struct ast_variable *var=NULL, *prev = NULL;
166 AST_LIST_TRAVERSE(&backends, cl, list) {
167 if (prev) {
168 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description)))
169 prev = prev->next;
170 } else {
171 var = ast_variable_new(cl->tech->type, cl->tech->description);
172 prev = var;
175 return var;
178 static int show_channeltypes(int fd, int argc, char *argv[])
180 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
181 struct chanlist *cl;
182 int count_chan = 0;
184 ast_cli(fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
185 ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
186 if (AST_LIST_LOCK(&channels)) {
187 ast_log(LOG_WARNING, "Unable to lock channel list\n");
188 return -1;
190 AST_LIST_TRAVERSE(&backends, cl, list) {
191 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description,
192 (cl->tech->devicestate) ? "yes" : "no",
193 (cl->tech->indicate) ? "yes" : "no",
194 (cl->tech->transfer) ? "yes" : "no");
195 count_chan++;
197 AST_LIST_UNLOCK(&channels);
198 ast_cli(fd, "----------\n%d channel drivers registered.\n", count_chan);
199 return RESULT_SUCCESS;
201 #undef FORMAT
205 static int show_channeltype(int fd, int argc, char *argv[])
207 struct chanlist *cl = NULL;
209 if (argc != 3)
210 return RESULT_SHOWUSAGE;
212 if (AST_LIST_LOCK(&channels)) {
213 ast_log(LOG_WARNING, "Unable to lock channel list\n");
214 return RESULT_FAILURE;
217 AST_LIST_TRAVERSE(&backends, cl, list) {
218 if (!strncasecmp(cl->tech->type, argv[2], strlen(cl->tech->type))) {
219 break;
224 if (!cl) {
225 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[2]);
226 AST_LIST_UNLOCK(&channels);
227 return RESULT_FAILURE;
230 ast_cli(fd,
231 "-- Info about channel driver: %s --\n"
232 " Device State: %s\n"
233 " Indication: %s\n"
234 " Transfer : %s\n"
235 " Capabilities: %d\n"
236 " Send Digit: %s\n"
237 " Send HTML : %s\n"
238 " Image Support: %s\n"
239 " Text Support: %s\n",
240 cl->tech->type,
241 (cl->tech->devicestate) ? "yes" : "no",
242 (cl->tech->indicate) ? "yes" : "no",
243 (cl->tech->transfer) ? "yes" : "no",
244 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
245 (cl->tech->send_digit) ? "yes" : "no",
246 (cl->tech->send_html) ? "yes" : "no",
247 (cl->tech->send_image) ? "yes" : "no",
248 (cl->tech->send_text) ? "yes" : "no"
252 AST_LIST_UNLOCK(&channels);
253 return RESULT_SUCCESS;
256 static char *complete_channeltypes(const char *line, const char *word, int pos, int state)
258 struct chanlist *cl;
259 int which = 0;
260 int wordlen;
261 char *ret = NULL;
263 if (pos != 2)
264 return NULL;
266 wordlen = strlen(word);
268 AST_LIST_TRAVERSE(&backends, cl, list) {
269 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
270 ret = strdup(cl->tech->type);
271 break;
275 return ret;
278 static char show_channeltypes_usage[] =
279 "Usage: show channeltypes\n"
280 " Shows available channel types registered in your Asterisk server.\n";
282 static char show_channeltype_usage[] =
283 "Usage: show channeltype <name>\n"
284 " Show details about the specified channel type, <name>.\n";
286 static struct ast_cli_entry cli_show_channeltypes =
287 { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
289 static struct ast_cli_entry cli_show_channeltype =
290 { { "show", "channeltype", NULL }, show_channeltype, "Give more details on that channel type", show_channeltype_usage, complete_channeltypes };
292 /*! \brief Checks to see if a channel is needing hang up */
293 int ast_check_hangup(struct ast_channel *chan)
295 if (chan->_softhangup) /* yes if soft hangup flag set */
296 return 1;
297 if (!chan->tech_pvt) /* yes if no technology private data */
298 return 1;
299 if (!chan->whentohangup) /* no if no hangup scheduled */
300 return 0;
301 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
302 return 0;
303 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
304 return 1;
307 static int ast_check_hangup_locked(struct ast_channel *chan)
309 int res;
310 ast_channel_lock(chan);
311 res = ast_check_hangup(chan);
312 ast_channel_unlock(chan);
313 return res;
316 /*! \brief Initiate system shutdown */
317 void ast_begin_shutdown(int hangup)
319 struct ast_channel *c;
320 shutting_down = 1;
321 if (hangup) {
322 AST_LIST_LOCK(&channels);
323 AST_LIST_TRAVERSE(&channels, c, chan_list)
324 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
325 AST_LIST_UNLOCK(&channels);
329 /*! \brief returns number of active/allocated channels */
330 int ast_active_channels(void)
332 struct ast_channel *c;
333 int cnt = 0;
334 AST_LIST_LOCK(&channels);
335 AST_LIST_TRAVERSE(&channels, c, chan_list)
336 cnt++;
337 AST_LIST_UNLOCK(&channels);
338 return cnt;
341 /*! \brief Cancel a shutdown in progress */
342 void ast_cancel_shutdown(void)
344 shutting_down = 0;
347 /*! \brief Returns non-zero if Asterisk is being shut down */
348 int ast_shutting_down(void)
350 return shutting_down;
353 /*! \brief Set when to hangup channel */
354 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
356 chan->whentohangup = offset ? time(NULL) + offset : 0;
357 ast_queue_frame(chan, &ast_null_frame);
358 return;
361 /*! \brief Compare a offset with when to hangup channel */
362 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
364 time_t whentohangup;
366 if (chan->whentohangup == 0) {
367 return (offset == 0) ? 0 : -1;
368 } else {
369 if (offset == 0) /* XXX why is this special ? */
370 return (1);
371 else {
372 whentohangup = offset + time (NULL);
373 if (chan->whentohangup < whentohangup)
374 return (1);
375 else if (chan->whentohangup == whentohangup)
376 return (0);
377 else
378 return (-1);
383 /*! \brief Register a new telephony channel in Asterisk */
384 int ast_channel_register(const struct ast_channel_tech *tech)
386 struct chanlist *chan;
388 AST_LIST_LOCK(&channels);
390 AST_LIST_TRAVERSE(&backends, chan, list) {
391 if (!strcasecmp(tech->type, chan->tech->type)) {
392 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
393 AST_LIST_UNLOCK(&channels);
394 return -1;
398 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
399 AST_LIST_UNLOCK(&channels);
400 return -1;
402 chan->tech = tech;
403 AST_LIST_INSERT_HEAD(&backends, chan, list);
405 if (option_debug)
406 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
408 if (option_verbose > 1)
409 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
410 chan->tech->description);
412 AST_LIST_UNLOCK(&channels);
413 return 0;
416 void ast_channel_unregister(const struct ast_channel_tech *tech)
418 struct chanlist *chan;
420 if (option_debug)
421 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
423 AST_LIST_LOCK(&channels);
425 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
426 if (chan->tech == tech) {
427 AST_LIST_REMOVE_CURRENT(&backends, list);
428 free(chan);
429 if (option_verbose > 1)
430 ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
431 break;
434 AST_LIST_TRAVERSE_SAFE_END
436 AST_LIST_UNLOCK(&channels);
439 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
441 struct chanlist *chanls;
442 const struct ast_channel_tech *ret = NULL;
444 if (AST_LIST_LOCK(&channels)) {
445 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
446 return NULL;
449 AST_LIST_TRAVERSE(&backends, chanls, list) {
450 if (!strcasecmp(name, chanls->tech->type)) {
451 ret = chanls->tech;
452 break;
456 AST_LIST_UNLOCK(&channels);
458 return ret;
461 /*! \brief Gives the string form of a given hangup cause */
462 const char *ast_cause2str(int cause)
464 int x;
466 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
467 if (causes[x].cause == cause)
468 return causes[x].desc;
471 return "Unknown";
474 /*! \brief Convert a symbolic hangup cause to number */
475 int ast_str2cause(const char *name)
477 int x;
479 for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
480 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
481 return causes[x].cause;
483 return -1;
486 /*! \brief Gives the string form of a given channel state */
487 char *ast_state2str(int state)
489 /* XXX Not reentrant XXX */
490 static char localtmp[256];
491 switch(state) {
492 case AST_STATE_DOWN:
493 return "Down";
494 case AST_STATE_RESERVED:
495 return "Rsrvd";
496 case AST_STATE_OFFHOOK:
497 return "OffHook";
498 case AST_STATE_DIALING:
499 return "Dialing";
500 case AST_STATE_RING:
501 return "Ring";
502 case AST_STATE_RINGING:
503 return "Ringing";
504 case AST_STATE_UP:
505 return "Up";
506 case AST_STATE_BUSY:
507 return "Busy";
508 default:
509 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
510 return localtmp;
514 /*! \brief Gives the string form of a given transfer capability */
515 char *ast_transfercapability2str(int transfercapability)
517 switch(transfercapability) {
518 case AST_TRANS_CAP_SPEECH:
519 return "SPEECH";
520 case AST_TRANS_CAP_DIGITAL:
521 return "DIGITAL";
522 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
523 return "RESTRICTED_DIGITAL";
524 case AST_TRANS_CAP_3_1K_AUDIO:
525 return "3K1AUDIO";
526 case AST_TRANS_CAP_DIGITAL_W_TONES:
527 return "DIGITAL_W_TONES";
528 case AST_TRANS_CAP_VIDEO:
529 return "VIDEO";
530 default:
531 return "UNKNOWN";
535 /*! \brief Pick the best audio codec */
536 int ast_best_codec(int fmts)
538 /* This just our opinion, expressed in code. We are asked to choose
539 the best codec to use, given no information */
540 int x;
541 static int prefs[] =
543 /*! Okay, ulaw is used by all telephony equipment, so start with it */
544 AST_FORMAT_ULAW,
545 /*! Unless of course, you're a silly European, so then prefer ALAW */
546 AST_FORMAT_ALAW,
547 /*! Okay, well, signed linear is easy to translate into other stuff */
548 AST_FORMAT_SLINEAR,
549 /*! G.726 is standard ADPCM, in RFC3551 packing order */
550 AST_FORMAT_G726,
551 /*! G.726 is standard ADPCM, in AAL2 packing order */
552 AST_FORMAT_G726_AAL2,
553 /*! ADPCM has great sound quality and is still pretty easy to translate */
554 AST_FORMAT_ADPCM,
555 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
556 translate and sounds pretty good */
557 AST_FORMAT_GSM,
558 /*! iLBC is not too bad */
559 AST_FORMAT_ILBC,
560 /*! Speex is free, but computationally more expensive than GSM */
561 AST_FORMAT_SPEEX,
562 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
563 to use it */
564 AST_FORMAT_LPC10,
565 /*! G.729a is faster than 723 and slightly less expensive */
566 AST_FORMAT_G729A,
567 /*! Down to G.723.1 which is proprietary but at least designed for voice */
568 AST_FORMAT_G723_1,
571 /* Strip out video */
572 fmts &= AST_FORMAT_AUDIO_MASK;
574 /* Find the first preferred codec in the format given */
575 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
576 if (fmts & prefs[x])
577 return prefs[x];
578 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
579 return 0;
582 static const struct ast_channel_tech null_tech = {
583 .type = "NULL",
584 .description = "Null channel (should not see this)",
587 /*! \brief Create a new channel structure */
588 struct ast_channel *ast_channel_alloc(int needqueue)
590 struct ast_channel *tmp;
591 int x;
592 int flags;
593 struct varshead *headp;
595 /* If shutting down, don't allocate any new channels */
596 if (shutting_down) {
597 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
598 return NULL;
601 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
602 return NULL;
604 if (!(tmp->sched = sched_context_create())) {
605 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
606 free(tmp);
607 return NULL;
610 ast_string_field_init(tmp, 128);
612 /* Don't bother initializing the last two FD here, because they
613 will *always* be set just a few lines down (AST_TIMING_FD,
614 AST_ALERT_FD). */
615 for (x=0; x<AST_MAX_FDS - 2; x++)
616 tmp->fds[x] = -1;
618 #ifdef HAVE_ZAPTEL
619 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
620 if (tmp->timingfd > -1) {
621 /* Check if timing interface supports new
622 ping/pong scheme */
623 flags = 1;
624 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
625 needqueue = 0;
627 #else
628 tmp->timingfd = -1;
629 #endif
631 if (needqueue) {
632 if (pipe(tmp->alertpipe)) {
633 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
634 free(tmp);
635 return NULL;
636 } else {
637 flags = fcntl(tmp->alertpipe[0], F_GETFL);
638 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
639 flags = fcntl(tmp->alertpipe[1], F_GETFL);
640 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
642 } else /* Make sure we've got it done right if they don't */
643 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
645 /* Always watch the alertpipe */
646 tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
647 /* And timing pipe */
648 tmp->fds[AST_TIMING_FD] = tmp->timingfd;
649 ast_string_field_set(tmp, name, "**Unknown**");
650 /* Initial state */
651 tmp->_state = AST_STATE_DOWN;
652 tmp->streamid = -1;
653 tmp->appl = NULL;
654 tmp->data = NULL;
655 tmp->fin = global_fin;
656 tmp->fout = global_fout;
657 ast_mutex_lock(&uniquelock);
658 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
659 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), uniqueint++);
660 else
661 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, (long) time(NULL), uniqueint++);
662 ast_mutex_unlock(&uniquelock);
663 headp = &tmp->varshead;
664 ast_mutex_init(&tmp->lock);
665 AST_LIST_HEAD_INIT_NOLOCK(headp);
666 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
667 strcpy(tmp->context, "default");
668 ast_string_field_set(tmp, language, defaultlanguage);
669 strcpy(tmp->exten, "s");
670 tmp->priority = 1;
671 tmp->amaflags = ast_default_amaflags;
672 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
674 tmp->tech = &null_tech;
676 AST_LIST_LOCK(&channels);
677 AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
678 AST_LIST_UNLOCK(&channels);
679 return tmp;
682 /*! \brief Queue an outgoing media frame */
683 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
685 struct ast_frame *f;
686 struct ast_frame *prev, *cur;
687 int blah = 1;
688 int qlen = 0;
690 /* Build us a copy and free the original one */
691 if (!(f = ast_frdup(fin))) {
692 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
693 return -1;
695 ast_channel_lock(chan);
696 prev = NULL;
697 for (cur = chan->readq; cur; cur = cur->next) {
698 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
699 /* Don't bother actually queueing anything after a hangup */
700 ast_frfree(f);
701 ast_channel_unlock(chan);
702 return 0;
704 prev = cur;
705 qlen++;
707 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
708 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
709 if (fin->frametype != AST_FRAME_VOICE) {
710 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
711 CRASH;
712 } else {
713 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
714 ast_frfree(f);
715 ast_channel_unlock(chan);
716 return 0;
719 if (prev)
720 prev->next = f;
721 else
722 chan->readq = f;
723 if (chan->alertpipe[1] > -1) {
724 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
725 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
726 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
727 #ifdef HAVE_ZAPTEL
728 } else if (chan->timingfd > -1) {
729 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
730 #endif
731 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
732 pthread_kill(chan->blocker, SIGURG);
734 ast_channel_unlock(chan);
735 return 0;
738 /*! \brief Queue a hangup frame for channel */
739 int ast_queue_hangup(struct ast_channel *chan)
741 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
742 /* Yeah, let's not change a lock-critical value without locking */
743 if (!ast_channel_trylock(chan)) {
744 chan->_softhangup |= AST_SOFTHANGUP_DEV;
745 ast_channel_unlock(chan);
747 return ast_queue_frame(chan, &f);
750 /*! \brief Queue a control frame */
751 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
753 struct ast_frame f = { AST_FRAME_CONTROL, };
755 f.subclass = control;
757 return ast_queue_frame(chan, &f);
760 /*! \brief Queue a control frame with payload */
761 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
762 const void *data, size_t datalen)
764 struct ast_frame f = { AST_FRAME_CONTROL, };
766 f.subclass = control;
767 f.data = (void *) data;
768 f.datalen = datalen;
770 return ast_queue_frame(chan, &f);
773 /*! \brief Set defer DTMF flag on channel */
774 int ast_channel_defer_dtmf(struct ast_channel *chan)
776 int pre = 0;
778 if (chan) {
779 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
780 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
782 return pre;
785 /*! \brief Unset defer DTMF flag on channel */
786 void ast_channel_undefer_dtmf(struct ast_channel *chan)
788 if (chan)
789 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
793 * \brief Helper function to find channels.
795 * It supports these modes:
797 * prev != NULL : get channel next in list after prev
798 * name != NULL : get channel with matching name
799 * name != NULL && namelen != 0 : get channel whose name starts with prefix
800 * exten != NULL : get channel whose exten or macroexten matches
801 * context != NULL && exten != NULL : get channel whose context or macrocontext
803 * It returns with the channel's lock held. If getting the individual lock fails,
804 * unlock and retry quickly up to 10 times, then give up.
806 * \note XXX Note that this code has cost O(N) because of the need to verify
807 * that the object is still on the global list.
809 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
810 * can only be done with the lock held or someone could delete the
811 * object while we work on it. This causes some ugliness in the code.
812 * Note that removing the first ast_log() may be harmful, as it would
813 * shorten the retry period and possibly cause failures.
814 * We should definitely go for a better scheme that is deadlock-free.
816 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
817 const char *name, const int namelen,
818 const char *context, const char *exten)
820 const char *msg = prev ? "deadlock" : "initial deadlock";
821 int retries;
822 struct ast_channel *c;
824 for (retries = 0; retries < 10; retries++) {
825 int done;
826 AST_LIST_LOCK(&channels);
827 AST_LIST_TRAVERSE(&channels, c, chan_list) {
828 if (prev) { /* look for next item */
829 if (c != prev) /* not this one */
830 continue;
831 /* found, prepare to return c->next */
832 c = AST_LIST_NEXT(c, chan_list);
833 } else if (name) { /* want match by name */
834 if ( (!namelen && strcasecmp(c->name, name)) ||
835 (namelen && strncasecmp(c->name, name, namelen)) )
836 continue; /* name match failed */
837 } else if (exten) {
838 if (context && strcasecmp(c->context, context) &&
839 strcasecmp(c->macrocontext, context))
840 continue; /* context match failed */
841 if (strcasecmp(c->exten, exten) &&
842 strcasecmp(c->macroexten, exten))
843 continue; /* exten match failed */
845 /* if we get here, c points to the desired record */
846 break;
848 /* exit if chan not found or mutex acquired successfully */
849 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
850 done = c == NULL || ast_channel_trylock(c) == 0;
851 if (!done)
852 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
853 AST_LIST_UNLOCK(&channels);
854 if (done)
855 return c;
856 usleep(1); /* give other threads a chance before retrying */
859 * c is surely not null, but we don't have the lock so cannot
860 * access c->name
862 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n",
863 c, retries);
865 return NULL;
868 /*! \brief Browse channels in use */
869 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
871 return channel_find_locked(prev, NULL, 0, NULL, NULL);
874 /*! \brief Get channel by name and lock it */
875 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
877 return channel_find_locked(NULL, name, 0, NULL, NULL);
880 /*! \brief Get channel by name prefix and lock it */
881 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
883 return channel_find_locked(NULL, name, namelen, NULL, NULL);
886 /*! \brief Get next channel by name prefix and lock it */
887 struct ast_channel *ast_walk_channel_by_name_prefix_locked(struct ast_channel *chan, const char *name, const int namelen)
889 return channel_find_locked(chan, name, namelen, NULL, NULL);
892 /*! \brief Get channel by exten (and optionally context) and lock it */
893 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
895 return channel_find_locked(NULL, NULL, 0, context, exten);
898 /*! \brief Wait, look for hangups and condition arg */
899 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
901 struct ast_frame *f;
903 while (ms > 0) {
904 if (cond && ((*cond)(data) == 0))
905 return 0;
906 ms = ast_waitfor(chan, ms);
907 if (ms < 0)
908 return -1;
909 if (ms > 0) {
910 f = ast_read(chan);
911 if (!f)
912 return -1;
913 ast_frfree(f);
916 return 0;
919 /*! \brief Wait, look for hangups */
920 int ast_safe_sleep(struct ast_channel *chan, int ms)
922 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
925 static void free_cid(struct ast_callerid *cid)
927 if (cid->cid_dnid)
928 free(cid->cid_dnid);
929 if (cid->cid_num)
930 free(cid->cid_num);
931 if (cid->cid_name)
932 free(cid->cid_name);
933 if (cid->cid_ani)
934 free(cid->cid_ani);
935 if (cid->cid_rdnis)
936 free(cid->cid_rdnis);
939 /*! \brief Free a channel structure */
940 void ast_channel_free(struct ast_channel *chan)
942 int fd;
943 struct ast_var_t *vardata;
944 struct ast_frame *f, *fp;
945 struct varshead *headp;
946 struct ast_datastore *datastore = NULL;
947 char name[AST_CHANNEL_NAME];
949 headp=&chan->varshead;
951 AST_LIST_LOCK(&channels);
952 AST_LIST_REMOVE(&channels, chan, chan_list);
953 /* Lock and unlock the channel just to be sure nobody
954 has it locked still */
955 ast_channel_lock(chan);
956 ast_channel_unlock(chan);
957 if (chan->tech_pvt) {
958 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
959 free(chan->tech_pvt);
962 if (chan->sched)
963 sched_context_destroy(chan->sched);
965 ast_copy_string(name, chan->name, sizeof(name));
967 /* Stop monitoring */
968 if (chan->monitor) {
969 chan->monitor->stop( chan, 0 );
972 /* If there is native format music-on-hold state, free it */
973 if(chan->music_state)
974 ast_moh_cleanup(chan);
976 /* Free translators */
977 if (chan->readtrans)
978 ast_translator_free_path(chan->readtrans);
979 if (chan->writetrans)
980 ast_translator_free_path(chan->writetrans);
981 if (chan->pbx)
982 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
983 free_cid(&chan->cid);
984 ast_mutex_destroy(&chan->lock);
985 /* Close pipes if appropriate */
986 if ((fd = chan->alertpipe[0]) > -1)
987 close(fd);
988 if ((fd = chan->alertpipe[1]) > -1)
989 close(fd);
990 if ((fd = chan->timingfd) > -1)
991 close(fd);
992 f = chan->readq;
993 chan->readq = NULL;
994 while(f) {
995 fp = f;
996 f = f->next;
997 ast_frfree(fp);
1000 /* Get rid of each of the data stores on the channel */
1001 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1002 /* Free the data store */
1003 ast_channel_datastore_free(datastore);
1004 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1006 /* loop over the variables list, freeing all data and deleting list items */
1007 /* no need to lock the list, as the channel is already locked */
1009 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1010 ast_var_delete(vardata);
1012 /* Destroy the jitterbuffer */
1013 ast_jb_destroy(chan);
1015 ast_string_field_free_all(chan);
1016 free(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 */
1027 if (info == NULL) {
1028 return NULL;
1031 /* Allocate memory for datastore and clear it */
1032 datastore = ast_calloc(1, sizeof(*datastore));
1033 if (datastore == NULL) {
1034 return NULL;
1037 datastore->info = info;
1039 datastore->uid = ast_strdup(uid);
1041 return datastore;
1044 int ast_channel_datastore_free(struct ast_datastore *datastore)
1046 int res = 0;
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 */
1061 free(datastore);
1063 return res;
1066 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1068 int res = 0;
1070 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1072 return res;
1075 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1077 struct ast_datastore *datastore2 = NULL;
1078 int res = -1;
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);
1084 res = 0;
1085 break;
1088 AST_LIST_TRAVERSE_SAFE_END
1090 return res;
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;
1097 if (info == NULL)
1098 return 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 */
1105 break;
1107 } else {
1108 /* Matched by type at least */
1109 break;
1113 AST_LIST_TRAVERSE_SAFE_END
1115 return datastore;
1118 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1120 /* Link the owner channel to the spy */
1121 spy->chan = chan;
1123 if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1124 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1125 spy->type, chan->name);
1126 return -1;
1129 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1130 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1131 ast_getformatname(spy->read_queue.format));
1132 return -1;
1135 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1136 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1137 ast_getformatname(spy->write_queue.format));
1138 return -1;
1141 if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1142 ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1143 (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1144 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1145 ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1146 return -1;
1149 if (!chan->spies) {
1150 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1151 return -1;
1154 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1155 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1156 } else {
1157 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1160 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1161 ast_cond_init(&spy->trigger, NULL);
1162 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1163 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1166 ast_log(LOG_DEBUG, "Spy %s added to channel %s\n",
1167 spy->type, chan->name);
1169 return 0;
1172 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1174 struct ast_channel_spy *spy;
1176 if (!chan->spies)
1177 return;
1179 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1180 ast_mutex_lock(&spy->lock);
1181 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1182 spy->status = CHANSPY_STOP;
1183 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1184 ast_cond_signal(&spy->trigger);
1186 ast_mutex_unlock(&spy->lock);
1190 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1192 struct timeval tv;
1193 struct timespec ts;
1195 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1196 ts.tv_sec = tv.tv_sec;
1197 ts.tv_nsec = tv.tv_usec * 1000;
1199 ast_cond_timedwait(&spy->trigger, &spy->lock, &ts);
1202 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1204 struct ast_frame *f;
1206 if (!chan->spies)
1207 return;
1209 AST_LIST_REMOVE(&chan->spies->list, spy, list);
1211 ast_mutex_lock(&spy->lock);
1213 spy->chan = NULL;
1215 for (f = spy->read_queue.head; f; f = spy->read_queue.head) {
1216 spy->read_queue.head = f->next;
1217 ast_frfree(f);
1219 for (f = spy->write_queue.head; f; f = spy->write_queue.head) {
1220 spy->write_queue.head = f->next;
1221 ast_frfree(f);
1224 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1225 ast_cond_destroy(&spy->trigger);
1227 ast_mutex_unlock(&spy->lock);
1229 ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n",
1230 spy->type, chan->name);
1232 if (AST_LIST_EMPTY(&chan->spies->list)) {
1233 if (chan->spies->read_translator.path)
1234 ast_translator_free_path(chan->spies->read_translator.path);
1235 if (chan->spies->write_translator.path)
1236 ast_translator_free_path(chan->spies->write_translator.path);
1237 free(chan->spies);
1238 chan->spies = NULL;
1242 static void detach_spies(struct ast_channel *chan)
1244 struct ast_channel_spy *spy;
1246 if (!chan->spies)
1247 return;
1249 /* Marking the spies as done is sufficient. Chanspy or spy users will get the picture. */
1250 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1251 ast_mutex_lock(&spy->lock);
1252 spy->chan = NULL;
1253 if (spy->status == CHANSPY_RUNNING)
1254 spy->status = CHANSPY_DONE;
1255 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1256 ast_cond_signal(&spy->trigger);
1257 ast_mutex_unlock(&spy->lock);
1260 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list)
1261 ast_channel_spy_remove(chan, spy);
1262 AST_LIST_TRAVERSE_SAFE_END;
1265 /*! \brief Softly hangup a channel, don't lock */
1266 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1268 if (option_debug)
1269 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1270 /* Inform channel driver that we need to be hung up, if it cares */
1271 chan->_softhangup |= cause;
1272 ast_queue_frame(chan, &ast_null_frame);
1273 /* Interrupt any poll call or such */
1274 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1275 pthread_kill(chan->blocker, SIGURG);
1276 return 0;
1279 /*! \brief Softly hangup a channel, lock */
1280 int ast_softhangup(struct ast_channel *chan, int cause)
1282 int res;
1283 ast_channel_lock(chan);
1284 res = ast_softhangup_nolock(chan, cause);
1285 ast_channel_unlock(chan);
1286 return res;
1289 enum spy_direction {
1290 SPY_READ,
1291 SPY_WRITE,
1294 #define SPY_QUEUE_SAMPLE_LIMIT 4000 /* half of one second */
1296 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1298 struct ast_frame *translated_frame = NULL;
1299 struct ast_channel_spy *spy;
1300 struct channel_spy_trans *trans;
1302 trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1304 AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1305 struct ast_frame *last;
1306 struct ast_frame *f1; /* the frame to append */
1307 struct ast_channel_spy_queue *queue;
1309 ast_mutex_lock(&spy->lock);
1311 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1313 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1314 if (!translated_frame) {
1315 if (trans->path && (trans->last_format != f->subclass)) {
1316 ast_translator_free_path(trans->path);
1317 trans->path = NULL;
1319 if (!trans->path) {
1320 ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1321 ast_getformatname(f->subclass), chan->name);
1322 if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1323 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1324 ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1325 ast_mutex_unlock(&spy->lock);
1326 continue;
1327 } else {
1328 trans->last_format = f->subclass;
1331 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1332 ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1333 ast_getformatname(AST_FORMAT_SLINEAR));
1334 ast_mutex_unlock(&spy->lock);
1335 break;
1338 f1 = translated_frame;
1339 } else {
1340 if (f->subclass != queue->format) {
1341 ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1342 spy->type, chan->name,
1343 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1344 ast_mutex_unlock(&spy->lock);
1345 continue;
1347 f1 = f;
1349 /* duplicate and append f1 to the tail */
1350 f1 = ast_frdup(f1);
1352 for (last = queue->head; last && last->next; last = last->next)
1354 if (last)
1355 last->next = f1;
1356 else
1357 queue->head = f1;
1359 queue->samples += f->samples;
1361 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1362 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1363 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1364 case CHANSPY_TRIGGER_READ:
1365 if (dir == SPY_WRITE) {
1366 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1367 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1368 if (option_debug)
1369 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1370 spy->type, chan->name);
1372 break;
1373 case CHANSPY_TRIGGER_WRITE:
1374 if (dir == SPY_READ) {
1375 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1376 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1377 if (option_debug)
1378 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1379 spy->type, chan->name);
1381 break;
1383 if (option_debug)
1384 ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1385 spy->type, chan->name);
1386 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1387 ast_cond_signal(&spy->trigger);
1388 } else {
1389 if (option_debug)
1390 ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1391 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1392 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1393 struct ast_frame *drop = queue->head;
1395 queue->samples -= drop->samples;
1396 queue->head = drop->next;
1397 ast_frfree(drop);
1400 } else {
1401 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1402 case CHANSPY_TRIGGER_READ:
1403 if (dir == SPY_READ)
1404 ast_cond_signal(&spy->trigger);
1405 break;
1406 case CHANSPY_TRIGGER_WRITE:
1407 if (dir == SPY_WRITE)
1408 ast_cond_signal(&spy->trigger);
1409 break;
1413 ast_mutex_unlock(&spy->lock);
1416 if (translated_frame)
1417 ast_frfree(translated_frame);
1420 static void free_translation(struct ast_channel *clone)
1422 if (clone->writetrans)
1423 ast_translator_free_path(clone->writetrans);
1424 if (clone->readtrans)
1425 ast_translator_free_path(clone->readtrans);
1426 clone->writetrans = NULL;
1427 clone->readtrans = NULL;
1428 clone->rawwriteformat = clone->nativeformats;
1429 clone->rawreadformat = clone->nativeformats;
1432 /*! \brief Hangup a channel */
1433 int ast_hangup(struct ast_channel *chan)
1435 int res = 0;
1437 /* Don't actually hang up a channel that will masquerade as someone else, or
1438 if someone is going to masquerade as us */
1439 ast_channel_lock(chan);
1441 detach_spies(chan); /* get rid of spies */
1443 if (chan->masq) {
1444 if (ast_do_masquerade(chan))
1445 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1448 if (chan->masq) {
1449 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1450 ast_channel_unlock(chan);
1451 return 0;
1453 /* If this channel is one which will be masqueraded into something,
1454 mark it as a zombie already, so we know to free it later */
1455 if (chan->masqr) {
1456 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1457 ast_channel_unlock(chan);
1458 return 0;
1460 free_translation(chan);
1461 if (chan->stream) /* Close audio stream */
1462 ast_closestream(chan->stream);
1463 if (chan->vstream) /* Close video stream */
1464 ast_closestream(chan->vstream);
1465 if (chan->sched) {
1466 sched_context_destroy(chan->sched);
1467 chan->sched = NULL;
1470 if (chan->generatordata) /* Clear any tone stuff remaining */
1471 chan->generator->release(chan, chan->generatordata);
1472 chan->generatordata = NULL;
1473 chan->generator = NULL;
1474 if (chan->cdr) { /* End the CDR if it hasn't already */
1475 ast_cdr_end(chan->cdr);
1476 ast_cdr_detach(chan->cdr); /* Post and Free the CDR */
1477 chan->cdr = NULL;
1479 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1480 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1481 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1482 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1483 CRASH;
1485 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1486 if (option_debug)
1487 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1488 if (chan->tech->hangup)
1489 res = chan->tech->hangup(chan);
1490 } else {
1491 if (option_debug)
1492 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1495 ast_channel_unlock(chan);
1496 manager_event(EVENT_FLAG_CALL, "Hangup",
1497 "Channel: %s\r\n"
1498 "Uniqueid: %s\r\n"
1499 "Cause: %d\r\n"
1500 "Cause-txt: %s\r\n",
1501 chan->name,
1502 chan->uniqueid,
1503 chan->hangupcause,
1504 ast_cause2str(chan->hangupcause)
1506 ast_channel_free(chan);
1507 return res;
1510 int ast_answer(struct ast_channel *chan)
1512 int res = 0;
1513 ast_channel_lock(chan);
1514 /* You can't answer an outbound call */
1515 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1516 ast_channel_unlock(chan);
1517 return 0;
1519 /* Stop if we're a zombie or need a soft hangup */
1520 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1521 ast_channel_unlock(chan);
1522 return -1;
1524 switch(chan->_state) {
1525 case AST_STATE_RINGING:
1526 case AST_STATE_RING:
1527 if (chan->tech->answer)
1528 res = chan->tech->answer(chan);
1529 ast_setstate(chan, AST_STATE_UP);
1530 ast_cdr_answer(chan->cdr);
1531 break;
1532 case AST_STATE_UP:
1533 ast_cdr_answer(chan->cdr);
1534 break;
1536 ast_channel_unlock(chan);
1537 return res;
1540 void ast_deactivate_generator(struct ast_channel *chan)
1542 ast_channel_lock(chan);
1543 if (chan->generatordata) {
1544 if (chan->generator && chan->generator->release)
1545 chan->generator->release(chan, chan->generatordata);
1546 chan->generatordata = NULL;
1547 chan->generator = NULL;
1548 chan->fds[AST_GENERATOR_FD] = -1;
1549 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1550 ast_settimeout(chan, 0, NULL, NULL);
1552 ast_channel_unlock(chan);
1555 static int generator_force(void *data)
1557 /* Called if generator doesn't have data */
1558 void *tmp;
1559 int res;
1560 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1561 struct ast_channel *chan = data;
1562 tmp = chan->generatordata;
1563 chan->generatordata = NULL;
1564 generate = chan->generator->generate;
1565 res = generate(chan, tmp, 0, 160);
1566 chan->generatordata = tmp;
1567 if (res) {
1568 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1569 ast_deactivate_generator(chan);
1571 return 0;
1574 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1576 int res = 0;
1578 ast_channel_lock(chan);
1580 if (chan->generatordata) {
1581 if (chan->generator && chan->generator->release)
1582 chan->generator->release(chan, chan->generatordata);
1583 chan->generatordata = NULL;
1586 ast_prod(chan);
1587 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1588 res = -1;
1591 if (!res) {
1592 ast_settimeout(chan, 160, generator_force, chan);
1593 chan->generator = gen;
1596 ast_channel_unlock(chan);
1598 return res;
1601 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1602 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1604 int winner = -1;
1605 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1606 return winner;
1609 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1610 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1611 int *exception, int *outfd, int *ms)
1613 struct timeval start = { 0 , 0 };
1614 struct pollfd *pfds;
1615 int res;
1616 long rms;
1617 int x, y, max;
1618 int sz;
1619 time_t now = 0;
1620 long whentohangup = 0, diff;
1621 struct ast_channel *winner = NULL;
1622 struct fdmap {
1623 int chan;
1624 int fdno;
1625 } *fdmap;
1627 sz = n * AST_MAX_FDS + nfds;
1628 pfds = alloca(sizeof(*pfds) * sz);
1629 fdmap = alloca(sizeof(*fdmap) * sz);
1631 if (outfd)
1632 *outfd = -99999;
1633 if (exception)
1634 *exception = 0;
1636 /* Perform any pending masquerades */
1637 for (x=0; x < n; x++) {
1638 ast_channel_lock(c[x]);
1639 if (c[x]->masq) {
1640 if (ast_do_masquerade(c[x])) {
1641 ast_log(LOG_WARNING, "Masquerade failed\n");
1642 *ms = -1;
1643 ast_channel_unlock(c[x]);
1644 return NULL;
1647 if (c[x]->whentohangup) {
1648 if (!whentohangup)
1649 time(&now);
1650 diff = c[x]->whentohangup - now;
1651 if (diff < 1) {
1652 /* Should already be hungup */
1653 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1654 ast_channel_unlock(c[x]);
1655 return c[x];
1657 if (!whentohangup || (diff < whentohangup))
1658 whentohangup = diff;
1660 ast_channel_unlock(c[x]);
1662 /* Wait full interval */
1663 rms = *ms;
1664 if (whentohangup) {
1665 rms = (whentohangup - now) * 1000; /* timeout in milliseconds */
1666 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1667 rms = *ms;
1670 * Build the pollfd array, putting the channels' fds first,
1671 * followed by individual fds. Order is important because
1672 * individual fd's must have priority over channel fds.
1674 max = 0;
1675 for (x=0; x<n; x++) {
1676 for (y=0; y<AST_MAX_FDS; y++) {
1677 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1678 fdmap[max].chan = x; /* channel x is linked to this pfds */
1679 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1681 CHECK_BLOCKING(c[x]);
1683 /* Add the individual fds */
1684 for (x=0; x<nfds; x++) {
1685 fdmap[max].chan = -1;
1686 max += ast_add_fd(&pfds[max], fds[x]);
1689 if (*ms > 0)
1690 start = ast_tvnow();
1692 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1693 do {
1694 int kbrms = rms;
1695 if (kbrms > 600000)
1696 kbrms = 600000;
1697 res = poll(pfds, max, kbrms);
1698 if (!res)
1699 rms -= kbrms;
1700 } while (!res && (rms > 0));
1701 } else {
1702 res = poll(pfds, max, rms);
1704 for (x=0; x<n; x++)
1705 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1706 if (res < 0) { /* Simulate a timeout if we were interrupted */
1707 if (errno != EINTR)
1708 *ms = -1;
1709 return NULL;
1711 if (whentohangup) { /* if we have a timeout, check who expired */
1712 time(&now);
1713 for (x=0; x<n; x++) {
1714 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1715 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1716 if (winner == NULL)
1717 winner = c[x];
1721 if (res == 0) { /* no fd ready, reset timeout and done */
1722 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1723 return winner;
1726 * Then check if any channel or fd has a pending event.
1727 * Remember to check channels first and fds last, as they
1728 * must have priority on setting 'winner'
1730 for (x = 0; x < max; x++) {
1731 res = pfds[x].revents;
1732 if (res == 0)
1733 continue;
1734 if (fdmap[x].chan >= 0) { /* this is a channel */
1735 winner = c[fdmap[x].chan]; /* override previous winners */
1736 if (res & POLLPRI)
1737 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1738 else
1739 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1740 winner->fdno = fdmap[x].fdno;
1741 } else { /* this is an fd */
1742 if (outfd)
1743 *outfd = pfds[x].fd;
1744 if (exception)
1745 *exception = (res & POLLPRI) ? -1 : 0;
1746 winner = NULL;
1749 if (*ms > 0) {
1750 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1751 if (*ms < 0)
1752 *ms = 0;
1754 return winner;
1757 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1759 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1762 int ast_waitfor(struct ast_channel *c, int ms)
1764 int oldms = ms; /* -1 if no timeout */
1766 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1767 if ((ms < 0) && (oldms < 0))
1768 ms = 0;
1769 return ms;
1772 /* XXX never to be called with ms = -1 */
1773 int ast_waitfordigit(struct ast_channel *c, int ms)
1775 return ast_waitfordigit_full(c, ms, -1, -1);
1778 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1780 int res = -1;
1781 #ifdef HAVE_ZAPTEL
1782 if (c->timingfd > -1) {
1783 if (!func) {
1784 samples = 0;
1785 data = 0;
1787 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1788 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1789 c->timingfunc = func;
1790 c->timingdata = data;
1792 #endif
1793 return res;
1796 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1799 /* Stop if we're a zombie or need a soft hangup */
1800 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1801 return -1;
1802 /* Wait for a digit, no more than ms milliseconds total. */
1803 while (ms) {
1804 struct ast_channel *rchan;
1805 int outfd;
1807 errno = 0;
1808 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1809 if (!rchan && outfd < 0 && ms) {
1810 if (errno == 0 || errno == EINTR)
1811 continue;
1812 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1813 return -1;
1814 } else if (outfd > -1) {
1815 /* The FD we were watching has something waiting */
1816 return 1;
1817 } else if (rchan) {
1818 int res;
1819 struct ast_frame *f = ast_read(c);
1820 if (!f)
1821 return -1;
1823 switch(f->frametype) {
1824 case AST_FRAME_DTMF:
1825 res = f->subclass;
1826 ast_frfree(f);
1827 return res;
1828 case AST_FRAME_CONTROL:
1829 switch(f->subclass) {
1830 case AST_CONTROL_HANGUP:
1831 ast_frfree(f);
1832 return -1;
1833 case AST_CONTROL_RINGING:
1834 case AST_CONTROL_ANSWER:
1835 /* Unimportant */
1836 break;
1837 default:
1838 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1840 case AST_FRAME_VOICE:
1841 /* Write audio if appropriate */
1842 if (audiofd > -1)
1843 write(audiofd, f->data, f->datalen);
1845 /* Ignore */
1846 ast_frfree(f);
1849 return 0; /* Time is up */
1852 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1854 struct ast_frame *f = NULL; /* the return value */
1855 int blah;
1856 int prestate;
1858 /* this function is very long so make sure there is only one return
1859 * point at the end (there is only one exception to this).
1861 ast_channel_lock(chan);
1862 if (chan->masq) {
1863 if (ast_do_masquerade(chan)) {
1864 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1865 } else {
1866 f = &ast_null_frame;
1868 goto done;
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 goto done;
1877 prestate = chan->_state;
1879 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1880 /* We have DTMF that has been deferred. Return it now */
1881 chan->dtmff.frametype = AST_FRAME_DTMF;
1882 chan->dtmff.subclass = chan->dtmfq[0];
1883 /* Drop first digit from the buffer */
1884 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1885 f = &chan->dtmff;
1886 goto done;
1889 /* Read and ignore anything on the alertpipe, but read only
1890 one sizeof(blah) per frame that we send from it */
1891 if (chan->alertpipe[0] > -1)
1892 read(chan->alertpipe[0], &blah, sizeof(blah));
1894 #ifdef HAVE_ZAPTEL
1895 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1896 int res;
1898 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1899 blah = -1;
1900 /* IF we can't get event, assume it's an expired as-per the old interface */
1901 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1902 if (res)
1903 blah = ZT_EVENT_TIMER_EXPIRED;
1905 if (blah == ZT_EVENT_TIMER_PING) {
1906 if (!chan->readq || !chan->readq->next) {
1907 /* Acknowledge PONG unless we need it again */
1908 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1909 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1912 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1913 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1914 if (chan->timingfunc) {
1915 /* save a copy of func/data before unlocking the channel */
1916 int (*func)(void *) = chan->timingfunc;
1917 void *data = chan->timingdata;
1918 ast_channel_unlock(chan);
1919 func(data);
1920 } else {
1921 blah = 0;
1922 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1923 chan->timingdata = NULL;
1924 ast_channel_unlock(chan);
1926 /* cannot 'goto done' because the channel is already unlocked */
1927 return &ast_null_frame;
1928 } else
1929 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1930 } else
1931 #endif
1932 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
1933 /* if the AST_GENERATOR_FD is set, call the generator with args
1934 * set to -1 so it can do whatever it needs to.
1936 void *tmp = chan->generatordata;
1937 chan->generatordata = NULL; /* reset to let ast_write get through */
1938 chan->generator->generate(chan, tmp, -1, -1);
1939 chan->generatordata = tmp;
1940 f = &ast_null_frame;
1941 goto done;
1944 /* Check for pending read queue */
1945 if (chan->readq) {
1946 f = chan->readq;
1947 chan->readq = f->next;
1948 f->next = NULL;
1949 /* Interpret hangup and return NULL */
1950 /* XXX why not the same for frames from the channel ? */
1951 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
1952 ast_frfree(f);
1953 f = NULL;
1955 } else {
1956 chan->blocker = pthread_self();
1957 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1958 if (chan->tech->exception)
1959 f = chan->tech->exception(chan);
1960 else {
1961 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1962 f = &ast_null_frame;
1964 /* Clear the exception flag */
1965 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1966 } else if (chan->tech->read)
1967 f = chan->tech->read(chan);
1968 else
1969 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1972 if (f) {
1973 /* if the channel driver returned more than one frame, stuff the excess
1974 into the readq for the next ast_read call
1976 if (f->next) {
1977 chan->readq = f->next;
1978 f->next = NULL;
1981 switch (f->frametype) {
1982 case AST_FRAME_CONTROL:
1983 if (f->subclass == AST_CONTROL_ANSWER) {
1984 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1985 ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
1986 ast_frfree(f);
1987 f = &ast_null_frame;
1988 } else if (prestate == AST_STATE_UP) {
1989 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1990 ast_frfree(f);
1991 f = &ast_null_frame;
1992 } else {
1993 /* Answer the CDR */
1994 ast_setstate(chan, AST_STATE_UP);
1995 ast_cdr_answer(chan->cdr);
1998 break;
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;
2004 else
2005 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2006 ast_frfree(f);
2007 f = &ast_null_frame;
2009 break;
2010 case AST_FRAME_DTMF_BEGIN:
2011 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2012 break;
2013 case AST_FRAME_DTMF_END:
2014 ast_log(LOG_DTMF, "DTMF end '%c' received on %s\n", f->subclass, chan->name);
2015 break;
2016 case AST_FRAME_VOICE:
2017 if (dropaudio) {
2018 ast_frfree(f);
2019 f = &ast_null_frame;
2020 } else if (!(f->subclass & chan->nativeformats)) {
2021 /* This frame can't be from the current native formats -- drop it on the
2022 floor */
2023 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2024 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2025 ast_frfree(f);
2026 f = &ast_null_frame;
2027 } else {
2028 if (chan->spies)
2029 queue_frame_to_spies(chan, f, SPY_READ);
2031 if (chan->monitor && chan->monitor->read_stream ) {
2032 /* XXX what does this do ? */
2033 #ifndef MONITOR_CONSTANT_DELAY
2034 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2035 if (jump >= 0) {
2036 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2037 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2038 chan->insmpl += jump + 4 * f->samples;
2039 } else
2040 chan->insmpl+= f->samples;
2041 #else
2042 int jump = chan->outsmpl - chan->insmpl;
2043 if (jump - MONITOR_DELAY >= 0) {
2044 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2045 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2046 chan->insmpl += jump;
2047 } else
2048 chan->insmpl += f->samples;
2049 #endif
2050 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2051 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2052 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2056 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2057 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)) {
2062 void *tmp = chan->generatordata;
2063 int res;
2065 if (chan->timingfunc) {
2066 if (option_debug > 1)
2067 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2068 ast_settimeout(chan, 0, NULL, NULL);
2071 chan->generatordata = NULL; /* reset, to let writes go through */
2072 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2073 chan->generatordata = tmp;
2074 if (res) {
2075 if (option_debug > 1)
2076 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2077 ast_deactivate_generator(chan);
2080 } else if (f->frametype == AST_FRAME_CNG) {
2081 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2082 if (option_debug > 1)
2083 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2084 ast_settimeout(chan, 160, generator_force, chan);
2089 } else {
2090 /* Make sure we always return NULL in the future */
2091 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2092 if (chan->generator)
2093 ast_deactivate_generator(chan);
2094 /* End the CDR if appropriate */
2095 if (chan->cdr)
2096 ast_cdr_end(chan->cdr);
2099 /* High bit prints debugging */
2100 if (chan->fin & DEBUGCHAN_FLAG)
2101 ast_frame_dump(chan->name, f, "<<");
2102 chan->fin = FRAMECOUNT_INC(chan->fin);
2104 done:
2105 ast_channel_unlock(chan);
2106 return f;
2109 int ast_internal_timing_enabled(struct ast_channel *chan)
2111 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2112 if (option_debug > 4)
2113 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);
2114 return ret;
2117 struct ast_frame *ast_read(struct ast_channel *chan)
2119 return __ast_read(chan, 0);
2122 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2124 return __ast_read(chan, 1);
2127 int ast_indicate(struct ast_channel *chan, int condition)
2129 return ast_indicate_data(chan, condition, NULL, 0);
2132 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2134 int res = -1;
2136 ast_channel_lock(chan);
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_channel_unlock(chan);
2140 return -1;
2142 if (chan->tech->indicate)
2143 res = chan->tech->indicate(chan, condition, data, datalen);
2144 ast_channel_unlock(chan);
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 ast_playtones_stop(chan);
2152 else {
2153 const struct tone_zone_sound *ts = NULL;
2154 switch (condition) {
2155 case AST_CONTROL_RINGING:
2156 ts = ast_get_indication_tone(chan->zone, "ring");
2157 break;
2158 case AST_CONTROL_BUSY:
2159 ts = ast_get_indication_tone(chan->zone, "busy");
2160 break;
2161 case AST_CONTROL_CONGESTION:
2162 ts = ast_get_indication_tone(chan->zone, "congestion");
2163 break;
2165 if (ts && ts->data[0]) {
2166 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2167 ast_playtones_start(chan,0,ts->data, 1);
2168 res = 0;
2169 } else if (condition == AST_CONTROL_PROGRESS) {
2170 /* ast_playtones_stop(chan); */
2171 } else if (condition == AST_CONTROL_PROCEEDING) {
2172 /* Do nothing, really */
2173 } else if (condition == AST_CONTROL_HOLD) {
2174 /* Do nothing.... */
2175 } else if (condition == AST_CONTROL_UNHOLD) {
2176 /* Do nothing.... */
2177 } else if (condition == AST_CONTROL_VIDUPDATE) {
2178 /* Do nothing.... */
2179 } else {
2180 /* not handled */
2181 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2182 res = -1;
2186 return res;
2189 int ast_recvchar(struct ast_channel *chan, int timeout)
2191 int c;
2192 char *buf = ast_recvtext(chan, timeout);
2193 if (buf == NULL)
2194 return -1; /* error or timeout */
2195 c = *(unsigned char *)buf;
2196 free(buf);
2197 return c;
2200 char *ast_recvtext(struct ast_channel *chan, int timeout)
2202 int res, done = 0;
2203 char *buf = NULL;
2205 while (!done) {
2206 struct ast_frame *f;
2207 if (ast_check_hangup(chan))
2208 break;
2209 res = ast_waitfor(chan, timeout);
2210 if (res <= 0) /* timeout or error */
2211 break;
2212 timeout = res; /* update timeout */
2213 f = ast_read(chan);
2214 if (f == NULL)
2215 break; /* no frame */
2216 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2217 done = 1; /* force a break */
2218 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2219 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2220 done = 1;
2222 ast_frfree(f);
2224 return buf;
2227 int ast_sendtext(struct ast_channel *chan, const char *text)
2229 int res = 0;
2230 /* Stop if we're a zombie or need a soft hangup */
2231 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2232 return -1;
2233 CHECK_BLOCKING(chan);
2234 if (chan->tech->send_text)
2235 res = chan->tech->send_text(chan, text);
2236 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2237 return res;
2240 static int do_senddigit(struct ast_channel *chan, char digit)
2242 int res = -1;
2244 if (chan->tech->send_digit)
2245 res = chan->tech->send_digit(chan, digit);
2246 if (res) {
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);
2276 else {
2277 /* not handled */
2278 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2281 return 0;
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 };
2292 char nothing[128];
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;
2299 a.src = "ast_prod";
2300 if (ast_write(chan, &a))
2301 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2303 return 0;
2306 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2308 int res;
2309 if (!chan->tech->write_video)
2310 return 0;
2311 res = ast_write(chan, fr);
2312 if (!res)
2313 res = 1;
2314 return res;
2317 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2319 int res = -1;
2320 struct ast_frame *f = NULL;
2322 /* Stop if we're a zombie or need a soft hangup */
2323 ast_channel_lock(chan);
2324 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2325 goto done;
2327 /* Handle any pending masquerades */
2328 if (chan->masq && ast_do_masquerade(chan)) {
2329 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2330 goto done;
2332 if (chan->masqr) {
2333 res = 0; /* XXX explain, why 0 ? */
2334 goto done;
2336 if (chan->generatordata) {
2337 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2338 ast_deactivate_generator(chan);
2339 else {
2340 res = 0; /* XXX explain, why 0 ? */
2341 goto done;
2344 /* High bit prints debugging */
2345 if (chan->fout & DEBUGCHAN_FLAG)
2346 ast_frame_dump(chan->name, fr, ">>");
2347 CHECK_BLOCKING(chan);
2348 switch(fr->frametype) {
2349 case AST_FRAME_CONTROL:
2350 /* XXX Interpret control frames XXX */
2351 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
2352 break;
2353 case AST_FRAME_DTMF_BEGIN:
2354 res = (chan->tech->send_digit_begin == NULL) ? 0 :
2355 chan->tech->send_digit_begin(chan, fr->subclass);
2356 break;
2357 case AST_FRAME_DTMF_END:
2358 res = (chan->tech->send_digit_end == NULL) ? 0 :
2359 chan->tech->send_digit_end(chan);
2360 break;
2361 case AST_FRAME_DTMF:
2362 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2363 ast_channel_unlock(chan);
2364 res = do_senddigit(chan,fr->subclass);
2365 ast_channel_lock(chan);
2366 CHECK_BLOCKING(chan);
2367 break;
2368 case AST_FRAME_TEXT:
2369 res = (chan->tech->send_text == NULL) ? 0 :
2370 chan->tech->send_text(chan, (char *) fr->data);
2371 break;
2372 case AST_FRAME_HTML:
2373 res = (chan->tech->send_html == NULL) ? 0 :
2374 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2375 break;
2376 case AST_FRAME_VIDEO:
2377 /* XXX Handle translation of video codecs one day XXX */
2378 res = (chan->tech->write_video == NULL) ? 0 :
2379 chan->tech->write_video(chan, fr);
2380 break;
2381 case AST_FRAME_MODEM:
2382 res = (chan->tech->write == NULL) ? 0 :
2383 chan->tech->write(chan, fr);
2384 break;
2385 case AST_FRAME_VOICE:
2386 if (chan->tech->write == NULL)
2387 break; /*! \todo XXX should return 0 maybe ? */
2389 /* Bypass translator if we're writing format in the raw write format. This
2390 allows mixing of native / non-native formats */
2391 if (fr->subclass == chan->rawwriteformat)
2392 f = fr;
2393 else
2394 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2395 if (f == NULL) {
2396 res = 0;
2397 } else {
2398 if (chan->spies)
2399 queue_frame_to_spies(chan, f, SPY_WRITE);
2401 if (chan->monitor && chan->monitor->write_stream) {
2402 /* XXX must explain this code */
2403 #ifndef MONITOR_CONSTANT_DELAY
2404 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2405 if (jump >= 0) {
2406 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2407 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2408 chan->outsmpl += jump + 4 * f->samples;
2409 } else
2410 chan->outsmpl += f->samples;
2411 #else
2412 int jump = chan->insmpl - chan->outsmpl;
2413 if (jump - MONITOR_DELAY >= 0) {
2414 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2415 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2416 chan->outsmpl += jump;
2417 } else
2418 chan->outsmpl += f->samples;
2419 #endif
2420 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2421 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2422 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2426 res = chan->tech->write(chan, f);
2428 break;
2431 if (f && f != fr)
2432 ast_frfree(f);
2433 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2434 /* Consider a write failure to force a soft hangup */
2435 if (res < 0)
2436 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2437 else {
2438 chan->fout = FRAMECOUNT_INC(chan->fout);
2440 done:
2441 ast_channel_unlock(chan);
2442 return res;
2445 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2446 struct ast_trans_pvt **trans, const int direction)
2448 int native;
2449 int res;
2451 /* Make sure we only consider audio */
2452 fmt &= AST_FORMAT_AUDIO_MASK;
2454 native = chan->nativeformats;
2455 /* Find a translation path from the native format to one of the desired formats */
2456 if (!direction)
2457 /* reading */
2458 res = ast_translator_best_choice(&fmt, &native);
2459 else
2460 /* writing */
2461 res = ast_translator_best_choice(&native, &fmt);
2463 if (res < 0) {
2464 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2465 ast_getformatname(native), ast_getformatname(fmt));
2466 return -1;
2469 /* Now we have a good choice for both. */
2470 ast_channel_lock(chan);
2471 *rawformat = native;
2472 /* User perspective is fmt */
2473 *format = fmt;
2474 /* Free any read translation we have right now */
2475 if (*trans)
2476 ast_translator_free_path(*trans);
2477 /* Build a translation path from the raw format to the desired format */
2478 if (!direction)
2479 /* reading */
2480 *trans = ast_translator_build_path(*format, *rawformat);
2481 else
2482 /* writing */
2483 *trans = ast_translator_build_path(*rawformat, *format);
2484 ast_channel_unlock(chan);
2485 if (option_debug)
2486 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2487 direction ? "write" : "read", ast_getformatname(fmt));
2488 return 0;
2491 int ast_set_read_format(struct ast_channel *chan, int fmt)
2493 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2494 &chan->readtrans, 0);
2497 int ast_set_write_format(struct ast_channel *chan, int fmt)
2499 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2500 &chan->writetrans, 1);
2503 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)
2505 int dummy_outstate;
2506 int cause = 0;
2507 struct ast_channel *chan;
2508 int res = 0;
2510 if (outstate)
2511 *outstate = 0;
2512 else
2513 outstate = &dummy_outstate; /* make outstate always a valid pointer */
2515 chan = ast_request(type, format, data, &cause);
2516 if (!chan) {
2517 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2518 /* compute error and return */
2519 if (cause == AST_CAUSE_BUSY)
2520 *outstate = AST_CONTROL_BUSY;
2521 else if (cause == AST_CAUSE_CONGESTION)
2522 *outstate = AST_CONTROL_CONGESTION;
2523 return NULL;
2526 if (oh) {
2527 if (oh->vars)
2528 ast_set_variables(chan, oh->vars);
2529 /* XXX why is this necessary, for the parent_channel perhaps ? */
2530 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2531 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2532 if (oh->parent_channel)
2533 ast_channel_inherit_variables(oh->parent_channel, chan);
2534 if (oh->account)
2535 ast_cdr_setaccount(chan, oh->account);
2537 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2539 if (ast_call(chan, data, 0)) { /* ast_call failed... */
2540 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2541 } else {
2542 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
2543 while (timeout && chan->_state != AST_STATE_UP) {
2544 struct ast_frame *f;
2545 res = ast_waitfor(chan, timeout);
2546 if (res <= 0) /* error, timeout, or done */
2547 break;
2548 if (timeout > -1)
2549 timeout = res;
2550 f = ast_read(chan);
2551 if (!f) {
2552 *outstate = AST_CONTROL_HANGUP;
2553 res = 0;
2554 break;
2556 if (f->frametype == AST_FRAME_CONTROL) {
2557 switch (f->subclass) {
2558 case AST_CONTROL_RINGING: /* record but keep going */
2559 *outstate = f->subclass;
2560 break;
2562 case AST_CONTROL_BUSY:
2563 case AST_CONTROL_CONGESTION:
2564 case AST_CONTROL_ANSWER:
2565 *outstate = f->subclass;
2566 timeout = 0; /* trick to force exit from the while() */
2567 break;
2569 /* Ignore these */
2570 case AST_CONTROL_PROGRESS:
2571 case AST_CONTROL_PROCEEDING:
2572 case AST_CONTROL_HOLD:
2573 case AST_CONTROL_UNHOLD:
2574 case AST_CONTROL_VIDUPDATE:
2575 case -1: /* Ignore -- just stopping indications */
2576 break;
2578 default:
2579 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2582 ast_frfree(f);
2586 /* Final fixups */
2587 if (oh) {
2588 if (!ast_strlen_zero(oh->context))
2589 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2590 if (!ast_strlen_zero(oh->exten))
2591 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2592 if (oh->priority)
2593 chan->priority = oh->priority;
2595 if (chan->_state == AST_STATE_UP)
2596 *outstate = AST_CONTROL_ANSWER;
2598 if (res <= 0) {
2599 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2600 ast_cdr_init(chan->cdr, chan);
2601 if (chan->cdr) {
2602 char tmp[256];
2603 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2604 ast_cdr_setapp(chan->cdr,"Dial",tmp);
2605 ast_cdr_update(chan);
2606 ast_cdr_start(chan->cdr);
2607 ast_cdr_end(chan->cdr);
2608 /* If the cause wasn't handled properly */
2609 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2610 ast_cdr_failed(chan->cdr);
2612 ast_hangup(chan);
2613 chan = NULL;
2615 return chan;
2618 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2620 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2623 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2625 struct chanlist *chan;
2626 struct ast_channel *c;
2627 int capabilities;
2628 int fmt;
2629 int res;
2630 int foo;
2631 int videoformat = format & AST_FORMAT_VIDEO_MASK;
2633 if (!cause)
2634 cause = &foo;
2635 *cause = AST_CAUSE_NOTDEFINED;
2637 if (AST_LIST_LOCK(&channels)) {
2638 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2639 return NULL;
2642 AST_LIST_TRAVERSE(&backends, chan, list) {
2643 if (strcasecmp(type, chan->tech->type))
2644 continue;
2646 capabilities = chan->tech->capabilities;
2647 fmt = format & AST_FORMAT_AUDIO_MASK;
2648 res = ast_translator_best_choice(&fmt, &capabilities);
2649 if (res < 0) {
2650 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2651 AST_LIST_UNLOCK(&channels);
2652 return NULL;
2654 AST_LIST_UNLOCK(&channels);
2655 if (!chan->tech->requester)
2656 return NULL;
2658 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
2659 return NULL;
2661 if (c->_state == AST_STATE_DOWN) {
2662 manager_event(EVENT_FLAG_CALL, "Newchannel",
2663 "Channel: %s\r\n"
2664 "State: %s\r\n"
2665 "CallerID: %s\r\n"
2666 "CallerIDName: %s\r\n"
2667 "Uniqueid: %s\r\n",
2668 c->name, ast_state2str(c->_state),
2669 S_OR(c->cid.cid_num, "<unknown>"),
2670 S_OR(c->cid.cid_name, "<unknown>"),
2671 c->uniqueid);
2673 return c;
2676 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2677 *cause = AST_CAUSE_NOSUCHDRIVER;
2678 AST_LIST_UNLOCK(&channels);
2680 return NULL;
2683 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2685 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2686 If the remote end does not answer within the timeout, then do NOT hang up, but
2687 return anyway. */
2688 int res = -1;
2689 /* Stop if we're a zombie or need a soft hangup */
2690 ast_channel_lock(chan);
2691 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2692 if (chan->tech->call)
2693 res = chan->tech->call(chan, addr, timeout);
2694 ast_set_flag(chan, AST_FLAG_OUTGOING);
2696 ast_channel_unlock(chan);
2697 return res;
2701 \brief Transfer a call to dest, if the channel supports transfer
2703 Called by:
2704 \arg app_transfer
2705 \arg the manager interface
2707 int ast_transfer(struct ast_channel *chan, char *dest)
2709 int res = -1;
2711 /* Stop if we're a zombie or need a soft hangup */
2712 ast_channel_lock(chan);
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);
2716 if (!res)
2717 res = 1;
2718 } else
2719 res = 0;
2721 ast_channel_unlock(chan);
2722 return res;
2725 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2727 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
2730 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2732 int pos = 0; /* index in the buffer where we accumulate digits */
2733 int to = ftimeout;
2735 /* Stop if we're a zombie or need a soft hangup */
2736 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2737 return -1;
2738 if (!len)
2739 return -1;
2740 for (;;) {
2741 int d;
2742 if (c->stream) {
2743 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2744 ast_stopstream(c);
2745 usleep(1000);
2746 if (!d)
2747 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2748 } else {
2749 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2751 if (d < 0)
2752 return -1;
2753 if (d == 0) {
2754 s[pos]='\0';
2755 return 1;
2757 if (d == 1) {
2758 s[pos]='\0';
2759 return 2;
2761 if (!strchr(enders, d))
2762 s[pos++] = d;
2763 if (strchr(enders, d) || (pos >= len)) {
2764 s[pos]='\0';
2765 return 0;
2767 to = timeout;
2769 /* Never reached */
2770 return 0;
2773 int ast_channel_supports_html(struct ast_channel *chan)
2775 return (chan->tech->send_html) ? 1 : 0;
2778 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2780 if (chan->tech->send_html)
2781 return chan->tech->send_html(chan, subclass, data, datalen);
2782 return -1;
2785 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2787 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
2790 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2792 int src;
2793 int dst;
2795 /* Set up translation from the chan to the peer */
2796 src = chan->nativeformats;
2797 dst = peer->nativeformats;
2798 if (ast_translator_best_choice(&dst, &src) < 0) {
2799 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2800 return -1;
2803 /* if the best path is not 'pass through', then
2804 transcoding is needed; if desired, force transcode path
2805 to use SLINEAR between channels, but only if there is
2806 no direct conversion available */
2807 if ((src != dst) && ast_opt_transcode_via_slin &&
2808 (ast_translate_path_steps(dst, src) != 1))
2809 dst = AST_FORMAT_SLINEAR;
2810 if (ast_set_read_format(chan, dst) < 0) {
2811 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2812 return -1;
2814 if (ast_set_write_format(peer, dst) < 0) {
2815 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2816 return -1;
2819 /* Set up translation from the peer to the chan */
2820 src = peer->nativeformats;
2821 dst = chan->nativeformats;
2822 if (ast_translator_best_choice(&dst, &src) < 0) {
2823 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2824 return -1;
2827 /* if the best path is not 'pass through', then
2828 transcoding is needed; if desired, force transcode path
2829 to use SLINEAR between channels, but only if there is
2830 no direct conversion available */
2831 if ((src != dst) && ast_opt_transcode_via_slin &&
2832 (ast_translate_path_steps(dst, src) != 1))
2833 dst = AST_FORMAT_SLINEAR;
2834 if (ast_set_read_format(peer, dst) < 0) {
2835 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2836 return -1;
2838 if (ast_set_write_format(chan, dst) < 0) {
2839 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2840 return -1;
2842 return 0;
2845 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2847 int res = -1;
2848 struct ast_channel *final_orig = original, *final_clone = clone;
2850 ast_channel_lock(original);
2851 while (ast_channel_trylock(clone)) {
2852 ast_channel_unlock(original);
2853 usleep(1);
2854 ast_channel_lock(original);
2857 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
2858 and if so, we don't really want to masquerade it, but its proxy */
2859 if (original->_bridge && (original->_bridge != ast_bridged_channel(original)))
2860 final_orig = original->_bridge;
2862 if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)))
2863 final_clone = clone->_bridge;
2865 if ((final_orig != original) || (final_clone != clone)) {
2866 ast_channel_lock(final_orig);
2867 while (ast_channel_trylock(final_clone)) {
2868 ast_channel_unlock(final_orig);
2869 usleep(1);
2870 ast_channel_lock(final_orig);
2872 ast_channel_unlock(clone);
2873 ast_channel_unlock(original);
2874 original = final_orig;
2875 clone = final_clone;
2878 if (original == clone) {
2879 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2880 ast_channel_unlock(clone);
2881 ast_channel_unlock(original);
2882 return -1;
2885 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
2886 clone->name, original->name);
2887 if (original->masq) {
2888 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2889 original->masq->name, original->name);
2890 } else if (clone->masqr) {
2891 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2892 clone->name, clone->masqr->name);
2893 } else {
2894 original->masq = clone;
2895 clone->masqr = original;
2896 ast_queue_frame(original, &ast_null_frame);
2897 ast_queue_frame(clone, &ast_null_frame);
2898 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
2899 res = 0;
2902 ast_channel_unlock(clone);
2903 ast_channel_unlock(original);
2905 return res;
2908 void ast_change_name(struct ast_channel *chan, char *newname)
2910 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
2911 ast_string_field_set(chan, name, newname);
2914 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2916 struct ast_var_t *current, *newvar;
2917 const char *varname;
2919 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2920 int vartype = 0;
2922 varname = ast_var_full_name(current);
2923 if (!varname)
2924 continue;
2926 if (varname[0] == '_') {
2927 vartype = 1;
2928 if (varname[1] == '_')
2929 vartype = 2;
2932 switch (vartype) {
2933 case 1:
2934 newvar = ast_var_assign(&varname[1], ast_var_value(current));
2935 if (newvar) {
2936 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2937 if (option_debug)
2938 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2940 break;
2941 case 2:
2942 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2943 if (newvar) {
2944 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2945 if (option_debug)
2946 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2948 break;
2949 default:
2950 if (option_debug)
2951 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2952 break;
2958 \brief Clone channel variables from 'clone' channel into 'original' channel
2960 All variables except those related to app_groupcount are cloned.
2961 Variables are actually _removed_ from 'clone' channel, presumably
2962 because it will subsequently be destroyed.
2964 \note Assumes locks will be in place on both channels when called.
2966 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2968 struct ast_var_t *varptr;
2970 /* we need to remove all app_groupcount related variables from the original
2971 channel before merging in the clone's variables; any groups assigned to the
2972 original channel should be released, only those assigned to the clone
2973 should remain
2976 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2977 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2978 AST_LIST_REMOVE(&original->varshead, varptr, entries);
2979 ast_var_delete(varptr);
2982 AST_LIST_TRAVERSE_SAFE_END;
2984 /* Append variables from clone channel into original channel */
2985 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2986 if (AST_LIST_FIRST(&clone->varshead))
2987 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2991 \brief Masquerade a channel
2993 \note Assumes channel will be locked when called
2995 int ast_do_masquerade(struct ast_channel *original)
2997 int x,i;
2998 int res=0;
2999 int origstate;
3000 struct ast_frame *cur, *prev;
3001 const struct ast_channel_tech *t;
3002 void *t_pvt;
3003 struct ast_callerid tmpcid;
3004 struct ast_channel *clone = original->masq;
3005 int rformat = original->readformat;
3006 int wformat = original->writeformat;
3007 char newn[100];
3008 char orig[100];
3009 char masqn[100];
3010 char zombn[100];
3012 if (option_debug > 3)
3013 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3014 clone->name, clone->_state, original->name, original->_state);
3016 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3017 the clone channel into the original channel. Start by killing off the original
3018 channel's backend. I'm not sure we're going to keep this function, because
3019 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3021 /* We need the clone's lock, too */
3022 ast_channel_lock(clone);
3024 if (option_debug > 1)
3025 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3027 /* Having remembered the original read/write formats, we turn off any translation on either
3028 one */
3029 free_translation(clone);
3030 free_translation(original);
3033 /* Unlink the masquerade */
3034 original->masq = NULL;
3035 clone->masqr = NULL;
3037 /* Save the original name */
3038 ast_copy_string(orig, original->name, sizeof(orig));
3039 /* Save the new name */
3040 ast_copy_string(newn, clone->name, sizeof(newn));
3041 /* Create the masq name */
3042 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3044 /* Copy the name from the clone channel */
3045 ast_string_field_set(original, name, newn);
3047 /* Mangle the name of the clone channel */
3048 ast_string_field_set(clone, name, masqn);
3050 /* Notify any managers of the change, first the masq then the other */
3051 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3052 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3054 /* Swap the technologies */
3055 t = original->tech;
3056 original->tech = clone->tech;
3057 clone->tech = t;
3059 t_pvt = original->tech_pvt;
3060 original->tech_pvt = clone->tech_pvt;
3061 clone->tech_pvt = t_pvt;
3063 /* Swap the readq's */
3064 cur = original->readq;
3065 original->readq = clone->readq;
3066 clone->readq = cur;
3068 /* Swap the alertpipes */
3069 for (i = 0; i < 2; i++) {
3070 x = original->alertpipe[i];
3071 original->alertpipe[i] = clone->alertpipe[i];
3072 clone->alertpipe[i] = x;
3075 /* Swap the raw formats */
3076 x = original->rawreadformat;
3077 original->rawreadformat = clone->rawreadformat;
3078 clone->rawreadformat = x;
3079 x = original->rawwriteformat;
3080 original->rawwriteformat = clone->rawwriteformat;
3081 clone->rawwriteformat = x;
3083 /* Save any pending frames on both sides. Start by counting
3084 * how many we're going to need... */
3085 prev = NULL;
3086 x = 0;
3087 for (cur = clone->readq; cur; cur = cur->next) {
3088 x++;
3089 prev = cur;
3091 /* If we had any, prepend them to the ones already in the queue, and
3092 * load up the alertpipe */
3093 if (prev) {
3094 prev->next = original->readq;
3095 original->readq = clone->readq;
3096 clone->readq = NULL;
3097 if (original->alertpipe[1] > -1) {
3098 for (i = 0; i < x; i++)
3099 write(original->alertpipe[1], &x, sizeof(x));
3102 clone->_softhangup = AST_SOFTHANGUP_DEV;
3105 /* And of course, so does our current state. Note we need not
3106 call ast_setstate since the event manager doesn't really consider
3107 these separate. We do this early so that the clone has the proper
3108 state of the original channel. */
3109 origstate = original->_state;
3110 original->_state = clone->_state;
3111 clone->_state = origstate;
3113 if (clone->tech->fixup){
3114 res = clone->tech->fixup(original, clone);
3115 if (res)
3116 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3119 /* Start by disconnecting the original's physical side */
3120 if (clone->tech->hangup)
3121 res = clone->tech->hangup(clone);
3122 if (res) {
3123 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
3124 ast_channel_unlock(clone);
3125 return -1;
3128 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3129 /* Mangle the name of the clone channel */
3130 ast_string_field_set(clone, name, zombn);
3131 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3133 /* Update the type. */
3134 t_pvt = original->monitor;
3135 original->monitor = clone->monitor;
3136 clone->monitor = t_pvt;
3138 /* Keep the same language. */
3139 ast_string_field_set(original, language, clone->language);
3140 /* Copy the FD's other than the generator fd */
3141 for (x = 0; x < AST_MAX_FDS; x++) {
3142 if (x != AST_GENERATOR_FD)
3143 original->fds[x] = clone->fds[x];
3145 /* Move data stores over */
3146 if (AST_LIST_FIRST(&clone->datastores))
3147 AST_LIST_INSERT_TAIL(&original->datastores, AST_LIST_FIRST(&clone->datastores), entry);
3148 AST_LIST_HEAD_INIT_NOLOCK(&clone->datastores);
3150 clone_variables(original, clone);
3151 AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3152 /* Presense of ADSI capable CPE follows clone */
3153 original->adsicpe = clone->adsicpe;
3154 /* Bridge remains the same */
3155 /* CDR fields remain the same */
3156 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3157 /* Application and data remain the same */
3158 /* Clone exception becomes real one, as with fdno */
3159 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3160 original->fdno = clone->fdno;
3161 /* Schedule context remains the same */
3162 /* Stream stuff stays the same */
3163 /* Keep the original state. The fixup code will need to work with it most likely */
3165 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3166 out. */
3167 tmpcid = original->cid;
3168 original->cid = clone->cid;
3169 clone->cid = tmpcid;
3171 /* Restore original timing file descriptor */
3172 original->fds[AST_TIMING_FD] = original->timingfd;
3174 /* Our native formats are different now */
3175 original->nativeformats = clone->nativeformats;
3177 /* Context, extension, priority, app data, jump table, remain the same */
3178 /* pvt switches. pbx stays the same, as does next */
3180 /* Set the write format */
3181 ast_set_write_format(original, wformat);
3183 /* Set the read format */
3184 ast_set_read_format(original, rformat);
3186 /* Copy the music class */
3187 ast_string_field_set(original, musicclass, clone->musicclass);
3189 if (option_debug)
3190 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3192 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3193 can fix up everything as best as possible */
3194 if (original->tech->fixup) {
3195 res = original->tech->fixup(clone, original);
3196 if (res) {
3197 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3198 original->tech->type, original->name);
3199 ast_channel_unlock(clone);
3200 return -1;
3202 } else
3203 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3204 original->tech->type, original->name);
3206 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3207 a zombie so nothing tries to touch it. If it's already been marked as a
3208 zombie, then free it now (since it already is considered invalid). */
3209 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3210 if (option_debug)
3211 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3212 ast_channel_unlock(clone);
3213 manager_event(EVENT_FLAG_CALL, "Hangup",
3214 "Channel: %s\r\n"
3215 "Uniqueid: %s\r\n"
3216 "Cause: %d\r\n"
3217 "Cause-txt: %s\r\n",
3218 clone->name,
3219 clone->uniqueid,
3220 clone->hangupcause,
3221 ast_cause2str(clone->hangupcause)
3223 ast_channel_free(clone);
3224 } else {
3225 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3226 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3227 ast_queue_frame(clone, &ast_null_frame);
3228 ast_channel_unlock(clone);
3231 /* Signal any blocker */
3232 if (ast_test_flag(original, AST_FLAG_BLOCKING))
3233 pthread_kill(original->blocker, SIGURG);
3234 if (option_debug)
3235 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3236 return 0;
3239 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3241 if (callerid) {
3242 if (chan->cid.cid_num)
3243 free(chan->cid.cid_num);
3244 chan->cid.cid_num = ast_strdup(callerid);
3246 if (calleridname) {
3247 if (chan->cid.cid_name)
3248 free(chan->cid.cid_name);
3249 chan->cid.cid_name = ast_strdup(calleridname);
3251 if (ani) {
3252 if (chan->cid.cid_ani)
3253 free(chan->cid.cid_ani);
3254 chan->cid.cid_ani = ast_strdup(ani);
3256 if (chan->cdr)
3257 ast_cdr_setcid(chan->cdr, chan);
3258 manager_event(EVENT_FLAG_CALL, "Newcallerid",
3259 "Channel: %s\r\n"
3260 "CallerID: %s\r\n"
3261 "CallerIDName: %s\r\n"
3262 "Uniqueid: %s\r\n"
3263 "CID-CallingPres: %d (%s)\r\n",
3264 chan->name,
3265 S_OR(chan->cid.cid_num, "<Unknown>"),
3266 S_OR(chan->cid.cid_name, "<Unknown>"),
3267 chan->uniqueid,
3268 chan->cid.cid_pres,
3269 ast_describe_caller_presentation(chan->cid.cid_pres)
3273 int ast_setstate(struct ast_channel *chan, int state)
3275 int oldstate = chan->_state;
3277 if (oldstate == state)
3278 return 0;
3280 chan->_state = state;
3281 ast_device_state_changed_literal(chan->name);
3282 manager_event(EVENT_FLAG_CALL,
3283 (oldstate == AST_STATE_DOWN) ? "Newchannel" : "Newstate",
3284 "Channel: %s\r\n"
3285 "State: %s\r\n"
3286 "CallerID: %s\r\n"
3287 "CallerIDName: %s\r\n"
3288 "Uniqueid: %s\r\n",
3289 chan->name, ast_state2str(chan->_state),
3290 S_OR(chan->cid.cid_num, "<unknown>"),
3291 S_OR(chan->cid.cid_name, "<unknown>"),
3292 chan->uniqueid);
3294 return 0;
3297 /*! \brief Find bridged channel */
3298 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3300 struct ast_channel *bridged;
3301 bridged = chan->_bridge;
3302 if (bridged && bridged->tech->bridged_channel)
3303 bridged = bridged->tech->bridged_channel(chan, bridged);
3304 return bridged;
3307 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3309 int min = 0, sec = 0, check;
3311 check = ast_autoservice_start(peer);
3312 if (check)
3313 return;
3315 if (remain > 0) {
3316 if (remain / 60 > 1) {
3317 min = remain / 60;
3318 sec = remain % 60;
3319 } else {
3320 sec = remain;
3324 if (!strcmp(sound,"timeleft")) { /* Queue support */
3325 ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
3326 if (min) {
3327 ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
3328 ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
3330 if (sec) {
3331 ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
3332 ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
3334 } else {
3335 ast_stream_and_wait(chan, sound, chan->language, "");
3338 ast_autoservice_stop(peer);
3341 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3342 struct ast_bridge_config *config, struct ast_frame **fo,
3343 struct ast_channel **rc, struct timeval bridge_end)
3345 /* Copy voice back and forth between the two channels. */
3346 struct ast_channel *cs[3];
3347 struct ast_frame *f;
3348 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3349 int o0nativeformats;
3350 int o1nativeformats;
3351 int watch_c0_dtmf;
3352 int watch_c1_dtmf;
3353 void *pvt0, *pvt1;
3354 /* Indicates whether a frame was queued into a jitterbuffer */
3355 int frame_put_in_jb = 0;
3356 int jb_in_use;
3357 int to;
3359 cs[0] = c0;
3360 cs[1] = c1;
3361 pvt0 = c0->tech_pvt;
3362 pvt1 = c1->tech_pvt;
3363 o0nativeformats = c0->nativeformats;
3364 o1nativeformats = c1->nativeformats;
3365 watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3366 watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3368 /* Check the need of a jitterbuffer for each channel */
3369 jb_in_use = ast_jb_do_usecheck(c0, c1);
3371 for (;;) {
3372 struct ast_channel *who, *other;
3374 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3375 (o0nativeformats != c0->nativeformats) ||
3376 (o1nativeformats != c1->nativeformats)) {
3377 /* Check for Masquerade, codec changes, etc */
3378 res = AST_BRIDGE_RETRY;
3379 break;
3381 if (bridge_end.tv_sec) {
3382 to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3383 if (to <= 0) {
3384 res = AST_BRIDGE_RETRY;
3385 break;
3387 } else
3388 to = -1;
3389 /* Calculate the appropriate max sleep interval - in general, this is the time,
3390 left to the closest jb delivery moment */
3391 if (jb_in_use)
3392 to = ast_jb_get_when_to_wakeup(c0, c1, to);
3393 who = ast_waitfor_n(cs, 2, &to);
3394 if (!who) {
3395 /* No frame received within the specified timeout - check if we have to deliver now */
3396 if (jb_in_use)
3397 ast_jb_get_and_deliver(c0, c1);
3398 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3399 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3400 c0->_softhangup = 0;
3401 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3402 c1->_softhangup = 0;
3403 c0->_bridge = c1;
3404 c1->_bridge = c0;
3406 continue;
3408 f = ast_read(who);
3409 if (!f) {
3410 *fo = NULL;
3411 *rc = who;
3412 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3413 break;
3416 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3417 /* Try add the frame info the who's bridged channel jitterbuff */
3418 if (jb_in_use)
3419 frame_put_in_jb = !ast_jb_put(other, f);
3421 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3422 int bridge_exit = 0;
3424 switch (f->subclass) {
3425 case AST_CONTROL_HOLD:
3426 case AST_CONTROL_UNHOLD:
3427 case AST_CONTROL_VIDUPDATE:
3428 ast_indicate_data(other, f->subclass, f->data, f->datalen);
3429 break;
3430 default:
3431 *fo = f;
3432 *rc = who;
3433 bridge_exit = 1;
3434 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3435 break;
3437 if (bridge_exit)
3438 break;
3440 if ((f->frametype == AST_FRAME_VOICE) ||
3441 (f->frametype == AST_FRAME_DTMF) ||
3442 (f->frametype == AST_FRAME_VIDEO) ||
3443 (f->frametype == AST_FRAME_IMAGE) ||
3444 (f->frametype == AST_FRAME_HTML) ||
3445 (f->frametype == AST_FRAME_MODEM) ||
3446 (f->frametype == AST_FRAME_TEXT)) {
3447 /* monitored dtmf causes exit from bridge */
3448 int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
3450 if (f->frametype == AST_FRAME_DTMF && monitored_source) {
3451 *fo = f;
3452 *rc = who;
3453 ast_log(LOG_DEBUG, "Got DTMF on channel (%s)\n", who->name);
3454 break;
3456 /* Write immediately frames, not passed through jb */
3457 if (!frame_put_in_jb)
3458 ast_write(other, f);
3460 /* Check if we have to deliver now */
3461 if (jb_in_use)
3462 ast_jb_get_and_deliver(c0, c1);
3464 /* XXX do we want to pass on also frames not matched above ? */
3465 ast_frfree(f);
3467 /* Swap who gets priority */
3468 cs[2] = cs[0];
3469 cs[0] = cs[1];
3470 cs[1] = cs[2];
3472 return res;
3475 /*! \brief Bridge two channels together */
3476 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3477 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
3479 struct ast_channel *who = NULL;
3480 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3481 int nativefailed=0;
3482 int firstpass;
3483 int o0nativeformats;
3484 int o1nativeformats;
3485 long time_left_ms=0;
3486 struct timeval nexteventts = { 0, };
3487 char caller_warning = 0;
3488 char callee_warning = 0;
3489 int to;
3491 if (c0->_bridge) {
3492 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3493 c0->name, c0->_bridge->name);
3494 return -1;
3496 if (c1->_bridge) {
3497 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3498 c1->name, c1->_bridge->name);
3499 return -1;
3502 /* Stop if we're a zombie or need a soft hangup */
3503 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3504 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3505 return -1;
3507 *fo = NULL;
3508 firstpass = config->firstpass;
3509 config->firstpass = 0;
3511 if (ast_tvzero(config->start_time))
3512 config->start_time = ast_tvnow();
3513 time_left_ms = config->timelimit;
3515 caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3516 callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3518 if (config->start_sound && firstpass) {
3519 if (caller_warning)
3520 bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3521 if (callee_warning)
3522 bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3525 /* Keep track of bridge */
3526 c0->_bridge = c1;
3527 c1->_bridge = c0;
3529 /* \todo XXX here should check that cid_num is not NULL */
3530 manager_event(EVENT_FLAG_CALL, "Link",
3531 "Channel1: %s\r\n"
3532 "Channel2: %s\r\n"
3533 "Uniqueid1: %s\r\n"
3534 "Uniqueid2: %s\r\n"
3535 "CallerID1: %s\r\n"
3536 "CallerID2: %s\r\n",
3537 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3539 o0nativeformats = c0->nativeformats;
3540 o1nativeformats = c1->nativeformats;
3542 if (config->timelimit) {
3543 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3544 if (caller_warning || callee_warning)
3545 nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
3548 for (/* ever */;;) {
3549 to = -1;
3550 if (config->timelimit) {
3551 struct timeval now;
3552 now = ast_tvnow();
3553 to = ast_tvdiff_ms(nexteventts, now);
3554 if (to < 0)
3555 to = 0;
3556 time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
3557 if (time_left_ms < to)
3558 to = time_left_ms;
3560 if (time_left_ms <= 0) {
3561 if (caller_warning && config->end_sound)
3562 bridge_playfile(c0, c1, config->end_sound, 0);
3563 if (callee_warning && config->end_sound)
3564 bridge_playfile(c1, c0, config->end_sound, 0);
3565 *fo = NULL;
3566 if (who)
3567 *rc = who;
3568 res = 0;
3569 break;
3572 if (!to) {
3573 if (time_left_ms >= 5000 && config->warning_sound && config->play_warning) {
3574 int t = (time_left_ms + 500) / 1000; /* round to nearest second */
3575 if (caller_warning)
3576 bridge_playfile(c0, c1, config->warning_sound, t);
3577 if (callee_warning)
3578 bridge_playfile(c1, c0, config->warning_sound, t);
3580 if (config->warning_freq) {
3581 nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
3582 } else
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;
3590 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3591 c1->_softhangup = 0;
3592 c0->_bridge = c1;
3593 c1->_bridge = c0;
3594 ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3595 continue;
3598 /* Stop if we're a zombie or need a soft hangup */
3599 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3600 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
3601 *fo = NULL;
3602 if (who)
3603 *rc = who;
3604 res = 0;
3605 ast_log(LOG_DEBUG, "Bridge stops because we're zombie or need a soft hangup: c0=%s, c1=%s, flags: %s,%s,%s,%s\n",
3606 c0->name, c1->name,
3607 ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
3608 ast_check_hangup(c0) ? "Yes" : "No",
3609 ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
3610 ast_check_hangup(c1) ? "Yes" : "No");
3611 break;
3614 if (c0->tech->bridge &&
3615 (config->timelimit == 0) &&
3616 (c0->tech->bridge == c1->tech->bridge) &&
3617 !nativefailed && !c0->monitor && !c1->monitor &&
3618 !c0->spies && !c1->spies && !ast_test_flag(&(config->features_callee),AST_FEATURE_REDIRECT) &&
3619 !ast_test_flag(&(config->features_caller),AST_FEATURE_REDIRECT) ) {
3620 /* Looks like they share a bridge method and nothing else is in the way */
3621 ast_set_flag(c0, AST_FLAG_NBRIDGE);
3622 ast_set_flag(c1, AST_FLAG_NBRIDGE);
3623 if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, to)) == AST_BRIDGE_COMPLETE) {
3624 /* \todo XXX here should check that cid_num is not NULL */
3625 manager_event(EVENT_FLAG_CALL, "Unlink",
3626 "Channel1: %s\r\n"
3627 "Channel2: %s\r\n"
3628 "Uniqueid1: %s\r\n"
3629 "Uniqueid2: %s\r\n"
3630 "CallerID1: %s\r\n"
3631 "CallerID2: %s\r\n",
3632 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3633 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
3635 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3636 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3638 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3639 continue;
3641 c0->_bridge = NULL;
3642 c1->_bridge = NULL;
3644 return res;
3645 } else {
3646 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3647 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3649 switch (res) {
3650 case AST_BRIDGE_RETRY:
3651 continue;
3652 default:
3653 if (option_verbose > 2)
3654 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s ended\n",
3655 c0->name, c1->name);
3656 /* fallthrough */
3657 case AST_BRIDGE_FAILED_NOWARN:
3658 nativefailed++;
3659 break;
3663 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
3664 (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
3665 !(c0->generator || c1->generator)) {
3666 if (ast_channel_make_compatible(c0, c1)) {
3667 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
3668 /* \todo XXX here should check that cid_num is not NULL */
3669 manager_event(EVENT_FLAG_CALL, "Unlink",
3670 "Channel1: %s\r\n"
3671 "Channel2: %s\r\n"
3672 "Uniqueid1: %s\r\n"
3673 "Uniqueid2: %s\r\n"
3674 "CallerID1: %s\r\n"
3675 "CallerID2: %s\r\n",
3676 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3677 return AST_BRIDGE_FAILED;
3679 o0nativeformats = c0->nativeformats;
3680 o1nativeformats = c1->nativeformats;
3682 res = ast_generic_bridge(c0, c1, config, fo, rc, nexteventts);
3683 if (res != AST_BRIDGE_RETRY)
3684 break;
3687 c0->_bridge = NULL;
3688 c1->_bridge = NULL;
3690 /* \todo XXX here should check that cid_num is not NULL */
3691 manager_event(EVENT_FLAG_CALL, "Unlink",
3692 "Channel1: %s\r\n"
3693 "Channel2: %s\r\n"
3694 "Uniqueid1: %s\r\n"
3695 "Uniqueid2: %s\r\n"
3696 "CallerID1: %s\r\n"
3697 "CallerID2: %s\r\n",
3698 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3699 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
3701 return res;
3704 /*! \brief Sets an option on a channel */
3705 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
3707 int res;
3709 if (chan->tech->setoption) {
3710 res = chan->tech->setoption(chan, option, data, datalen);
3711 if (res < 0)
3712 return res;
3713 } else {
3714 errno = ENOSYS;
3715 return -1;
3717 if (block) {
3718 /* XXX Implement blocking -- just wait for our option frame reply, discarding
3719 intermediate packets. XXX */
3720 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
3721 return -1;
3723 return 0;
3726 struct tonepair_def {
3727 int freq1;
3728 int freq2;
3729 int duration;
3730 int vol;
3733 struct tonepair_state {
3734 float freq1;
3735 float freq2;
3736 float vol;
3737 int duration;
3738 int pos;
3739 int origwfmt;
3740 struct ast_frame f;
3741 unsigned char offset[AST_FRIENDLY_OFFSET];
3742 short data[4000];
3745 static void tonepair_release(struct ast_channel *chan, void *params)
3747 struct tonepair_state *ts = params;
3749 if (chan)
3750 ast_set_write_format(chan, ts->origwfmt);
3751 free(ts);
3754 static void *tonepair_alloc(struct ast_channel *chan, void *params)
3756 struct tonepair_state *ts;
3757 struct tonepair_def *td = params;
3759 if (!(ts = ast_calloc(1, sizeof(*ts))))
3760 return NULL;
3761 ts->origwfmt = chan->writeformat;
3762 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
3763 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
3764 tonepair_release(NULL, ts);
3765 ts = NULL;
3766 } else {
3767 ts->freq1 = td->freq1;
3768 ts->freq2 = td->freq2;
3769 ts->duration = td->duration;
3770 ts->vol = td->vol;
3772 /* Let interrupts interrupt :) */
3773 ast_set_flag(chan, AST_FLAG_WRITE_INT);
3774 return ts;
3777 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
3779 struct tonepair_state *ts = data;
3780 int x;
3782 /* we need to prepare a frame with 16 * timelen samples as we're
3783 * generating SLIN audio
3785 len = samples * 2;
3787 if (len > sizeof(ts->data) / 2 - 1) {
3788 ast_log(LOG_WARNING, "Can't generate that much data!\n");
3789 return -1;
3791 memset(&ts->f, 0, sizeof(ts->f));
3792 for (x = 0; x < (len / 2); x++) {
3793 ts->data[x] = ts->vol * (
3794 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
3795 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
3798 ts->f.frametype = AST_FRAME_VOICE;
3799 ts->f.subclass = AST_FORMAT_SLINEAR;
3800 ts->f.datalen = len;
3801 ts->f.samples = samples;
3802 ts->f.offset = AST_FRIENDLY_OFFSET;
3803 ts->f.data = ts->data;
3804 ast_write(chan, &ts->f);
3805 ts->pos += x;
3806 if (ts->duration > 0) {
3807 if (ts->pos >= ts->duration * 8)
3808 return -1;
3810 return 0;
3813 static struct ast_generator tonepair = {
3814 alloc: tonepair_alloc,
3815 release: tonepair_release,
3816 generate: tonepair_generator,
3819 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
3821 struct tonepair_def d = { 0, };
3823 d.freq1 = freq1;
3824 d.freq2 = freq2;
3825 d.duration = duration;
3826 d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
3827 if (ast_activate_generator(chan, &tonepair, &d))
3828 return -1;
3829 return 0;
3832 void ast_tonepair_stop(struct ast_channel *chan)
3834 ast_deactivate_generator(chan);
3837 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
3839 int res;
3841 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
3842 return res;
3844 /* Give us some wiggle room */
3845 while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
3846 struct ast_frame *f = ast_read(chan);
3847 if (f)
3848 ast_frfree(f);
3849 else
3850 return -1;
3852 return 0;
3855 ast_group_t ast_get_group(char *s)
3857 char *piece;
3858 char *c;
3859 int start=0, finish=0, x;
3860 ast_group_t group = 0;
3862 c = ast_strdupa(s);
3864 while ((piece = strsep(&c, ","))) {
3865 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
3866 /* Range */
3867 } else if (sscanf(piece, "%d", &start)) {
3868 /* Just one */
3869 finish = start;
3870 } else {
3871 ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
3872 continue;
3874 for (x = start; x <= finish; x++) {
3875 if ((x > 63) || (x < 0)) {
3876 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
3877 } else
3878 group |= ((ast_group_t) 1 << x);
3881 return group;
3884 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *) = NULL;
3885 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
3886 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
3888 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *),
3889 void (*stop_ptr)(struct ast_channel *),
3890 void (*cleanup_ptr)(struct ast_channel *))
3892 ast_moh_start_ptr = start_ptr;
3893 ast_moh_stop_ptr = stop_ptr;
3894 ast_moh_cleanup_ptr = cleanup_ptr;
3897 void ast_uninstall_music_functions(void)
3899 ast_moh_start_ptr = NULL;
3900 ast_moh_stop_ptr = NULL;
3901 ast_moh_cleanup_ptr = NULL;
3904 /*! \brief Turn on music on hold on a given channel */
3905 int ast_moh_start(struct ast_channel *chan, const char *mclass)
3907 if (ast_moh_start_ptr)
3908 return ast_moh_start_ptr(chan, mclass);
3910 if (option_verbose > 2)
3911 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : "default");
3913 return 0;
3916 /*! \brief Turn off music on hold on a given channel */
3917 void ast_moh_stop(struct ast_channel *chan)
3919 if (ast_moh_stop_ptr)
3920 ast_moh_stop_ptr(chan);
3923 void ast_moh_cleanup(struct ast_channel *chan)
3925 if (ast_moh_cleanup_ptr)
3926 ast_moh_cleanup_ptr(chan);
3929 void ast_channels_init(void)
3931 ast_cli_register(&cli_show_channeltypes);
3932 ast_cli_register(&cli_show_channeltype);
3935 /*! \brief Print call group and pickup group ---*/
3936 char *ast_print_group(char *buf, int buflen, ast_group_t group)
3938 unsigned int i;
3939 int first=1;
3940 char num[3];
3942 buf[0] = '\0';
3944 if (!group) /* Return empty string if no group */
3945 return buf;
3947 for (i = 0; i <= 63; i++) { /* Max group is 63 */
3948 if (group & ((ast_group_t) 1 << i)) {
3949 if (!first) {
3950 strncat(buf, ", ", buflen);
3951 } else {
3952 first=0;
3954 snprintf(num, sizeof(num), "%u", i);
3955 strncat(buf, num, buflen);
3958 return buf;
3961 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
3963 struct ast_variable *cur;
3965 for (cur = vars; cur; cur = cur->next)
3966 pbx_builtin_setvar_helper(chan, cur->name, cur->value);
3969 static void copy_data_from_queue(struct ast_channel_spy_queue *queue, short *buf, unsigned int samples)
3971 struct ast_frame *f;
3972 int tocopy;
3973 int bytestocopy;
3975 while (samples) {
3976 f = queue->head;
3978 if (!f) {
3979 ast_log(LOG_ERROR, "Ran out of frames before buffer filled!\n");
3980 break;
3983 tocopy = (f->samples > samples) ? samples : f->samples;
3984 bytestocopy = ast_codec_get_len(queue->format, tocopy);
3985 memcpy(buf, f->data, bytestocopy);
3986 samples -= tocopy;
3987 buf += tocopy;
3988 f->samples -= tocopy;
3989 f->data += bytestocopy;
3990 f->datalen -= bytestocopy;
3991 f->offset += bytestocopy;
3992 queue->samples -= tocopy;
3993 if (!f->samples) {
3994 queue->head = f->next;
3995 ast_frfree(f);
4000 struct ast_frame *ast_channel_spy_read_frame(struct ast_channel_spy *spy, unsigned int samples)
4002 struct ast_frame *result;
4003 /* buffers are allocated to hold SLINEAR, which is the largest format */
4004 short read_buf[samples];
4005 short write_buf[samples];
4006 struct ast_frame *read_frame;
4007 struct ast_frame *write_frame;
4008 int need_dup;
4009 struct ast_frame stack_read_frame = { .frametype = AST_FRAME_VOICE,
4010 .subclass = spy->read_queue.format,
4011 .data = read_buf,
4012 .samples = samples,
4013 .datalen = ast_codec_get_len(spy->read_queue.format, samples),
4015 struct ast_frame stack_write_frame = { .frametype = AST_FRAME_VOICE,
4016 .subclass = spy->write_queue.format,
4017 .data = write_buf,
4018 .samples = samples,
4019 .datalen = ast_codec_get_len(spy->write_queue.format, samples),
4022 /* if a flush has been requested, dump everything in whichever queue is larger */
4023 if (ast_test_flag(spy, CHANSPY_TRIGGER_FLUSH)) {
4024 if (spy->read_queue.samples > spy->write_queue.samples) {
4025 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST)) {
4026 for (result = spy->read_queue.head; result; result = result->next)
4027 ast_frame_adjust_volume(result, spy->read_vol_adjustment);
4029 result = spy->read_queue.head;
4030 spy->read_queue.head = NULL;
4031 spy->read_queue.samples = 0;
4032 } else {
4033 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST)) {
4034 for (result = spy->write_queue.head; result; result = result->next)
4035 ast_frame_adjust_volume(result, spy->write_vol_adjustment);
4037 result = spy->write_queue.head;
4038 spy->write_queue.head = NULL;
4039 spy->write_queue.samples = 0;
4041 ast_clear_flag(spy, CHANSPY_TRIGGER_FLUSH);
4042 return result;
4045 if ((spy->read_queue.samples < samples) || (spy->write_queue.samples < samples))
4046 return NULL;
4048 /* short-circuit if both head frames have exactly what we want */
4049 if ((spy->read_queue.head->samples == samples) &&
4050 (spy->write_queue.head->samples == samples)) {
4051 read_frame = spy->read_queue.head;
4052 spy->read_queue.head = read_frame->next;
4053 read_frame->next = NULL;
4055 write_frame = spy->write_queue.head;
4056 spy->write_queue.head = write_frame->next;
4057 write_frame->next = NULL;
4059 spy->read_queue.samples -= samples;
4060 spy->write_queue.samples -= samples;
4062 need_dup = 0;
4063 } else {
4064 copy_data_from_queue(&spy->read_queue, read_buf, samples);
4065 copy_data_from_queue(&spy->write_queue, write_buf, samples);
4067 read_frame = &stack_read_frame;
4068 write_frame = &stack_write_frame;
4069 need_dup = 1;
4072 if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST))
4073 ast_frame_adjust_volume(read_frame, spy->read_vol_adjustment);
4075 if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST))
4076 ast_frame_adjust_volume(write_frame, spy->write_vol_adjustment);
4078 if (ast_test_flag(spy, CHANSPY_MIXAUDIO)) {
4079 ast_frame_slinear_sum(read_frame, write_frame);
4081 if (need_dup)
4082 result = ast_frdup(read_frame);
4083 else {
4084 result = read_frame;
4085 ast_frfree(write_frame);
4087 } else {
4088 if (need_dup) {
4089 result = ast_frdup(read_frame);
4090 result->next = ast_frdup(write_frame);
4091 } else {
4092 result = read_frame;
4093 result->next = write_frame;
4097 return result;
4100 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
4102 /* just store the data pointer in the channel structure */
4103 return data;
4106 static void silence_generator_release(struct ast_channel *chan, void *data)
4108 /* nothing to do */
4111 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
4113 short buf[samples];
4114 struct ast_frame frame = {
4115 .frametype = AST_FRAME_VOICE,
4116 .subclass = AST_FORMAT_SLINEAR,
4117 .data = buf,
4118 .samples = samples,
4119 .datalen = sizeof(buf),
4121 memset(buf, 0, sizeof(buf));
4122 if (ast_write(chan, &frame))
4123 return -1;
4124 return 0;
4127 static struct ast_generator silence_generator = {
4128 .alloc = silence_generator_alloc,
4129 .release = silence_generator_release,
4130 .generate = silence_generator_generate,
4133 struct ast_silence_generator {
4134 int old_write_format;
4137 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
4139 struct ast_silence_generator *state;
4141 if (!(state = ast_calloc(1, sizeof(*state)))) {
4142 return NULL;
4145 state->old_write_format = chan->writeformat;
4147 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
4148 ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
4149 free(state);
4150 return NULL;
4153 ast_activate_generator(chan, &silence_generator, state);
4155 if (option_debug)
4156 ast_log(LOG_DEBUG, "Started silence generator on '%s'\n", chan->name);
4158 return state;
4161 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
4163 if (!state)
4164 return;
4166 ast_deactivate_generator(chan);
4168 if (option_debug)
4169 ast_log(LOG_DEBUG, "Stopped silence generator on '%s'\n", chan->name);
4171 if (ast_set_write_format(chan, state->old_write_format) < 0)
4172 ast_log(LOG_ERROR, "Could not return write format to its original state\n");
4174 free(state);
4178 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
4179 const char *channelreloadreason2txt(enum channelreloadreason reason)
4181 switch (reason) {
4182 case CHANNEL_MODULE_LOAD:
4183 return "LOAD (Channel module load)";
4185 case CHANNEL_MODULE_RELOAD:
4186 return "RELOAD (Channel module reload)";
4188 case CHANNEL_CLI_RELOAD:
4189 return "CLIRELOAD (Channel module reload by CLI command)";
4191 default:
4192 return "MANAGERRELOAD (Channel module reload by manager)";
4196 #ifdef DEBUG_CHANNEL_LOCKS
4198 /*! \brief Unlock AST channel (and print debugging output)
4199 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
4201 int ast_channel_unlock(struct ast_channel *chan)
4203 int res = 0;
4204 if (option_debug > 2)
4205 ast_log(LOG_DEBUG, "::::==== Unlocking AST channel %s\n", chan->name);
4207 if (!chan) {
4208 ast_log(LOG_DEBUG, "::::==== Unlocking non-existing channel \n");
4209 return 0;
4212 res = ast_mutex_unlock(&chan->lock);
4214 if (option_debug > 2) {
4215 /* Try to find counter if possible on your platform
4216 I've only found out how to do this on Linux
4217 DEBUG_THREADS changes the lock structure
4219 #ifdef __linux__
4220 int count = 0;
4221 #ifdef DEBUG_THREADS
4222 if ((count = chan->lock.mutex.__m_count))
4223 #else
4224 if ((count = chan->lock.__m_count))
4225 #endif
4226 ast_log(LOG_DEBUG, ":::=== Still have %d locks (recursive)\n", count);
4227 #endif
4228 if (!res)
4229 ast_log(LOG_DEBUG, "::::==== Channel %s was unlocked\n", chan->name);
4230 if (res == EINVAL) {
4231 ast_log(LOG_DEBUG, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan->name);
4234 if (res == EPERM) {
4235 /* We had no lock, so okay any way*/
4236 if (option_debug > 3)
4237 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked at all \n", chan->name);
4238 res = 0;
4240 return res;
4243 /*! \brief Lock AST channel (and print debugging output)
4244 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4245 int ast_channel_lock(struct ast_channel *chan)
4247 int res;
4249 if (option_debug > 3)
4250 ast_log(LOG_DEBUG, "====:::: Locking AST channel %s\n", chan->name);
4252 res = ast_mutex_lock(&chan->lock);
4254 if (option_debug > 3) {
4255 #ifdef __linux__
4256 int count = 0;
4257 #ifdef DEBUG_THREADS
4258 if ((count = chan->lock.mutex.__m_count))
4259 #else
4260 if ((count = chan->lock.__m_count))
4261 #endif
4262 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4263 #endif
4264 if (!res)
4265 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4266 if (res == EDEADLK) {
4267 /* We had no lock, so okey any way */
4268 if (option_debug > 3)
4269 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan->name);
4271 if (res == EINVAL) {
4272 if (option_debug > 3)
4273 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4276 return res;
4279 /*! \brief Lock AST channel (and print debugging output)
4280 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4281 int ast_channel_trylock(struct ast_channel *chan)
4283 int res;
4285 if (option_debug > 2)
4286 ast_log(LOG_DEBUG, "====:::: Trying to lock AST channel %s\n", chan->name);
4288 res = ast_mutex_trylock(&chan->lock);
4290 if (option_debug > 2) {
4291 #ifdef __linux__
4292 int count = 0;
4293 #ifdef DEBUG_THREADS
4294 if ((count = chan->lock.mutex.__m_count))
4295 #else
4296 if ((count = chan->lock.__m_count))
4297 #endif
4298 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4299 #endif
4300 if (!res)
4301 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4302 if (res == EBUSY) {
4303 /* We failed to lock */
4304 if (option_debug > 2)
4305 ast_log(LOG_DEBUG, "::::==== Channel %s failed to lock. Not waiting around...\n", chan->name);
4307 if (res == EDEADLK) {
4308 /* We had no lock, so okey any way*/
4309 if (option_debug > 2)
4310 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan->name);
4312 if (res == EINVAL && option_debug > 2)
4313 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4315 return res;
4318 #endif
4321 * Wrappers for various ast_say_*() functions that call the full version
4322 * of the same functions.
4323 * The proper place would be say.c, but that file is optional and one
4324 * must be able to build asterisk even without it (using a loadable 'say'
4325 * implementation that only supplies the 'full' version of the functions.
4328 int ast_say_number(struct ast_channel *chan, int num,
4329 const char *ints, const char *language, const char *options)
4331 return ast_say_number_full(chan, num, ints, language, options, -1, -1);
4334 int ast_say_enumeration(struct ast_channel *chan, int num,
4335 const char *ints, const char *language, const char *options)
4337 return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
4340 int ast_say_digits(struct ast_channel *chan, int num,
4341 const char *ints, const char *lang)
4343 return ast_say_digits_full(chan, num, ints, lang, -1, -1);
4346 int ast_say_digit_str(struct ast_channel *chan, const char *str,
4347 const char *ints, const char *lang)
4349 return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
4352 int ast_say_character_str(struct ast_channel *chan, const char *str,
4353 const char *ints, const char *lang)
4355 return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
4358 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
4359 const char *ints, const char *lang)
4361 return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
4364 int ast_say_digits_full(struct ast_channel *chan, int num,
4365 const char *ints, const char *lang, int audiofd, int ctrlfd)
4367 char buf[256];
4369 snprintf(buf, sizeof(buf), "%d", num);
4370 return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);
4373 /* end of file */