initialize send_message to make chan_vpb build
[asterisk-bristuff.git] / main / channel.c
blob8c65e383b1976cabb733d61afb5d34fb4bcb97f8
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 <stdarg.h>
33 #include <string.h>
34 #include <sys/time.h>
35 #include <signal.h>
36 #include <errno.h>
37 #include <unistd.h>
38 #include <math.h>
40 #if defined(HAVE_ZAPTEL) || defined (HAVE_DAHDI)
41 #include <sys/ioctl.h>
42 #include "asterisk/dahdi_compat.h"
43 #endif
45 #include "asterisk/pbx.h"
46 #include "asterisk/frame.h"
47 #include "asterisk/sched.h"
48 #include "asterisk/options.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/audiohook.h"
51 #include "asterisk/musiconhold.h"
52 #include "asterisk/logger.h"
53 #include "asterisk/say.h"
54 #include "asterisk/file.h"
55 #include "asterisk/cli.h"
56 #include "asterisk/translate.h"
57 #include "asterisk/manager.h"
58 #include "asterisk/chanvars.h"
59 #include "asterisk/linkedlists.h"
60 #include "asterisk/indications.h"
61 #include "asterisk/monitor.h"
62 #include "asterisk/causes.h"
63 #include "asterisk/callerid.h"
64 #include "asterisk/utils.h"
65 #include "asterisk/lock.h"
66 #include "asterisk/app.h"
67 #include "asterisk/transcap.h"
68 #include "asterisk/devicestate.h"
69 #include "asterisk/sha1.h"
70 #include "asterisk/threadstorage.h"
71 #include "asterisk/slinfactory.h"
73 /* uncomment if you have problems with 'monitoring' synchronized files */
74 #if 0
75 #define MONITOR_CONSTANT_DELAY
76 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
77 #endif
79 /*! Prevent new channel allocation if shutting down. */
80 static int shutting_down;
82 static int uniqueint;
84 unsigned long global_fin, global_fout;
86 AST_THREADSTORAGE(state2str_threadbuf, state2str_threadbuf_init);
87 #define STATE2STR_BUFSIZE 32
89 /*! Default amount of time to use when emulating a digit as a begin and end
90 * 100ms */
91 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
93 /*! Minimum allowed digit length - 80ms */
94 #define AST_MIN_DTMF_DURATION 80
96 /*! Minimum amount of time between the end of the last digit and the beginning
97 * of a new one - 45ms */
98 #define AST_MIN_DTMF_GAP 45
100 struct chanlist {
101 const struct ast_channel_tech *tech;
102 AST_LIST_ENTRY(chanlist) list;
105 /*! the list of registered channel types */
106 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
108 /*! the list of channels we have. Note that the lock for this list is used for
109 both the channels list and the backends list. */
110 static AST_LIST_HEAD_STATIC(channels, ast_channel);
112 /*! map AST_CAUSE's to readable string representations */
113 const struct ast_cause {
114 int cause;
115 const char *name;
116 const char *desc;
117 } causes[] = {
118 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
119 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
120 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
121 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
122 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
123 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
124 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
125 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
126 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
127 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
128 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
129 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
130 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
131 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
132 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
133 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
134 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
135 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
136 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
137 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
138 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
139 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
140 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
141 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
142 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
143 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
144 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
145 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
146 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
147 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
148 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
149 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
150 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
151 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
152 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
153 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
154 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
155 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
156 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
157 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
158 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
159 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
160 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
161 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
164 struct ast_variable *ast_channeltype_list(void)
166 struct chanlist *cl;
167 struct ast_variable *var=NULL, *prev = NULL;
168 AST_LIST_TRAVERSE(&backends, cl, list) {
169 if (prev) {
170 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description)))
171 prev = prev->next;
172 } else {
173 var = ast_variable_new(cl->tech->type, cl->tech->description);
174 prev = var;
177 return var;
180 static int show_channeltypes(int fd, int argc, char *argv[])
182 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
183 struct chanlist *cl;
184 int count_chan = 0;
186 ast_cli(fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
187 ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
188 if (AST_LIST_LOCK(&channels)) {
189 ast_log(LOG_WARNING, "Unable to lock channel list\n");
190 return -1;
192 AST_LIST_TRAVERSE(&backends, cl, list) {
193 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description,
194 (cl->tech->devicestate) ? "yes" : "no",
195 (cl->tech->indicate) ? "yes" : "no",
196 (cl->tech->transfer) ? "yes" : "no");
197 count_chan++;
199 AST_LIST_UNLOCK(&channels);
200 ast_cli(fd, "----------\n%d channel drivers registered.\n", count_chan);
201 return RESULT_SUCCESS;
203 #undef FORMAT
207 static int show_channeltype_deprecated(int fd, int argc, char *argv[])
209 struct chanlist *cl = NULL;
211 if (argc != 3)
212 return RESULT_SHOWUSAGE;
214 if (AST_LIST_LOCK(&channels)) {
215 ast_log(LOG_WARNING, "Unable to lock channel list\n");
216 return RESULT_FAILURE;
219 AST_LIST_TRAVERSE(&backends, cl, list) {
220 if (!strncasecmp(cl->tech->type, argv[2], strlen(cl->tech->type))) {
221 break;
226 if (!cl) {
227 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[2]);
228 AST_LIST_UNLOCK(&channels);
229 return RESULT_FAILURE;
232 ast_cli(fd,
233 "-- Info about channel driver: %s --\n"
234 " Device State: %s\n"
235 " Indication: %s\n"
236 " Transfer : %s\n"
237 " Capabilities: %d\n"
238 " Digit Begin: %s\n"
239 " Digit End: %s\n"
240 " Send HTML : %s\n"
241 " Image Support: %s\n"
242 " Text Support: %s\n",
243 cl->tech->type,
244 (cl->tech->devicestate) ? "yes" : "no",
245 (cl->tech->indicate) ? "yes" : "no",
246 (cl->tech->transfer) ? "yes" : "no",
247 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
248 (cl->tech->send_digit_begin) ? "yes" : "no",
249 (cl->tech->send_digit_end) ? "yes" : "no",
250 (cl->tech->send_html) ? "yes" : "no",
251 (cl->tech->send_image) ? "yes" : "no",
252 (cl->tech->send_text) ? "yes" : "no"
256 AST_LIST_UNLOCK(&channels);
257 return RESULT_SUCCESS;
260 static int show_channeltype(int fd, int argc, char *argv[])
262 struct chanlist *cl = NULL;
264 if (argc != 4)
265 return RESULT_SHOWUSAGE;
267 if (AST_LIST_LOCK(&channels)) {
268 ast_log(LOG_WARNING, "Unable to lock channel list\n");
269 return RESULT_FAILURE;
272 AST_LIST_TRAVERSE(&backends, cl, list) {
273 if (!strncasecmp(cl->tech->type, argv[3], strlen(cl->tech->type))) {
274 break;
279 if (!cl) {
280 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[3]);
281 AST_LIST_UNLOCK(&channels);
282 return RESULT_FAILURE;
285 ast_cli(fd,
286 "-- Info about channel driver: %s --\n"
287 " Device State: %s\n"
288 " Indication: %s\n"
289 " Transfer : %s\n"
290 " Capabilities: %d\n"
291 " Digit Begin: %s\n"
292 " Digit End: %s\n"
293 " Send HTML : %s\n"
294 " Image Support: %s\n"
295 " Text Support: %s\n",
296 cl->tech->type,
297 (cl->tech->devicestate) ? "yes" : "no",
298 (cl->tech->indicate) ? "yes" : "no",
299 (cl->tech->transfer) ? "yes" : "no",
300 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
301 (cl->tech->send_digit_begin) ? "yes" : "no",
302 (cl->tech->send_digit_end) ? "yes" : "no",
303 (cl->tech->send_html) ? "yes" : "no",
304 (cl->tech->send_image) ? "yes" : "no",
305 (cl->tech->send_text) ? "yes" : "no"
309 AST_LIST_UNLOCK(&channels);
310 return RESULT_SUCCESS;
313 static char *complete_channeltypes_deprecated(const char *line, const char *word, int pos, int state)
315 struct chanlist *cl;
316 int which = 0;
317 int wordlen;
318 char *ret = NULL;
320 if (pos != 2)
321 return NULL;
323 wordlen = strlen(word);
325 AST_LIST_TRAVERSE(&backends, cl, list) {
326 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
327 ret = strdup(cl->tech->type);
328 break;
332 return ret;
335 static char *complete_channeltypes(const char *line, const char *word, int pos, int state)
337 struct chanlist *cl;
338 int which = 0;
339 int wordlen;
340 char *ret = NULL;
342 if (pos != 3)
343 return NULL;
345 wordlen = strlen(word);
347 AST_LIST_TRAVERSE(&backends, cl, list) {
348 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
349 ret = strdup(cl->tech->type);
350 break;
354 return ret;
357 static char show_channeltypes_usage[] =
358 "Usage: core show channeltypes\n"
359 " Lists available channel types registered in your Asterisk server.\n";
361 static char show_channeltype_usage[] =
362 "Usage: core show channeltype <name>\n"
363 " Show details about the specified channel type, <name>.\n";
365 static struct ast_cli_entry cli_show_channeltypes_deprecated = {
366 { "show", "channeltypes", NULL },
367 show_channeltypes, NULL,
368 NULL };
370 static struct ast_cli_entry cli_show_channeltype_deprecated = {
371 { "show", "channeltype", NULL },
372 show_channeltype_deprecated, NULL,
373 NULL, complete_channeltypes_deprecated };
375 static struct ast_cli_entry cli_channel[] = {
376 { { "core", "show", "channeltypes", NULL },
377 show_channeltypes, "List available channel types",
378 show_channeltypes_usage, NULL, &cli_show_channeltypes_deprecated },
380 { { "core", "show", "channeltype", NULL },
381 show_channeltype, "Give more details on that channel type",
382 show_channeltype_usage, complete_channeltypes, &cli_show_channeltype_deprecated },
385 /*! \brief Checks to see if a channel is needing hang up */
386 int ast_check_hangup(struct ast_channel *chan)
388 if (chan->_softhangup) /* yes if soft hangup flag set */
389 return 1;
390 if (!chan->tech_pvt) /* yes if no technology private data */
391 return 1;
392 if (!chan->whentohangup) /* no if no hangup scheduled */
393 return 0;
394 if (chan->whentohangup > time(NULL)) /* no if hangup time has not come yet. */
395 return 0;
396 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
397 return 1;
400 static int ast_check_hangup_locked(struct ast_channel *chan)
402 int res;
403 ast_channel_lock(chan);
404 res = ast_check_hangup(chan);
405 ast_channel_unlock(chan);
406 return res;
409 /*! \brief printf the string into a correctly sized mallocd buffer, and return the buffer */
410 char *ast_safe_string_alloc(const char *fmt, ...)
412 char *b2, buf[1];
413 int len;
414 va_list args;
416 va_start(args, fmt);
417 len = vsnprintf(buf, 1, fmt, args);
418 va_end(args);
420 if (!(b2 = ast_malloc(len + 1)))
421 return NULL;
423 va_start(args, fmt);
424 vsnprintf(b2, len + 1, fmt, args);
425 va_end(args);
427 return b2;
430 /*! \brief Initiate system shutdown */
431 void ast_begin_shutdown(int hangup)
433 struct ast_channel *c;
434 shutting_down = 1;
435 if (hangup) {
436 AST_LIST_LOCK(&channels);
437 AST_LIST_TRAVERSE(&channels, c, chan_list)
438 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
439 AST_LIST_UNLOCK(&channels);
443 /*! \brief returns number of active/allocated channels */
444 int ast_active_channels(void)
446 struct ast_channel *c;
447 int cnt = 0;
448 AST_LIST_LOCK(&channels);
449 AST_LIST_TRAVERSE(&channels, c, chan_list)
450 cnt++;
451 AST_LIST_UNLOCK(&channels);
452 return cnt;
455 /*! \brief Cancel a shutdown in progress */
456 void ast_cancel_shutdown(void)
458 shutting_down = 0;
461 /*! \brief Returns non-zero if Asterisk is being shut down */
462 int ast_shutting_down(void)
464 return shutting_down;
467 /*! \brief Set when to hangup channel */
468 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
470 chan->whentohangup = offset ? time(NULL) + offset : 0;
471 ast_queue_frame(chan, &ast_null_frame);
472 return;
475 /*! \brief Compare a offset with when to hangup channel */
476 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
478 time_t whentohangup;
480 if (chan->whentohangup == 0) {
481 return (offset == 0) ? 0 : -1;
482 } else {
483 if (offset == 0) /* XXX why is this special ? */
484 return (1);
485 else {
486 whentohangup = offset + time (NULL);
487 if (chan->whentohangup < whentohangup)
488 return (1);
489 else if (chan->whentohangup == whentohangup)
490 return (0);
491 else
492 return (-1);
497 /*! \brief Register a new telephony channel in Asterisk */
498 int ast_channel_register(const struct ast_channel_tech *tech)
500 struct chanlist *chan;
502 AST_LIST_LOCK(&channels);
504 AST_LIST_TRAVERSE(&backends, chan, list) {
505 if (!strcasecmp(tech->type, chan->tech->type)) {
506 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
507 AST_LIST_UNLOCK(&channels);
508 return -1;
512 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
513 AST_LIST_UNLOCK(&channels);
514 return -1;
516 chan->tech = tech;
517 AST_LIST_INSERT_HEAD(&backends, chan, list);
519 if (option_debug)
520 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
522 if (option_verbose > 1)
523 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
524 chan->tech->description);
526 AST_LIST_UNLOCK(&channels);
527 return 0;
530 void ast_channel_unregister(const struct ast_channel_tech *tech)
532 struct chanlist *chan;
534 if (option_debug)
535 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
537 AST_LIST_LOCK(&channels);
539 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
540 if (chan->tech == tech) {
541 AST_LIST_REMOVE_CURRENT(&backends, list);
542 free(chan);
543 if (option_verbose > 1)
544 ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
545 break;
548 AST_LIST_TRAVERSE_SAFE_END
550 AST_LIST_UNLOCK(&channels);
553 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
555 struct chanlist *chanls;
556 const struct ast_channel_tech *ret = NULL;
558 if (AST_LIST_LOCK(&channels)) {
559 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
560 return NULL;
563 AST_LIST_TRAVERSE(&backends, chanls, list) {
564 if (!strcasecmp(name, chanls->tech->type)) {
565 ret = chanls->tech;
566 break;
570 AST_LIST_UNLOCK(&channels);
572 return ret;
575 /*! \brief Gives the string form of a given hangup cause */
576 const char *ast_cause2str(int cause)
578 int x;
580 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
581 if (causes[x].cause == cause)
582 return causes[x].desc;
585 return "Unknown";
588 /*! \brief Convert a symbolic hangup cause to number */
589 int ast_str2cause(const char *name)
591 int x;
593 for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
594 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
595 return causes[x].cause;
597 return -1;
600 /*! \brief Gives the string form of a given channel state */
601 char *ast_state2str(enum ast_channel_state state)
603 char *buf;
605 switch(state) {
606 case AST_STATE_DOWN:
607 return "Down";
608 case AST_STATE_RESERVED:
609 return "Rsrvd";
610 case AST_STATE_OFFHOOK:
611 return "OffHook";
612 case AST_STATE_DIALING:
613 return "Dialing";
614 case AST_STATE_RING:
615 return "Ring";
616 case AST_STATE_RINGING:
617 return "Ringing";
618 case AST_STATE_UP:
619 return "Up";
620 case AST_STATE_BUSY:
621 return "Busy";
622 case AST_STATE_DIALING_OFFHOOK:
623 return "Dialing Offhook";
624 case AST_STATE_PRERING:
625 return "Pre-ring";
626 default:
627 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
628 return "Unknown";
629 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
630 return buf;
634 /*! \brief Gives the string form of a given transfer capability */
635 char *ast_transfercapability2str(int transfercapability)
637 switch(transfercapability) {
638 case AST_TRANS_CAP_SPEECH:
639 return "SPEECH";
640 case AST_TRANS_CAP_DIGITAL:
641 return "DIGITAL";
642 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
643 return "RESTRICTED_DIGITAL";
644 case AST_TRANS_CAP_3_1K_AUDIO:
645 return "3K1AUDIO";
646 case AST_TRANS_CAP_DIGITAL_W_TONES:
647 return "DIGITAL_W_TONES";
648 case AST_TRANS_CAP_VIDEO:
649 return "VIDEO";
650 default:
651 return "UNKNOWN";
655 /*! \brief Pick the best audio codec */
656 int ast_best_codec(int fmts)
658 /* This just our opinion, expressed in code. We are asked to choose
659 the best codec to use, given no information */
660 int x;
661 static int prefs[] =
663 /*! Okay, ulaw is used by all telephony equipment, so start with it */
664 AST_FORMAT_ULAW,
665 /*! Unless of course, you're a silly European, so then prefer ALAW */
666 AST_FORMAT_ALAW,
667 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
668 AST_FORMAT_G722,
669 /*! Okay, well, signed linear is easy to translate into other stuff */
670 AST_FORMAT_SLINEAR,
671 /*! G.726 is standard ADPCM, in RFC3551 packing order */
672 AST_FORMAT_G726,
673 /*! G.726 is standard ADPCM, in AAL2 packing order */
674 AST_FORMAT_G726_AAL2,
675 /*! ADPCM has great sound quality and is still pretty easy to translate */
676 AST_FORMAT_ADPCM,
677 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
678 translate and sounds pretty good */
679 AST_FORMAT_GSM,
680 /*! iLBC is not too bad */
681 AST_FORMAT_ILBC,
682 /*! Speex is free, but computationally more expensive than GSM */
683 AST_FORMAT_SPEEX,
684 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
685 to use it */
686 AST_FORMAT_LPC10,
687 /*! G.729a is faster than 723 and slightly less expensive */
688 AST_FORMAT_G729A,
689 /*! Down to G.723.1 which is proprietary but at least designed for voice */
690 AST_FORMAT_G723_1,
693 /* Strip out video */
694 fmts &= AST_FORMAT_AUDIO_MASK;
696 /* Find the first preferred codec in the format given */
697 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
698 if (fmts & prefs[x])
699 return prefs[x];
700 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
701 return 0;
704 static const struct ast_channel_tech null_tech = {
705 .type = "NULL",
706 .description = "Null channel (should not see this)",
709 /*! \brief Create a new channel structure */
710 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num, const char *cid_name, const char *acctcode, const char *exten, const char *context, const int amaflag, const char *name_fmt, ...)
712 struct ast_channel *tmp;
713 int x;
714 int flags;
715 struct varshead *headp;
716 va_list ap1, ap2;
718 /* If shutting down, don't allocate any new channels */
719 if (shutting_down) {
720 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
721 return NULL;
724 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
725 return NULL;
727 if (!(tmp->sched = sched_context_create())) {
728 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
729 free(tmp);
730 return NULL;
733 if ((ast_string_field_init(tmp, 128))) {
734 sched_context_destroy(tmp->sched);
735 free(tmp);
736 return NULL;
739 /* Don't bother initializing the last two FD here, because they
740 will *always* be set just a few lines down (AST_TIMING_FD,
741 AST_ALERT_FD). */
742 for (x = 0; x < AST_MAX_FDS - 2; x++)
743 tmp->fds[x] = -1;
745 #ifdef HAVE_DAHDI
747 #ifdef HAVE_ZAPTEL
748 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
749 #else
750 tmp->timingfd = open("/dev/dahdi/timer", O_RDWR);
751 #endif
753 if (tmp->timingfd > -1) {
754 /* Check if timing interface supports new
755 ping/pong scheme */
756 flags = 1;
757 if (!ioctl(tmp->timingfd, DAHDI_TIMERPONG, &flags))
758 needqueue = 0;
760 #else
761 tmp->timingfd = -1;
762 #endif
764 if (needqueue) {
765 if (pipe(tmp->alertpipe)) {
766 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
767 alertpipe_failed:
768 #ifdef HAVE_DAHDI
769 if (tmp->timingfd > -1)
770 close(tmp->timingfd);
771 #endif
772 sched_context_destroy(tmp->sched);
773 ast_string_field_free_memory(tmp);
774 free(tmp);
775 return NULL;
776 } else {
777 flags = fcntl(tmp->alertpipe[0], F_GETFL);
778 if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
779 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
780 close(tmp->alertpipe[0]);
781 close(tmp->alertpipe[1]);
782 goto alertpipe_failed;
784 flags = fcntl(tmp->alertpipe[1], F_GETFL);
785 if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
786 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
787 close(tmp->alertpipe[0]);
788 close(tmp->alertpipe[1]);
789 goto alertpipe_failed;
792 } else /* Make sure we've got it done right if they don't */
793 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
795 /* Always watch the alertpipe */
796 tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
797 /* And timing pipe */
798 tmp->fds[AST_TIMING_FD] = tmp->timingfd;
799 ast_string_field_set(tmp, name, "**Unknown**");
801 /* Initial state */
802 tmp->_state = state;
804 tmp->streamid = -1;
806 tmp->fin = global_fin;
807 tmp->fout = global_fout;
809 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
810 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
811 ast_atomic_fetchadd_int(&uniqueint, 1));
812 } else {
813 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
814 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
817 tmp->cid.cid_name = ast_strdup(cid_name);
818 tmp->cid.cid_num = ast_strdup(cid_num);
820 if (!ast_strlen_zero(name_fmt)) {
821 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
822 * And they all use slightly different formats for their name string.
823 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
824 * This means, that the stringfields must have a routine that takes the va_lists directly, and
825 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
826 * This new function was written so this can be accomplished.
828 va_start(ap1, name_fmt);
829 va_start(ap2, name_fmt);
830 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
831 va_end(ap1);
832 va_end(ap2);
835 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
837 /* These 4 variables need to be set up for the cdr_init() to work right */
838 if (amaflag)
839 tmp->amaflags = amaflag;
840 else
841 tmp->amaflags = ast_default_amaflags;
843 if (!ast_strlen_zero(acctcode))
844 ast_string_field_set(tmp, accountcode, acctcode);
845 else
846 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
848 if (!ast_strlen_zero(context))
849 ast_copy_string(tmp->context, context, sizeof(tmp->context));
850 else
851 strcpy(tmp->context, "default");
853 if (!ast_strlen_zero(exten))
854 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
855 else
856 strcpy(tmp->exten, "s");
858 tmp->priority = 1;
860 tmp->cdr = ast_cdr_alloc();
861 ast_cdr_init(tmp->cdr, tmp);
862 ast_cdr_start(tmp->cdr);
864 headp = &tmp->varshead;
865 AST_LIST_HEAD_INIT_NOLOCK(headp);
867 ast_mutex_init(&tmp->lock);
869 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
871 ast_string_field_set(tmp, language, defaultlanguage);
873 tmp->tech = &null_tech;
875 AST_LIST_LOCK(&channels);
876 AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
877 AST_LIST_UNLOCK(&channels);
879 /*\!note
880 * and now, since the channel structure is built, and has its name, let's
881 * call the manager event generator with this Newchannel event. This is the
882 * proper and correct place to make this call, but you sure do have to pass
883 * a lot of data into this func to do it here!
885 if (!ast_strlen_zero(name_fmt)) {
886 manager_event(EVENT_FLAG_CALL, "Newchannel",
887 "Channel: %s\r\n"
888 "State: %s\r\n"
889 "CallerIDNum: %s\r\n"
890 "CallerIDName: %s\r\n"
891 "Uniqueid: %s\r\n",
892 tmp->name, ast_state2str(state),
893 S_OR(cid_num, "<unknown>"),
894 S_OR(cid_name, "<unknown>"),
895 tmp->uniqueid);
898 return tmp;
901 /*! \brief Queue an outgoing media frame */
902 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
904 struct ast_frame *f;
905 struct ast_frame *cur;
906 int blah = 1;
907 int qlen = 0;
909 /* Build us a copy and free the original one */
910 if (!(f = ast_frdup(fin))) {
911 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
912 return -1;
914 ast_channel_lock(chan);
916 /* See if the last frame on the queue is a hangup, if so don't queue anything */
917 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
918 ast_frfree(f);
919 ast_channel_unlock(chan);
920 return 0;
923 /* Count how many frames exist on the queue */
924 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
925 qlen++;
928 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
929 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
930 if (fin->frametype != AST_FRAME_VOICE) {
931 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
932 ast_assert(fin->frametype == AST_FRAME_VOICE);
933 } else {
934 if (option_debug)
935 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
936 ast_frfree(f);
937 ast_channel_unlock(chan);
938 return 0;
941 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
942 if (chan->alertpipe[1] > -1) {
943 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
944 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
945 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
946 #ifdef HAVE_DAHDI
947 } else if (chan->timingfd > -1) {
948 ioctl(chan->timingfd, DAHDI_TIMERPING, &blah);
949 #endif
950 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
951 pthread_kill(chan->blocker, SIGURG);
953 ast_channel_unlock(chan);
954 return 0;
957 /*! \brief Queue a hangup frame for channel */
958 int ast_queue_hangup(struct ast_channel *chan)
960 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
961 /* Yeah, let's not change a lock-critical value without locking */
962 if (!ast_channel_trylock(chan)) {
963 chan->_softhangup |= AST_SOFTHANGUP_DEV;
964 ast_channel_unlock(chan);
966 return ast_queue_frame(chan, &f);
969 /*! \brief Queue a control frame */
970 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
972 struct ast_frame f = { AST_FRAME_CONTROL, };
974 f.subclass = control;
976 return ast_queue_frame(chan, &f);
979 /*! \brief Queue a control frame with payload */
980 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
981 const void *data, size_t datalen)
983 struct ast_frame f = { AST_FRAME_CONTROL, };
985 f.subclass = control;
986 f.data = (void *) data;
987 f.datalen = datalen;
989 return ast_queue_frame(chan, &f);
992 /*! \brief Set defer DTMF flag on channel */
993 int ast_channel_defer_dtmf(struct ast_channel *chan)
995 int pre = 0;
997 if (chan) {
998 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
999 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1001 return pre;
1004 /*! \brief Unset defer DTMF flag on channel */
1005 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1007 if (chan)
1008 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1012 * \brief Helper function to find channels.
1014 * It supports these modes:
1016 * prev != NULL : get channel next in list after prev
1017 * name != NULL : get channel with matching name
1018 * name != NULL && namelen != 0 : get channel whose name starts with prefix
1019 * exten != NULL : get channel whose exten or macroexten matches
1020 * context != NULL && exten != NULL : get channel whose context or macrocontext
1022 * It returns with the channel's lock held. If getting the individual lock fails,
1023 * unlock and retry quickly up to 10 times, then give up.
1025 * \note XXX Note that this code has cost O(N) because of the need to verify
1026 * that the object is still on the global list.
1028 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
1029 * can only be done with the lock held or someone could delete the
1030 * object while we work on it. This causes some ugliness in the code.
1031 * Note that removing the first ast_log() may be harmful, as it would
1032 * shorten the retry period and possibly cause failures.
1033 * We should definitely go for a better scheme that is deadlock-free.
1035 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
1036 const char *name, const int namelen,
1037 const char *context, const char *exten, const char *uniqueid)
1039 const char *msg = prev ? "deadlock" : "initial deadlock";
1040 int retries;
1041 struct ast_channel *c;
1042 const struct ast_channel *_prev = prev;
1044 for (retries = 0; retries < 200; retries++) {
1045 int done;
1046 /* Reset prev on each retry. See note below for the reason. */
1047 prev = _prev;
1048 AST_LIST_LOCK(&channels);
1049 AST_LIST_TRAVERSE(&channels, c, chan_list) {
1050 if (prev) { /* look for last item, first, before any evaluation */
1051 if (c != prev) /* not this one */
1052 continue;
1053 /* found, prepare to return c->next */
1054 if ((c = AST_LIST_NEXT(c, chan_list)) == NULL) break;
1055 /*!\note
1056 * We're done searching through the list for the previous item.
1057 * Any item after this point, we want to evaluate for a match.
1058 * If we didn't set prev to NULL here, then we would only
1059 * return matches for the first matching item (since the above
1060 * "if (c != prev)" would not permit any other potential
1061 * matches to reach the additional matching logic, below).
1062 * Instead, it would just iterate until it once again found the
1063 * original match, then iterate down to the end of the list and
1064 * quit.
1066 prev = NULL;
1068 if (uniqueid) {
1069 if (!strcasecmp(c->uniqueid, uniqueid))
1070 break;
1071 } else if (name) { /* want match by name */
1072 if ((!namelen && strcasecmp(c->name, name)) ||
1073 (namelen && strncasecmp(c->name, name, namelen)))
1074 continue; /* name match failed */
1075 } else if (exten) {
1076 if (context && strcasecmp(c->context, context) &&
1077 strcasecmp(c->macrocontext, context))
1078 continue; /* context match failed */
1079 if (strcasecmp(c->exten, exten) &&
1080 strcasecmp(c->macroexten, exten))
1081 continue; /* exten match failed */
1083 /* if we get here, c points to the desired record */
1084 break;
1086 /* exit if chan not found or mutex acquired successfully */
1087 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1088 done = c == NULL || ast_channel_trylock(c) == 0;
1089 if (!done) {
1090 if (option_debug)
1091 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
1092 if (retries == 199) {
1093 /* We are about to fail due to a deadlock, so report this
1094 * while we still have the list lock.
1096 if (option_debug)
1097 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n", c, retries);
1098 /* As we have deadlocked, we will skip this channel and
1099 * see if there is another match.
1100 * NOTE: No point doing this for a full-name match,
1101 * as there can be no more matches.
1103 if (!(name && !namelen)) {
1104 prev = c;
1105 retries = -1;
1109 AST_LIST_UNLOCK(&channels);
1110 if (done)
1111 return c;
1112 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1113 * starting from the beginning of the list we can restore our saved pointer to the previous
1114 * channel and start from there.
1116 prev = _prev;
1117 usleep(1); /* give other threads a chance before retrying */
1120 return NULL;
1123 /*! \brief Browse channels in use */
1124 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1126 return channel_find_locked(prev, NULL, 0, NULL, NULL, NULL);
1129 /*! \brief Get channel by name and lock it */
1130 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1132 return channel_find_locked(NULL, name, 0, NULL, NULL, NULL);
1135 /*! \brief Get channel by name prefix and lock it */
1136 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1138 return channel_find_locked(NULL, name, namelen, NULL, NULL, NULL);
1141 /*! \brief Get next channel by name prefix and lock it */
1142 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1143 const int namelen)
1145 return channel_find_locked(chan, name, namelen, NULL, NULL, NULL);
1148 /*! \brief Get channel by exten (and optionally context) and lock it */
1149 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1151 return channel_find_locked(NULL, NULL, 0, context, exten, NULL);
1154 /*! \brief Get next channel by exten (and optionally context) and lock it */
1155 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1156 const char *context)
1158 return channel_find_locked(chan, NULL, 0, context, exten, NULL);
1161 struct ast_channel *ast_get_channel_by_uniqueid_locked(const char *uniqueid)
1163 return channel_find_locked(NULL, NULL, 0, NULL, NULL, uniqueid);
1166 /*! \brief Wait, look for hangups and condition arg */
1167 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1169 struct ast_frame *f;
1171 while (ms > 0) {
1172 if (cond && ((*cond)(data) == 0))
1173 return 0;
1174 ms = ast_waitfor(chan, ms);
1175 if (ms < 0)
1176 return -1;
1177 if (ms > 0) {
1178 f = ast_read(chan);
1179 if (!f)
1180 return -1;
1181 ast_frfree(f);
1184 return 0;
1187 /*! \brief Wait, look for hangups */
1188 int ast_safe_sleep(struct ast_channel *chan, int ms)
1190 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1193 static void free_cid(struct ast_callerid *cid)
1195 if (cid->cid_dnid)
1196 free(cid->cid_dnid);
1197 if (cid->cid_num)
1198 free(cid->cid_num);
1199 if (cid->cid_name)
1200 free(cid->cid_name);
1201 if (cid->cid_ani)
1202 free(cid->cid_ani);
1203 if (cid->cid_rdnis)
1204 free(cid->cid_rdnis);
1207 /*! \brief Free a channel structure */
1208 void ast_channel_free(struct ast_channel *chan)
1210 int fd;
1211 struct ast_var_t *vardata;
1212 struct ast_frame *f;
1213 struct varshead *headp;
1214 struct ast_datastore *datastore = NULL;
1215 char name[AST_CHANNEL_NAME], *dashptr;
1217 headp=&chan->varshead;
1219 AST_LIST_LOCK(&channels);
1220 if (!AST_LIST_REMOVE(&channels, chan, chan_list)) {
1221 AST_LIST_UNLOCK(&channels);
1222 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1224 /* Lock and unlock the channel just to be sure nobody has it locked still
1225 due to a reference retrieved from the channel list. */
1226 ast_channel_lock(chan);
1227 ast_channel_unlock(chan);
1229 /* Get rid of each of the data stores on the channel */
1230 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1231 /* Free the data store */
1232 ast_channel_datastore_free(datastore);
1234 /* Lock and unlock the channel just to be sure nobody has it locked still
1235 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1236 ast_channel_lock(chan);
1237 ast_channel_unlock(chan);
1239 if (chan->tech_pvt) {
1240 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1241 free(chan->tech_pvt);
1244 if (chan->sched)
1245 sched_context_destroy(chan->sched);
1247 ast_copy_string(name, chan->name, sizeof(name));
1248 if ((dashptr = strrchr(name, '-'))) {
1249 *dashptr = '\0';
1252 /* Stop monitoring */
1253 if (chan->monitor)
1254 chan->monitor->stop( chan, 0 );
1256 /* If there is native format music-on-hold state, free it */
1257 if (chan->music_state)
1258 ast_moh_cleanup(chan);
1260 /* Free translators */
1261 if (chan->readtrans)
1262 ast_translator_free_path(chan->readtrans);
1263 if (chan->writetrans)
1264 ast_translator_free_path(chan->writetrans);
1265 if (chan->pbx)
1266 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1267 free_cid(&chan->cid);
1268 /* Close pipes if appropriate */
1269 if ((fd = chan->alertpipe[0]) > -1)
1270 close(fd);
1271 if ((fd = chan->alertpipe[1]) > -1)
1272 close(fd);
1273 if ((fd = chan->timingfd) > -1)
1274 close(fd);
1275 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1276 ast_frfree(f);
1278 /* loop over the variables list, freeing all data and deleting list items */
1279 /* no need to lock the list, as the channel is already locked */
1281 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1282 ast_var_delete(vardata);
1284 ast_app_group_discard(chan);
1286 /* Destroy the jitterbuffer */
1287 ast_jb_destroy(chan);
1289 if (chan->cdr) {
1290 ast_cdr_detach(chan->cdr);
1291 chan->cdr = NULL;
1294 ast_mutex_destroy(&chan->lock);
1296 ast_string_field_free_memory(chan);
1297 free(chan);
1298 AST_LIST_UNLOCK(&channels);
1300 ast_device_state_changed_literal(name);
1303 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1305 struct ast_datastore *datastore = NULL;
1307 /* Make sure we at least have type so we can identify this */
1308 if (info == NULL) {
1309 return NULL;
1312 /* Allocate memory for datastore and clear it */
1313 datastore = ast_calloc(1, sizeof(*datastore));
1314 if (datastore == NULL) {
1315 return NULL;
1318 datastore->info = info;
1320 datastore->uid = ast_strdup(uid);
1322 return datastore;
1325 int ast_channel_datastore_free(struct ast_datastore *datastore)
1327 int res = 0;
1329 /* Using the destroy function (if present) destroy the data */
1330 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1331 datastore->info->destroy(datastore->data);
1332 datastore->data = NULL;
1335 /* Free allocated UID memory */
1336 if (datastore->uid != NULL) {
1337 free(datastore->uid);
1338 datastore->uid = NULL;
1341 /* Finally free memory used by ourselves */
1342 free(datastore);
1344 return res;
1347 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1349 struct ast_datastore *datastore = NULL, *datastore2;
1351 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1352 if (datastore->inheritance > 0) {
1353 datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1354 if (datastore2) {
1355 datastore2->data = datastore->info->duplicate(datastore->data);
1356 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1357 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1361 return 0;
1364 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1366 int res = 0;
1368 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1370 return res;
1373 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1375 struct ast_datastore *datastore2 = NULL;
1376 int res = -1;
1378 /* Find our position and remove ourselves */
1379 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1380 if (datastore2 == datastore) {
1381 AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1382 res = 0;
1383 break;
1386 AST_LIST_TRAVERSE_SAFE_END
1388 return res;
1391 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1393 struct ast_datastore *datastore = NULL;
1395 if (info == NULL)
1396 return NULL;
1398 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1399 if (datastore->info == info) {
1400 if (uid != NULL && datastore->uid != NULL) {
1401 if (!strcasecmp(uid, datastore->uid)) {
1402 /* Matched by type AND uid */
1403 break;
1405 } else {
1406 /* Matched by type at least */
1407 break;
1411 AST_LIST_TRAVERSE_SAFE_END
1413 return datastore;
1416 /*! \brief Softly hangup a channel, don't lock */
1417 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1419 if (option_debug)
1420 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1421 /* Inform channel driver that we need to be hung up, if it cares */
1422 chan->_softhangup |= cause;
1423 ast_queue_frame(chan, &ast_null_frame);
1424 /* Interrupt any poll call or such */
1425 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1426 pthread_kill(chan->blocker, SIGURG);
1427 return 0;
1430 /*! \brief Softly hangup a channel, lock */
1431 int ast_softhangup(struct ast_channel *chan, int cause)
1433 int res;
1434 ast_channel_lock(chan);
1435 res = ast_softhangup_nolock(chan, cause);
1436 ast_channel_unlock(chan);
1437 return res;
1440 static void free_translation(struct ast_channel *clone)
1442 if (clone->writetrans)
1443 ast_translator_free_path(clone->writetrans);
1444 if (clone->readtrans)
1445 ast_translator_free_path(clone->readtrans);
1446 clone->writetrans = NULL;
1447 clone->readtrans = NULL;
1448 clone->rawwriteformat = clone->nativeformats;
1449 clone->rawreadformat = clone->nativeformats;
1452 /*! \brief Hangup a channel */
1453 int ast_hangup(struct ast_channel *chan)
1455 int res = 0;
1457 /* Don't actually hang up a channel that will masquerade as someone else, or
1458 if someone is going to masquerade as us */
1459 ast_channel_lock(chan);
1461 if (chan->audiohooks) {
1462 ast_audiohook_detach_list(chan->audiohooks);
1463 chan->audiohooks = NULL;
1466 ast_autoservice_stop(chan);
1468 if (chan->masq) {
1469 if (ast_do_masquerade(chan))
1470 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1473 if (chan->masq) {
1474 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1475 ast_channel_unlock(chan);
1476 return 0;
1478 /* If this channel is one which will be masqueraded into something,
1479 mark it as a zombie already, so we know to free it later */
1480 if (chan->masqr) {
1481 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1482 ast_channel_unlock(chan);
1483 return 0;
1485 free_translation(chan);
1486 /* Close audio stream */
1487 if (chan->stream) {
1488 ast_closestream(chan->stream);
1489 chan->stream = NULL;
1491 /* Close video stream */
1492 if (chan->vstream) {
1493 ast_closestream(chan->vstream);
1494 chan->vstream = NULL;
1496 if (chan->sched) {
1497 sched_context_destroy(chan->sched);
1498 chan->sched = NULL;
1501 if (chan->generatordata) /* Clear any tone stuff remaining */
1502 chan->generator->release(chan, chan->generatordata);
1503 chan->generatordata = NULL;
1504 chan->generator = NULL;
1505 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1506 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1507 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1508 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1509 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
1511 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1512 if (option_debug)
1513 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1514 if (chan->tech->hangup)
1515 res = chan->tech->hangup(chan);
1516 } else {
1517 if (option_debug)
1518 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1521 ast_channel_unlock(chan);
1522 manager_event(EVENT_FLAG_CALL, "Hangup",
1523 "Channel: %s\r\n"
1524 "Uniqueid: %s\r\n"
1525 "Cause: %d\r\n"
1526 "Cause-txt: %s\r\n",
1527 chan->name,
1528 chan->uniqueid,
1529 chan->hangupcause,
1530 ast_cause2str(chan->hangupcause)
1533 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
1534 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
1535 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
1537 ast_cdr_end(chan->cdr);
1538 ast_cdr_detach(chan->cdr);
1539 chan->cdr = NULL;
1542 ast_channel_free(chan);
1544 return res;
1547 int ast_answer(struct ast_channel *chan)
1549 int res = 0;
1550 ast_channel_lock(chan);
1551 /* You can't answer an outbound call */
1552 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1553 ast_channel_unlock(chan);
1554 return 0;
1556 /* Stop if we're a zombie or need a soft hangup */
1557 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1558 ast_channel_unlock(chan);
1559 return -1;
1561 switch(chan->_state) {
1562 case AST_STATE_RINGING:
1563 case AST_STATE_RING:
1564 if (chan->tech->answer)
1565 res = chan->tech->answer(chan);
1566 ast_setstate(chan, AST_STATE_UP);
1567 ast_cdr_answer(chan->cdr);
1568 break;
1569 case AST_STATE_UP:
1570 break;
1571 default:
1572 break;
1574 chan->visible_indication = 0;
1575 ast_channel_unlock(chan);
1576 return res;
1579 void ast_deactivate_generator(struct ast_channel *chan)
1581 ast_channel_lock(chan);
1582 if (chan->generatordata) {
1583 if (chan->generator && chan->generator->release)
1584 chan->generator->release(chan, chan->generatordata);
1585 chan->generatordata = NULL;
1586 chan->generator = NULL;
1587 chan->fds[AST_GENERATOR_FD] = -1;
1588 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1589 ast_settimeout(chan, 0, NULL, NULL);
1591 ast_channel_unlock(chan);
1594 static int generator_force(const void *data)
1596 /* Called if generator doesn't have data */
1597 void *tmp;
1598 int res;
1599 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1600 struct ast_channel *chan = (struct ast_channel *)data;
1602 ast_channel_lock(chan);
1603 tmp = chan->generatordata;
1604 chan->generatordata = NULL;
1605 if (chan->generator)
1606 generate = chan->generator->generate;
1607 ast_channel_unlock(chan);
1609 if (!tmp || !generate)
1610 return 0;
1612 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
1614 chan->generatordata = tmp;
1616 if (res) {
1617 if (option_debug)
1618 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1619 ast_deactivate_generator(chan);
1622 return 0;
1625 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1627 int res = 0;
1629 ast_channel_lock(chan);
1631 if (chan->generatordata) {
1632 if (chan->generator && chan->generator->release)
1633 chan->generator->release(chan, chan->generatordata);
1634 chan->generatordata = NULL;
1637 ast_prod(chan);
1638 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1639 res = -1;
1642 if (!res) {
1643 ast_settimeout(chan, 160, generator_force, chan);
1644 chan->generator = gen;
1647 ast_channel_unlock(chan);
1649 return res;
1652 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1653 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1655 int winner = -1;
1656 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1657 return winner;
1660 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1661 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1662 int *exception, int *outfd, int *ms)
1664 struct timeval start = { 0 , 0 };
1665 struct pollfd *pfds = NULL;
1666 int res;
1667 long rms;
1668 int x, y, max;
1669 int sz;
1670 time_t now = 0;
1671 long whentohangup = 0, diff;
1672 struct ast_channel *winner = NULL;
1673 struct fdmap {
1674 int chan;
1675 int fdno;
1676 } *fdmap = NULL;
1678 if ((sz = n * AST_MAX_FDS + nfds)) {
1679 pfds = alloca(sizeof(*pfds) * sz);
1680 fdmap = alloca(sizeof(*fdmap) * sz);
1683 if (outfd)
1684 *outfd = -99999;
1685 if (exception)
1686 *exception = 0;
1688 /* Perform any pending masquerades */
1689 for (x=0; x < n; x++) {
1690 ast_channel_lock(c[x]);
1691 if (c[x]->masq) {
1692 if (ast_do_masquerade(c[x])) {
1693 ast_log(LOG_WARNING, "Masquerade failed\n");
1694 *ms = -1;
1695 ast_channel_unlock(c[x]);
1696 return NULL;
1699 if (c[x]->whentohangup) {
1700 if (!whentohangup)
1701 time(&now);
1702 diff = c[x]->whentohangup - now;
1703 if (diff < 1) {
1704 /* Should already be hungup */
1705 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1706 ast_channel_unlock(c[x]);
1707 return c[x];
1709 if (!whentohangup || (diff < whentohangup))
1710 whentohangup = diff;
1712 ast_channel_unlock(c[x]);
1714 /* Wait full interval */
1715 rms = *ms;
1716 if (whentohangup) {
1717 rms = whentohangup * 1000; /* timeout in milliseconds */
1718 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1719 rms = *ms;
1722 * Build the pollfd array, putting the channels' fds first,
1723 * followed by individual fds. Order is important because
1724 * individual fd's must have priority over channel fds.
1726 max = 0;
1727 for (x=0; x<n; x++) {
1728 for (y=0; y<AST_MAX_FDS; y++) {
1729 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1730 fdmap[max].chan = x; /* channel x is linked to this pfds */
1731 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1733 CHECK_BLOCKING(c[x]);
1735 /* Add the individual fds */
1736 for (x=0; x<nfds; x++) {
1737 fdmap[max].chan = -1;
1738 max += ast_add_fd(&pfds[max], fds[x]);
1741 if (*ms > 0)
1742 start = ast_tvnow();
1744 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1745 do {
1746 int kbrms = rms;
1747 if (kbrms > 600000)
1748 kbrms = 600000;
1749 res = poll(pfds, max, kbrms);
1750 if (!res)
1751 rms -= kbrms;
1752 } while (!res && (rms > 0));
1753 } else {
1754 res = poll(pfds, max, rms);
1756 for (x=0; x<n; x++)
1757 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1758 if (res < 0) { /* Simulate a timeout if we were interrupted */
1759 if (errno != EINTR)
1760 *ms = -1;
1761 return NULL;
1763 if (whentohangup) { /* if we have a timeout, check who expired */
1764 time(&now);
1765 for (x=0; x<n; x++) {
1766 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1767 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1768 if (winner == NULL)
1769 winner = c[x];
1773 if (res == 0) { /* no fd ready, reset timeout and done */
1774 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1775 return winner;
1778 * Then check if any channel or fd has a pending event.
1779 * Remember to check channels first and fds last, as they
1780 * must have priority on setting 'winner'
1782 for (x = 0; x < max; x++) {
1783 res = pfds[x].revents;
1784 if (res == 0)
1785 continue;
1786 if (fdmap[x].chan >= 0) { /* this is a channel */
1787 winner = c[fdmap[x].chan]; /* override previous winners */
1788 if (res & POLLPRI)
1789 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1790 else
1791 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1792 winner->fdno = fdmap[x].fdno;
1793 } else { /* this is an fd */
1794 if (outfd)
1795 *outfd = pfds[x].fd;
1796 if (exception)
1797 *exception = (res & POLLPRI) ? -1 : 0;
1798 winner = NULL;
1801 if (*ms > 0) {
1802 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1803 if (*ms < 0)
1804 *ms = 0;
1806 return winner;
1809 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1811 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1814 int ast_waitfor(struct ast_channel *c, int ms)
1816 int oldms = ms; /* -1 if no timeout */
1818 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1819 if ((ms < 0) && (oldms < 0))
1820 ms = 0;
1821 return ms;
1824 /* XXX never to be called with ms = -1 */
1825 int ast_waitfordigit(struct ast_channel *c, int ms)
1827 return ast_waitfordigit_full(c, ms, -1, -1);
1830 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
1832 int res = -1;
1833 #ifdef HAVE_DAHDI
1834 if (c->timingfd > -1) {
1835 if (!func) {
1836 samples = 0;
1837 data = 0;
1839 if (option_debug)
1840 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1841 res = ioctl(c->timingfd, DAHDI_TIMERCONFIG, &samples);
1842 c->timingfunc = func;
1843 c->timingdata = data;
1845 #endif
1846 return res;
1849 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1851 /* Stop if we're a zombie or need a soft hangup */
1852 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1853 return -1;
1855 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
1856 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
1858 /* Wait for a digit, no more than ms milliseconds total. */
1859 while (ms) {
1860 struct ast_channel *rchan;
1861 int outfd;
1863 errno = 0;
1864 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1865 if (!rchan && outfd < 0 && ms) {
1866 if (errno == 0 || errno == EINTR)
1867 continue;
1868 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1869 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1870 return -1;
1871 } else if (outfd > -1) {
1872 /* The FD we were watching has something waiting */
1873 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1874 return 1;
1875 } else if (rchan) {
1876 int res;
1877 struct ast_frame *f = ast_read(c);
1878 if (!f)
1879 return -1;
1881 switch(f->frametype) {
1882 case AST_FRAME_DTMF_BEGIN:
1883 break;
1884 case AST_FRAME_DTMF_END:
1885 res = f->subclass;
1886 ast_frfree(f);
1887 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1888 return res;
1889 case AST_FRAME_CONTROL:
1890 switch(f->subclass) {
1891 case AST_CONTROL_HANGUP:
1892 ast_frfree(f);
1893 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1894 return -1;
1895 case AST_CONTROL_RINGING:
1896 case AST_CONTROL_ANSWER:
1897 case AST_CONTROL_SRCUPDATE:
1898 /* Unimportant */
1899 break;
1900 default:
1901 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1902 break;
1904 break;
1905 case AST_FRAME_VOICE:
1906 /* Write audio if appropriate */
1907 if (audiofd > -1)
1908 write(audiofd, f->data, f->datalen);
1909 default:
1910 /* Ignore */
1911 break;
1913 ast_frfree(f);
1917 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1919 return 0; /* Time is up */
1922 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
1924 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
1925 void *tmp = chan->generatordata;
1926 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1927 int res;
1928 int samples;
1930 if (chan->timingfunc) {
1931 if (option_debug > 1)
1932 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1933 ast_settimeout(chan, 0, NULL, NULL);
1936 chan->generatordata = NULL; /* reset, to let writes go through */
1938 if (f->subclass != chan->writeformat) {
1939 float factor;
1940 factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass));
1941 samples = (int) ( ((float) f->samples) * factor );
1942 } else {
1943 samples = f->samples;
1946 if (chan->generator->generate) {
1947 generate = chan->generator->generate;
1949 /* This unlock is here based on two assumptions that hold true at this point in the
1950 * code. 1) this function is only called from within __ast_read() and 2) all generators
1951 * call ast_write() in their generate callback.
1953 * The reason this is added is so that when ast_write is called, the lock that occurs
1954 * there will not recursively lock the channel. Doing this will cause intended deadlock
1955 * avoidance not to work in deeper functions
1957 ast_channel_unlock(chan);
1958 res = generate(chan, tmp, f->datalen, samples);
1959 ast_channel_lock(chan);
1960 chan->generatordata = tmp;
1961 if (res) {
1962 if (option_debug > 1)
1963 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1964 ast_deactivate_generator(chan);
1967 } else if (f->frametype == AST_FRAME_CNG) {
1968 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1969 if (option_debug > 1)
1970 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
1971 ast_settimeout(chan, 160, generator_force, chan);
1976 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1978 struct ast_frame *f = NULL; /* the return value */
1979 int blah;
1980 int prestate;
1981 int count = 0;
1983 /* this function is very long so make sure there is only one return
1984 * point at the end (there are only two exceptions to this).
1986 while(ast_channel_trylock(chan)) {
1987 if(count++ > 10)
1988 /*cannot goto done since the channel is not locked*/
1989 return &ast_null_frame;
1990 usleep(1);
1993 if (chan->masq) {
1994 if (ast_do_masquerade(chan))
1995 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1996 else
1997 f = &ast_null_frame;
1998 goto done;
2001 /* Stop if we're a zombie or need a soft hangup */
2002 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2003 if (chan->generator)
2004 ast_deactivate_generator(chan);
2005 goto done;
2007 prestate = chan->_state;
2009 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2010 !ast_strlen_zero(chan->dtmfq) &&
2011 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2012 /* We have DTMF that has been deferred. Return it now */
2013 chan->dtmff.subclass = chan->dtmfq[0];
2014 /* Drop first digit from the buffer */
2015 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2016 f = &chan->dtmff;
2017 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2018 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2019 chan->dtmff.frametype = AST_FRAME_DTMF_END;
2020 } else {
2021 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %d queued on %s\n", f->subclass, AST_DEFAULT_EMULATE_DTMF_DURATION, chan->name);
2022 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2023 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2024 chan->emulate_dtmf_digit = f->subclass;
2025 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2027 chan->dtmf_tv = ast_tvnow();
2028 goto done;
2031 /* Read and ignore anything on the alertpipe, but read only
2032 one sizeof(blah) per frame that we send from it */
2033 if (chan->alertpipe[0] > -1) {
2034 int flags = fcntl(chan->alertpipe[0], F_GETFL);
2035 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
2036 * which immediately causes a deadlock scenario. Detect and prevent this. */
2037 if ((flags & O_NONBLOCK) == 0) {
2038 ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
2039 if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2040 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
2041 f = &ast_null_frame;
2042 goto done;
2045 read(chan->alertpipe[0], &blah, sizeof(blah));
2048 #ifdef HAVE_DAHDI
2049 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2050 int res;
2052 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2053 blah = -1;
2054 /* IF we can't get event, assume it's an expired as-per the old interface */
2055 res = ioctl(chan->timingfd, DAHDI_GETEVENT, &blah);
2056 if (res)
2057 blah = DAHDI_EVENT_TIMER_EXPIRED;
2059 if (blah == DAHDI_EVENT_TIMER_PING) {
2060 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2061 /* Acknowledge PONG unless we need it again */
2062 if (ioctl(chan->timingfd, DAHDI_TIMERPONG, &blah)) {
2063 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2066 } else if (blah == DAHDI_EVENT_TIMER_EXPIRED) {
2067 ioctl(chan->timingfd, DAHDI_TIMERACK, &blah);
2068 if (chan->timingfunc) {
2069 /* save a copy of func/data before unlocking the channel */
2070 int (*func)(const void *) = chan->timingfunc;
2071 void *data = chan->timingdata;
2072 ast_channel_unlock(chan);
2073 func(data);
2074 } else {
2075 blah = 0;
2076 ioctl(chan->timingfd, DAHDI_TIMERCONFIG, &blah);
2077 chan->timingdata = NULL;
2078 ast_channel_unlock(chan);
2080 /* cannot 'goto done' because the channel is already unlocked */
2081 return &ast_null_frame;
2082 } else
2083 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2084 } else
2085 #endif
2086 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2087 /* if the AST_GENERATOR_FD is set, call the generator with args
2088 * set to -1 so it can do whatever it needs to.
2090 void *tmp = chan->generatordata;
2091 chan->generatordata = NULL; /* reset to let ast_write get through */
2092 chan->generator->generate(chan, tmp, -1, -1);
2093 chan->generatordata = tmp;
2094 f = &ast_null_frame;
2095 goto done;
2098 /* Check for pending read queue */
2099 if (!AST_LIST_EMPTY(&chan->readq)) {
2100 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2101 /* Interpret hangup and return NULL */
2102 /* XXX why not the same for frames from the channel ? */
2103 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2104 ast_frfree(f);
2105 f = NULL;
2107 } else {
2108 chan->blocker = pthread_self();
2109 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2110 if (chan->tech->exception)
2111 f = chan->tech->exception(chan);
2112 else {
2113 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2114 f = &ast_null_frame;
2116 /* Clear the exception flag */
2117 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2118 } else if (chan->tech->read)
2119 f = chan->tech->read(chan);
2120 else
2121 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2124 if (f) {
2125 /* if the channel driver returned more than one frame, stuff the excess
2126 into the readq for the next ast_read call (note that we can safely assume
2127 that the readq is empty, because otherwise we would not have called into
2128 the channel driver and f would be only a single frame)
2130 if (AST_LIST_NEXT(f, frame_list)) {
2131 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2132 AST_LIST_NEXT(f, frame_list) = NULL;
2135 switch (f->frametype) {
2136 case AST_FRAME_CONTROL:
2137 if (f->subclass == AST_CONTROL_ANSWER) {
2138 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2139 if (option_debug)
2140 ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
2141 ast_frfree(f);
2142 f = &ast_null_frame;
2143 } else if (prestate == AST_STATE_UP) {
2144 if (option_debug)
2145 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
2146 ast_frfree(f);
2147 f = &ast_null_frame;
2148 } else {
2149 /* Answer the CDR */
2150 ast_setstate(chan, AST_STATE_UP);
2151 /* removed a call to ast_cdr_answer(chan->cdr) from here. */
2154 break;
2155 case AST_FRAME_DTMF_END:
2156 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2157 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2158 * However, only let emulation be forced if the other end cares about BEGIN frames */
2159 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2160 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2161 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2162 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2163 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2164 } else
2165 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2166 ast_frfree(f);
2167 f = &ast_null_frame;
2168 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2169 if (!ast_tvzero(chan->dtmf_tv) &&
2170 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2171 /* If it hasn't been long enough, defer this digit */
2172 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2173 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2174 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2175 } else
2176 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2177 ast_frfree(f);
2178 f = &ast_null_frame;
2179 } else {
2180 /* There was no begin, turn this into a begin and send the end later */
2181 f->frametype = AST_FRAME_DTMF_BEGIN;
2182 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2183 chan->emulate_dtmf_digit = f->subclass;
2184 chan->dtmf_tv = ast_tvnow();
2185 if (f->len) {
2186 if (f->len > AST_MIN_DTMF_DURATION)
2187 chan->emulate_dtmf_duration = f->len;
2188 else
2189 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2190 } else
2191 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2192 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2194 if (chan->audiohooks) {
2195 struct ast_frame *old_frame = f;
2196 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2197 if (old_frame != f)
2198 ast_frfree(old_frame);
2200 } else {
2201 struct timeval now = ast_tvnow();
2202 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2203 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2204 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2205 if (!f->len)
2206 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2207 } else if (!f->len) {
2208 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2209 f->len = AST_MIN_DTMF_DURATION;
2211 if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2212 ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f->subclass, f->len, AST_MIN_DTMF_DURATION, chan->name);
2213 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2214 chan->emulate_dtmf_digit = f->subclass;
2215 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2216 ast_frfree(f);
2217 f = &ast_null_frame;
2218 } else {
2219 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2220 if (f->len < AST_MIN_DTMF_DURATION) {
2221 f->len = AST_MIN_DTMF_DURATION;
2223 chan->dtmf_tv = now;
2225 if (chan->audiohooks) {
2226 struct ast_frame *old_frame = f;
2227 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2228 if (old_frame != f)
2229 ast_frfree(old_frame);
2232 break;
2233 case AST_FRAME_DTMF_BEGIN:
2234 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2235 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
2236 (!ast_tvzero(chan->dtmf_tv) &&
2237 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2238 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2239 ast_frfree(f);
2240 f = &ast_null_frame;
2241 } else {
2242 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2243 chan->dtmf_tv = ast_tvnow();
2244 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2246 break;
2247 case AST_FRAME_NULL:
2248 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2249 * is reached , because we want to make sure we pass at least one
2250 * voice frame through before starting the next digit, to ensure a gap
2251 * between DTMF digits. */
2252 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2253 struct timeval now = ast_tvnow();
2254 if (!chan->emulate_dtmf_duration) {
2255 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2256 chan->emulate_dtmf_digit = 0;
2257 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2258 chan->emulate_dtmf_duration = 0;
2259 ast_frfree(f);
2260 f = &chan->dtmff;
2261 f->frametype = AST_FRAME_DTMF_END;
2262 f->subclass = chan->emulate_dtmf_digit;
2263 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2264 chan->dtmf_tv = now;
2265 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2266 chan->emulate_dtmf_digit = 0;
2267 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2270 break;
2271 case AST_FRAME_VOICE:
2272 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2273 * is reached , because we want to make sure we pass at least one
2274 * voice frame through before starting the next digit, to ensure a gap
2275 * between DTMF digits. */
2276 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2277 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2278 chan->emulate_dtmf_digit = 0;
2281 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2282 if (dropaudio)
2283 ast_read_generator_actions(chan, f);
2284 ast_frfree(f);
2285 f = &ast_null_frame;
2288 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2289 struct timeval now = ast_tvnow();
2290 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2291 chan->emulate_dtmf_duration = 0;
2292 ast_frfree(f);
2293 f = &chan->dtmff;
2294 f->frametype = AST_FRAME_DTMF_END;
2295 f->subclass = chan->emulate_dtmf_digit;
2296 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2297 chan->dtmf_tv = now;
2298 if (chan->audiohooks) {
2299 struct ast_frame *old_frame = f;
2300 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2301 if (old_frame != f)
2302 ast_frfree(old_frame);
2304 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2305 } else {
2306 /* Drop voice frames while we're still in the middle of the digit */
2307 ast_frfree(f);
2308 f = &ast_null_frame;
2310 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2311 /* This frame is not one of the current native formats -- drop it on the floor */
2312 char to[200];
2313 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2314 chan->name, ast_getformatname(f->subclass), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
2315 ast_frfree(f);
2316 f = &ast_null_frame;
2317 } else if ((f->frametype == AST_FRAME_VOICE)) {
2318 if (chan->audiohooks) {
2319 struct ast_frame *old_frame = f;
2320 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2321 if (old_frame != f)
2322 ast_frfree(old_frame);
2324 if (chan->monitor && chan->monitor->read_stream ) {
2325 /* XXX what does this do ? */
2326 #ifndef MONITOR_CONSTANT_DELAY
2327 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2328 if (jump >= 0) {
2329 jump = chan->outsmpl - chan->insmpl;
2330 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2331 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2332 chan->insmpl += jump + f->samples;
2333 } else
2334 chan->insmpl+= f->samples;
2335 #else
2336 int jump = chan->outsmpl - chan->insmpl;
2337 if (jump - MONITOR_DELAY >= 0) {
2338 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2339 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2340 chan->insmpl += jump;
2341 } else
2342 chan->insmpl += f->samples;
2343 #endif
2344 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2345 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2346 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2350 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2351 f = &ast_null_frame;
2353 /* Run generator sitting on the line if timing device not available
2354 * and synchronous generation of outgoing frames is necessary */
2355 ast_read_generator_actions(chan, f);
2357 default:
2358 /* Just pass it on! */
2359 break;
2361 } else {
2362 /* Make sure we always return NULL in the future */
2363 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2364 if (chan->generator)
2365 ast_deactivate_generator(chan);
2366 /* We no longer End the CDR here */
2369 /* High bit prints debugging */
2370 if (chan->fin & DEBUGCHAN_FLAG)
2371 ast_frame_dump(chan->name, f, "<<");
2372 chan->fin = FRAMECOUNT_INC(chan->fin);
2374 done:
2375 ast_channel_unlock(chan);
2376 return f;
2379 int ast_internal_timing_enabled(struct ast_channel *chan)
2381 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2382 if (option_debug > 4)
2383 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);
2384 return ret;
2387 struct ast_frame *ast_read(struct ast_channel *chan)
2389 return __ast_read(chan, 0);
2392 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2394 return __ast_read(chan, 1);
2397 int ast_indicate(struct ast_channel *chan, int condition)
2399 return ast_indicate_data(chan, condition, NULL, 0);
2402 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2404 int res = -1;
2406 ast_channel_lock(chan);
2407 /* Stop if we're a zombie or need a soft hangup */
2408 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2409 ast_channel_unlock(chan);
2410 return -1;
2412 if (chan->tech->indicate)
2413 res = chan->tech->indicate(chan, condition, data, datalen);
2414 ast_channel_unlock(chan);
2415 if (!chan->tech->indicate || res) {
2417 * Device does not support (that) indication, lets fake
2418 * it by doing our own tone generation. (PM2002)
2420 if (condition < 0)
2421 ast_playtones_stop(chan);
2422 else {
2423 const struct ind_tone_zone_sound *ts = NULL;
2424 switch (condition) {
2425 case AST_CONTROL_RINGING:
2426 ts = ast_get_indication_tone(chan->zone, "ring");
2427 break;
2428 case AST_CONTROL_BUSY:
2429 ts = ast_get_indication_tone(chan->zone, "busy");
2430 break;
2431 case AST_CONTROL_CONGESTION:
2432 ts = ast_get_indication_tone(chan->zone, "congestion");
2433 break;
2435 if (ts && ts->data[0]) {
2436 if (option_debug)
2437 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2438 ast_playtones_start(chan,0,ts->data, 1);
2439 res = 0;
2440 chan->visible_indication = condition;
2441 } else if (condition == AST_CONTROL_PROGRESS) {
2442 /* ast_playtones_stop(chan); */
2443 } else if (condition == AST_CONTROL_PROCEEDING) {
2444 /* Do nothing, really */
2445 } else if (condition == AST_CONTROL_HOLD) {
2446 /* Do nothing.... */
2447 } else if (condition == AST_CONTROL_UNHOLD) {
2448 /* Do nothing.... */
2449 } else if (condition == AST_CONTROL_VIDUPDATE) {
2450 /* Do nothing.... */
2451 } else if (condition == AST_CONTROL_SRCUPDATE) {
2452 /* Do nothing... */
2453 } else {
2454 /* not handled */
2455 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2456 res = -1;
2459 } else
2460 chan->visible_indication = condition;
2462 return res;
2465 int ast_recvchar(struct ast_channel *chan, int timeout)
2467 int c;
2468 char *buf = ast_recvtext(chan, timeout);
2469 if (buf == NULL)
2470 return -1; /* error or timeout */
2471 c = *(unsigned char *)buf;
2472 free(buf);
2473 return c;
2476 char *ast_recvtext(struct ast_channel *chan, int timeout)
2478 int res, done = 0;
2479 char *buf = NULL;
2481 while (!done) {
2482 struct ast_frame *f;
2483 if (ast_check_hangup(chan))
2484 break;
2485 res = ast_waitfor(chan, timeout);
2486 if (res <= 0) /* timeout or error */
2487 break;
2488 timeout = res; /* update timeout */
2489 f = ast_read(chan);
2490 if (f == NULL)
2491 break; /* no frame */
2492 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2493 done = 1; /* force a break */
2494 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2495 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2496 done = 1;
2498 ast_frfree(f);
2500 return buf;
2503 int ast_sendtext(struct ast_channel *chan, const char *text)
2505 int res = 0;
2506 /* Stop if we're a zombie or need a soft hangup */
2507 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2508 return -1;
2509 CHECK_BLOCKING(chan);
2510 if (chan->tech->send_text)
2511 res = chan->tech->send_text(chan, text);
2512 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2513 return res;
2516 int ast_sendmessage(struct ast_channel *chan, const char *dest, const char *text, int ispdu)
2518 int res = 0;
2519 /* Stop if we're a zombie or need a soft hangup */
2520 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2521 return -1;
2522 CHECK_BLOCKING(chan);
2523 if (chan->tech->send_message)
2524 res = chan->tech->send_message(chan, dest, text, ispdu);
2525 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2526 return res;
2529 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2531 /* Device does not support DTMF tones, lets fake
2532 * it by doing our own generation. */
2533 static const char* dtmf_tones[] = {
2534 "941+1336", /* 0 */
2535 "697+1209", /* 1 */
2536 "697+1336", /* 2 */
2537 "697+1477", /* 3 */
2538 "770+1209", /* 4 */
2539 "770+1336", /* 5 */
2540 "770+1477", /* 6 */
2541 "852+1209", /* 7 */
2542 "852+1336", /* 8 */
2543 "852+1477", /* 9 */
2544 "697+1633", /* A */
2545 "770+1633", /* B */
2546 "852+1633", /* C */
2547 "941+1633", /* D */
2548 "941+1209", /* * */
2549 "941+1477" /* # */
2552 if (!chan->tech->send_digit_begin)
2553 return 0;
2555 if (!chan->tech->send_digit_begin(chan, digit))
2556 return 0;
2558 if (digit >= '0' && digit <='9')
2559 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2560 else if (digit >= 'A' && digit <= 'D')
2561 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2562 else if (digit == '*')
2563 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2564 else if (digit == '#')
2565 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2566 else {
2567 /* not handled */
2568 if (option_debug)
2569 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2572 return 0;
2575 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2577 int res = -1;
2579 if (chan->tech->send_digit_end)
2580 res = chan->tech->send_digit_end(chan, digit, duration);
2582 if (res && chan->generator)
2583 ast_playtones_stop(chan);
2585 return 0;
2588 int ast_senddigit(struct ast_channel *chan, char digit)
2590 if (chan->tech->send_digit_begin) {
2591 ast_senddigit_begin(chan, digit);
2592 ast_safe_sleep(chan, AST_DEFAULT_EMULATE_DTMF_DURATION);
2595 return ast_senddigit_end(chan, digit, AST_DEFAULT_EMULATE_DTMF_DURATION);
2598 int ast_prod(struct ast_channel *chan)
2600 struct ast_frame a = { AST_FRAME_VOICE };
2601 char nothing[128];
2603 /* Send an empty audio frame to get things moving */
2604 if (chan->_state != AST_STATE_UP) {
2605 if (option_debug)
2606 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2607 a.subclass = chan->rawwriteformat;
2608 a.data = nothing + AST_FRIENDLY_OFFSET;
2609 a.src = "ast_prod";
2610 if (ast_write(chan, &a))
2611 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2613 return 0;
2616 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2618 int res;
2619 if (!chan->tech->write_video)
2620 return 0;
2621 res = ast_write(chan, fr);
2622 if (!res)
2623 res = 1;
2624 return res;
2627 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2629 int res = -1;
2630 int count = 0;
2631 struct ast_frame *f = NULL, *f2 = NULL;
2633 /*Deadlock avoidance*/
2634 while(ast_channel_trylock(chan)) {
2635 /*cannot goto done since the channel is not locked*/
2636 if(count++ > 10) {
2637 if(option_debug)
2638 ast_log(LOG_DEBUG, "Deadlock avoided for write to channel '%s'\n", chan->name);
2639 return 0;
2641 usleep(1);
2643 /* Stop if we're a zombie or need a soft hangup */
2644 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2645 goto done;
2647 /* Handle any pending masquerades */
2648 if (chan->masq && ast_do_masquerade(chan)) {
2649 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2650 goto done;
2652 if (chan->masqr) {
2653 res = 0; /* XXX explain, why 0 ? */
2654 goto done;
2656 if (chan->generatordata) {
2657 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2658 ast_deactivate_generator(chan);
2659 else {
2660 if (fr->frametype == AST_FRAME_DTMF_END) {
2661 /* There is a generator running while we're in the middle of a digit.
2662 * It's probably inband DTMF, so go ahead and pass it so it can
2663 * stop the generator */
2664 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2665 ast_channel_unlock(chan);
2666 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2667 ast_channel_lock(chan);
2668 CHECK_BLOCKING(chan);
2669 } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2670 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2671 res = (chan->tech->indicate == NULL) ? 0 :
2672 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2674 res = 0; /* XXX explain, why 0 ? */
2675 goto done;
2678 /* High bit prints debugging */
2679 if (chan->fout & DEBUGCHAN_FLAG)
2680 ast_frame_dump(chan->name, fr, ">>");
2681 CHECK_BLOCKING(chan);
2682 switch(fr->frametype) {
2683 case AST_FRAME_CONTROL:
2684 res = (chan->tech->indicate == NULL) ? 0 :
2685 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2686 break;
2687 case AST_FRAME_DTMF_BEGIN:
2688 if (chan->audiohooks) {
2689 struct ast_frame *old_frame = fr;
2690 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2691 if (old_frame != fr)
2692 f = fr;
2694 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2695 ast_channel_unlock(chan);
2696 res = ast_senddigit_begin(chan, fr->subclass);
2697 ast_channel_lock(chan);
2698 CHECK_BLOCKING(chan);
2699 break;
2700 case AST_FRAME_DTMF_END:
2701 if (chan->audiohooks) {
2702 struct ast_frame *old_frame = fr;
2703 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2704 if (old_frame != fr)
2705 f = fr;
2707 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2708 ast_channel_unlock(chan);
2709 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2710 ast_channel_lock(chan);
2711 CHECK_BLOCKING(chan);
2712 break;
2713 case AST_FRAME_TEXT:
2714 res = (chan->tech->send_text == NULL) ? 0 :
2715 chan->tech->send_text(chan, (char *) fr->data);
2716 break;
2717 case AST_FRAME_HTML:
2718 res = (chan->tech->send_html == NULL) ? 0 :
2719 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2720 break;
2721 case AST_FRAME_VIDEO:
2722 /* XXX Handle translation of video codecs one day XXX */
2723 res = (chan->tech->write_video == NULL) ? 0 :
2724 chan->tech->write_video(chan, fr);
2725 break;
2726 case AST_FRAME_MODEM:
2727 res = (chan->tech->write == NULL) ? 0 :
2728 chan->tech->write(chan, fr);
2729 break;
2730 case AST_FRAME_VOICE:
2731 if (chan->tech->write == NULL)
2732 break; /*! \todo XXX should return 0 maybe ? */
2734 if (chan->audiohooks) {
2735 struct ast_frame *old_frame = fr;
2736 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2737 if (old_frame != fr)
2738 f2 = fr;
2741 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2742 if (fr->subclass == chan->rawwriteformat)
2743 f = fr;
2744 else
2745 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2747 /* If we have no frame of audio, then we have to bail out */
2748 if (!f) {
2749 res = 0;
2750 break;
2753 /* If Monitor is running on this channel, then we have to write frames out there too */
2754 if (chan->monitor && chan->monitor->write_stream) {
2755 /* XXX must explain this code */
2756 #ifndef MONITOR_CONSTANT_DELAY
2757 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2758 if (jump >= 0) {
2759 jump = chan->insmpl - chan->outsmpl;
2760 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2761 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2762 chan->outsmpl += jump + f->samples;
2763 } else
2764 chan->outsmpl += f->samples;
2765 #else
2766 int jump = chan->insmpl - chan->outsmpl;
2767 if (jump - MONITOR_DELAY >= 0) {
2768 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2769 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2770 chan->outsmpl += jump;
2771 } else
2772 chan->outsmpl += f->samples;
2773 #endif
2774 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2775 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2776 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2780 if (f)
2781 res = chan->tech->write(chan,f);
2782 else
2783 res = 0;
2784 break;
2785 case AST_FRAME_NULL:
2786 case AST_FRAME_IAX:
2787 /* Ignore these */
2788 res = 0;
2789 break;
2790 default:
2791 /* At this point, fr is the incoming frame and f is NULL. Channels do
2792 * not expect to get NULL as a frame pointer and will segfault. Hence,
2793 * we output the original frame passed in. */
2794 res = chan->tech->write(chan, fr);
2795 break;
2798 if (f && f != fr)
2799 ast_frfree(f);
2800 if (f2)
2801 ast_frfree(f2);
2802 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2803 /* Consider a write failure to force a soft hangup */
2804 if (res < 0)
2805 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2806 else {
2807 chan->fout = FRAMECOUNT_INC(chan->fout);
2809 done:
2810 ast_channel_unlock(chan);
2811 return res;
2814 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2815 struct ast_trans_pvt **trans, const int direction)
2817 int native;
2818 int res;
2819 char from[200], to[200];
2821 /* Make sure we only consider audio */
2822 fmt &= AST_FORMAT_AUDIO_MASK;
2824 native = chan->nativeformats;
2825 /* Find a translation path from the native format to one of the desired formats */
2826 if (!direction)
2827 /* reading */
2828 res = ast_translator_best_choice(&fmt, &native);
2829 else
2830 /* writing */
2831 res = ast_translator_best_choice(&native, &fmt);
2833 if (res < 0) {
2834 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2835 ast_getformatname_multiple(from, sizeof(from), native),
2836 ast_getformatname_multiple(to, sizeof(to), fmt));
2837 return -1;
2840 /* Now we have a good choice for both. */
2841 ast_channel_lock(chan);
2843 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2844 /* the channel is already in these formats, so nothing to do */
2845 ast_channel_unlock(chan);
2846 return 0;
2849 *rawformat = native;
2850 /* User perspective is fmt */
2851 *format = fmt;
2852 /* Free any read translation we have right now */
2853 if (*trans)
2854 ast_translator_free_path(*trans);
2855 /* Build a translation path from the raw format to the desired format */
2856 if (!direction)
2857 /* reading */
2858 *trans = ast_translator_build_path(*format, *rawformat);
2859 else
2860 /* writing */
2861 *trans = ast_translator_build_path(*rawformat, *format);
2862 ast_channel_unlock(chan);
2863 if (option_debug)
2864 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2865 direction ? "write" : "read", ast_getformatname(fmt));
2866 return 0;
2869 int ast_set_read_format(struct ast_channel *chan, int fmt)
2871 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2872 &chan->readtrans, 0);
2875 int ast_set_write_format(struct ast_channel *chan, int fmt)
2877 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2878 &chan->writetrans, 1);
2881 char *ast_channel_reason2str(int reason)
2883 switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
2885 case 0:
2886 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
2887 case AST_CONTROL_HANGUP:
2888 return "Hangup";
2889 case AST_CONTROL_RING:
2890 return "Local Ring";
2891 case AST_CONTROL_RINGING:
2892 return "Remote end Ringing";
2893 case AST_CONTROL_ANSWER:
2894 return "Remote end has Answered";
2895 case AST_CONTROL_BUSY:
2896 return "Remote end is Busy";
2897 case AST_CONTROL_CONGESTION:
2898 return "Congestion (circuits busy)";
2899 default:
2900 return "Unknown Reason!!";
2904 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)
2906 int dummy_outstate;
2907 int cause = 0;
2908 struct ast_channel *chan;
2909 int res = 0;
2910 int last_subclass = 0;
2912 if (outstate)
2913 *outstate = 0;
2914 else
2915 outstate = &dummy_outstate; /* make outstate always a valid pointer */
2917 chan = ast_request(type, format, data, &cause);
2918 if (!chan) {
2919 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2920 /* compute error and return */
2921 if (cause == AST_CAUSE_BUSY)
2922 *outstate = AST_CONTROL_BUSY;
2923 else if (cause == AST_CAUSE_CONGESTION)
2924 *outstate = AST_CONTROL_CONGESTION;
2925 return NULL;
2928 if (oh) {
2929 if (oh->vars)
2930 ast_set_variables(chan, oh->vars);
2931 /* XXX why is this necessary, for the parent_channel perhaps ? */
2932 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2933 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2934 if (oh->parent_channel)
2935 ast_channel_inherit_variables(oh->parent_channel, chan);
2936 if (oh->account)
2937 ast_cdr_setaccount(chan, oh->account);
2939 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2941 if (ast_call(chan, data, 0)) { /* ast_call failed... */
2942 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2943 } else {
2944 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
2945 while (timeout && chan->_state != AST_STATE_UP) {
2946 struct ast_frame *f;
2947 res = ast_waitfor(chan, timeout);
2948 if (res <= 0) /* error, timeout, or done */
2949 break;
2950 if (timeout > -1)
2951 timeout = res;
2952 f = ast_read(chan);
2953 if (!f) {
2954 *outstate = AST_CONTROL_HANGUP;
2955 res = 0;
2956 break;
2958 if (f->frametype == AST_FRAME_CONTROL) {
2959 switch (f->subclass) {
2960 case AST_CONTROL_RINGING: /* record but keep going */
2961 *outstate = f->subclass;
2962 break;
2964 case AST_CONTROL_BUSY:
2965 case AST_CONTROL_CONGESTION:
2966 case AST_CONTROL_ANSWER:
2967 *outstate = f->subclass;
2968 timeout = 0; /* trick to force exit from the while() */
2969 break;
2971 /* Ignore these */
2972 case AST_CONTROL_PROGRESS:
2973 case AST_CONTROL_PROCEEDING:
2974 case AST_CONTROL_HOLD:
2975 case AST_CONTROL_UNHOLD:
2976 case AST_CONTROL_VIDUPDATE:
2977 case AST_CONTROL_SRCUPDATE:
2978 case -1: /* Ignore -- just stopping indications */
2979 break;
2981 default:
2982 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2984 last_subclass = f->subclass;
2986 ast_frfree(f);
2990 /* Final fixups */
2991 if (oh) {
2992 if (!ast_strlen_zero(oh->context))
2993 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2994 if (!ast_strlen_zero(oh->exten))
2995 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2996 if (oh->priority)
2997 chan->priority = oh->priority;
2999 if (chan->_state == AST_STATE_UP)
3000 *outstate = AST_CONTROL_ANSWER;
3002 if (res <= 0) {
3003 if ( AST_CONTROL_RINGING == last_subclass )
3004 chan->hangupcause = AST_CAUSE_NO_ANSWER;
3005 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
3006 ast_cdr_init(chan->cdr, chan);
3007 if (chan->cdr) {
3008 char tmp[256];
3009 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
3010 ast_cdr_setapp(chan->cdr,"Dial",tmp);
3011 ast_cdr_update(chan);
3012 ast_cdr_start(chan->cdr);
3013 ast_cdr_end(chan->cdr);
3014 /* If the cause wasn't handled properly */
3015 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
3016 ast_cdr_failed(chan->cdr);
3018 ast_hangup(chan);
3019 chan = NULL;
3021 return chan;
3024 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
3026 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
3029 struct ast_channel *ast_request_uniqueid(const char *type, int format, void *data, int *cause, char *uniqueid)
3031 struct chanlist *chan;
3032 struct ast_channel *c;
3033 int capabilities;
3034 int fmt;
3035 int res;
3036 int foo;
3037 int videoformat = format & AST_FORMAT_VIDEO_MASK;
3039 if (!cause)
3040 cause = &foo;
3041 *cause = AST_CAUSE_NOTDEFINED;
3043 if (AST_LIST_LOCK(&channels)) {
3044 ast_log(LOG_WARNING, "Unable to lock channel list\n");
3045 return NULL;
3048 AST_LIST_TRAVERSE(&backends, chan, list) {
3049 if (strcasecmp(type, chan->tech->type))
3050 continue;
3052 capabilities = chan->tech->capabilities;
3053 fmt = format & AST_FORMAT_AUDIO_MASK;
3054 res = ast_translator_best_choice(&fmt, &capabilities);
3055 if (res < 0) {
3056 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
3057 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3058 AST_LIST_UNLOCK(&channels);
3059 return NULL;
3061 AST_LIST_UNLOCK(&channels);
3062 if (!chan->tech->requester)
3063 return NULL;
3065 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
3066 return NULL;
3068 if (uniqueid) ast_string_field_set(c, uniqueid, uniqueid);
3069 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3070 return c;
3073 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
3074 *cause = AST_CAUSE_NOSUCHDRIVER;
3075 AST_LIST_UNLOCK(&channels);
3077 return NULL;
3080 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
3082 return ast_request_uniqueid(type, format, data, cause, NULL);
3085 int ast_call(struct ast_channel *chan, char *addr, int timeout)
3087 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3088 If the remote end does not answer within the timeout, then do NOT hang up, but
3089 return anyway. */
3090 int res = -1;
3091 /* Stop if we're a zombie or need a soft hangup */
3092 ast_channel_lock(chan);
3093 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3094 if (chan->cdr)
3095 ast_set_flag(chan->cdr, AST_CDR_FLAG_DIALED);
3096 if (chan->tech->call)
3097 res = chan->tech->call(chan, addr, timeout);
3098 ast_set_flag(chan, AST_FLAG_OUTGOING);
3100 ast_channel_unlock(chan);
3101 return res;
3105 \brief Transfer a call to dest, if the channel supports transfer
3107 Called by:
3108 \arg app_transfer
3109 \arg the manager interface
3111 int ast_transfer(struct ast_channel *chan, char *dest)
3113 int res = -1;
3115 /* Stop if we're a zombie or need a soft hangup */
3116 ast_channel_lock(chan);
3117 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3118 if (chan->tech->transfer) {
3119 res = chan->tech->transfer(chan, dest);
3120 if (!res)
3121 res = 1;
3122 } else
3123 res = 0;
3125 ast_channel_unlock(chan);
3126 return res;
3129 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3131 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3134 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3136 int pos = 0; /* index in the buffer where we accumulate digits */
3137 int to = ftimeout;
3139 /* Stop if we're a zombie or need a soft hangup */
3140 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3141 return -1;
3142 if (!len)
3143 return -1;
3144 for (;;) {
3145 int d;
3146 if (c->stream) {
3147 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3148 ast_stopstream(c);
3149 usleep(1000);
3150 if (!d)
3151 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3152 } else {
3153 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3155 if (d < 0)
3156 return -1;
3157 if (d == 0) {
3158 s[pos]='\0';
3159 return 1;
3161 if (d == 1) {
3162 s[pos]='\0';
3163 return 2;
3165 if (!strchr(enders, d))
3166 s[pos++] = d;
3167 if (strchr(enders, d) || (pos >= len)) {
3168 s[pos]='\0';
3169 return 0;
3171 to = timeout;
3173 /* Never reached */
3174 return 0;
3177 int ast_channel_supports_html(struct ast_channel *chan)
3179 return (chan->tech->send_html) ? 1 : 0;
3182 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3184 if (chan->tech->send_html)
3185 return chan->tech->send_html(chan, subclass, data, datalen);
3186 return -1;
3189 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3191 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3194 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3196 int src;
3197 int dst;
3199 if (chan->readformat == peer->writeformat && chan->writeformat == peer->readformat) {
3200 /* Already compatible! Moving on ... */
3201 return 0;
3204 /* Set up translation from the chan to the peer */
3205 src = chan->nativeformats;
3206 dst = peer->nativeformats;
3207 if (ast_translator_best_choice(&dst, &src) < 0) {
3208 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
3209 return -1;
3212 /* if the best path is not 'pass through', then
3213 transcoding is needed; if desired, force transcode path
3214 to use SLINEAR between channels, but only if there is
3215 no direct conversion available */
3216 if ((src != dst) && ast_opt_transcode_via_slin &&
3217 (ast_translate_path_steps(dst, src) != 1))
3218 dst = AST_FORMAT_SLINEAR;
3219 if (ast_set_read_format(chan, dst) < 0) {
3220 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
3221 return -1;
3223 if (ast_set_write_format(peer, dst) < 0) {
3224 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
3225 return -1;
3228 /* Set up translation from the peer to the chan */
3229 src = peer->nativeformats;
3230 dst = chan->nativeformats;
3231 if (ast_translator_best_choice(&dst, &src) < 0) {
3232 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
3233 return -1;
3236 /* if the best path is not 'pass through', then
3237 transcoding is needed; if desired, force transcode path
3238 to use SLINEAR between channels, but only if there is
3239 no direct conversion available */
3240 if ((src != dst) && ast_opt_transcode_via_slin &&
3241 (ast_translate_path_steps(dst, src) != 1))
3242 dst = AST_FORMAT_SLINEAR;
3243 if (ast_set_read_format(peer, dst) < 0) {
3244 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
3245 return -1;
3247 if (ast_set_write_format(chan, dst) < 0) {
3248 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
3249 return -1;
3251 return 0;
3254 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3256 int res = -1;
3257 struct ast_channel *final_orig, *final_clone, *base;
3259 retrymasq:
3260 final_orig = original;
3261 final_clone = clone;
3263 ast_channel_lock(original);
3264 while (ast_channel_trylock(clone)) {
3265 ast_channel_unlock(original);
3266 usleep(1);
3267 ast_channel_lock(original);
3270 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3271 and if so, we don't really want to masquerade it, but its proxy */
3272 if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
3273 final_orig = original->_bridge;
3275 if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)) && (clone->_bridge->_bridge != clone))
3276 final_clone = clone->_bridge;
3278 if (final_clone->tech->get_base_channel && (base = final_clone->tech->get_base_channel(final_clone))) {
3279 final_clone = base;
3282 if ((final_orig != original) || (final_clone != clone)) {
3283 /* Lots and lots of deadlock avoidance. The main one we're competing with
3284 * is ast_write(), which locks channels recursively, when working with a
3285 * proxy channel. */
3286 if (ast_channel_trylock(final_orig)) {
3287 ast_channel_unlock(clone);
3288 ast_channel_unlock(original);
3289 goto retrymasq;
3291 if (ast_channel_trylock(final_clone)) {
3292 ast_channel_unlock(final_orig);
3293 ast_channel_unlock(clone);
3294 ast_channel_unlock(original);
3295 goto retrymasq;
3297 ast_channel_unlock(clone);
3298 ast_channel_unlock(original);
3299 original = final_orig;
3300 clone = final_clone;
3303 if (original == clone) {
3304 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3305 ast_channel_unlock(clone);
3306 ast_channel_unlock(original);
3307 return -1;
3310 if (option_debug)
3311 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
3312 clone->name, original->name);
3313 if (original->masq) {
3314 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3315 original->masq->name, original->name);
3316 } else if (clone->masqr) {
3317 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3318 clone->name, clone->masqr->name);
3319 } else {
3320 original->masq = clone;
3321 clone->masqr = original;
3322 ast_queue_frame(original, &ast_null_frame);
3323 ast_queue_frame(clone, &ast_null_frame);
3324 if (option_debug)
3325 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3326 res = 0;
3329 ast_channel_unlock(clone);
3330 ast_channel_unlock(original);
3332 return res;
3335 void ast_change_name(struct ast_channel *chan, char *newname)
3337 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3338 ast_string_field_set(chan, name, newname);
3341 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3343 struct ast_var_t *current, *newvar;
3344 const char *varname;
3346 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3347 int vartype = 0;
3349 varname = ast_var_full_name(current);
3350 if (!varname)
3351 continue;
3353 if (varname[0] == '_') {
3354 vartype = 1;
3355 if (varname[1] == '_')
3356 vartype = 2;
3359 switch (vartype) {
3360 case 1:
3361 newvar = ast_var_assign(&varname[1], ast_var_value(current));
3362 if (newvar) {
3363 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3364 if (option_debug)
3365 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3367 break;
3368 case 2:
3369 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
3370 if (newvar) {
3371 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3372 if (option_debug)
3373 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3375 break;
3376 default:
3377 if (option_debug)
3378 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
3379 break;
3385 \brief Clone channel variables from 'clone' channel into 'original' channel
3387 All variables except those related to app_groupcount are cloned.
3388 Variables are actually _removed_ from 'clone' channel, presumably
3389 because it will subsequently be destroyed.
3391 \note Assumes locks will be in place on both channels when called.
3393 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3395 struct ast_var_t *current, *newvar;
3396 /* Append variables from clone channel into original channel */
3397 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3398 if (AST_LIST_FIRST(&clone->varshead))
3399 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3401 /* then, dup the varshead list into the clone */
3403 AST_LIST_TRAVERSE(&original->varshead, current, entries) {
3404 newvar = ast_var_assign(current->name, current->value);
3405 if (newvar)
3406 AST_LIST_INSERT_TAIL(&clone->varshead, newvar, entries);
3411 \brief Masquerade a channel
3413 \note Assumes channel will be locked when called
3415 int ast_do_masquerade(struct ast_channel *original)
3417 int x,i;
3418 int res=0;
3419 int origstate;
3420 struct ast_frame *cur;
3421 const struct ast_channel_tech *t;
3422 void *t_pvt;
3423 struct ast_callerid tmpcid;
3424 struct ast_channel *clone = original->masq;
3425 struct ast_cdr *cdr;
3426 int rformat = original->readformat;
3427 int wformat = original->writeformat;
3428 char newn[100];
3429 char orig[100];
3430 char masqn[100];
3431 char zombn[100];
3433 if (option_debug > 3)
3434 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3435 clone->name, clone->_state, original->name, original->_state);
3437 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3438 the clone channel into the original channel. Start by killing off the original
3439 channel's backend. I'm not sure we're going to keep this function, because
3440 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3442 /* We need the clone's lock, too */
3443 ast_channel_lock(clone);
3445 if (option_debug > 1)
3446 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3448 /* Having remembered the original read/write formats, we turn off any translation on either
3449 one */
3450 free_translation(clone);
3451 free_translation(original);
3454 /* Unlink the masquerade */
3455 original->masq = NULL;
3456 clone->masqr = NULL;
3458 /* Save the original name */
3459 ast_copy_string(orig, original->name, sizeof(orig));
3460 /* Save the new name */
3461 ast_copy_string(newn, clone->name, sizeof(newn));
3462 /* Create the masq name */
3463 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3465 /* Copy the name from the clone channel */
3466 ast_string_field_set(original, name, newn);
3468 /* Mangle the name of the clone channel */
3469 ast_string_field_set(clone, name, masqn);
3471 /* Notify any managers of the change, first the masq then the other */
3472 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3473 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3475 /* Swap the technologies */
3476 t = original->tech;
3477 original->tech = clone->tech;
3478 clone->tech = t;
3480 /* Swap the cdrs */
3481 cdr = original->cdr;
3482 original->cdr = clone->cdr;
3483 clone->cdr = cdr;
3485 t_pvt = original->tech_pvt;
3486 original->tech_pvt = clone->tech_pvt;
3487 clone->tech_pvt = t_pvt;
3489 /* Swap the alertpipes */
3490 for (i = 0; i < 2; i++) {
3491 x = original->alertpipe[i];
3492 original->alertpipe[i] = clone->alertpipe[i];
3493 clone->alertpipe[i] = x;
3497 * Swap the readq's. The end result should be this:
3499 * 1) All frames should be on the new (original) channel.
3500 * 2) Any frames that were already on the new channel before this
3501 * masquerade need to be at the end of the readq, after all of the
3502 * frames on the old (clone) channel.
3503 * 3) The alertpipe needs to get poked for every frame that was already
3504 * on the new channel, since we are now using the alert pipe from the
3505 * old (clone) channel.
3508 AST_LIST_HEAD_NOLOCK(, ast_frame) tmp_readq;
3509 AST_LIST_HEAD_SET_NOLOCK(&tmp_readq, NULL);
3511 AST_LIST_APPEND_LIST(&tmp_readq, &original->readq, frame_list);
3512 AST_LIST_APPEND_LIST(&original->readq, &clone->readq, frame_list);
3514 while ((cur = AST_LIST_REMOVE_HEAD(&tmp_readq, frame_list))) {
3515 AST_LIST_INSERT_TAIL(&original->readq, cur, frame_list);
3516 if (original->alertpipe[1] > -1) {
3517 int poke = 0;
3518 write(original->alertpipe[1], &poke, sizeof(poke));
3523 /* Swap the raw formats */
3524 x = original->rawreadformat;
3525 original->rawreadformat = clone->rawreadformat;
3526 clone->rawreadformat = x;
3527 x = original->rawwriteformat;
3528 original->rawwriteformat = clone->rawwriteformat;
3529 clone->rawwriteformat = x;
3531 clone->_softhangup = AST_SOFTHANGUP_DEV;
3533 /* And of course, so does our current state. Note we need not
3534 call ast_setstate since the event manager doesn't really consider
3535 these separate. We do this early so that the clone has the proper
3536 state of the original channel. */
3537 origstate = original->_state;
3538 original->_state = clone->_state;
3539 clone->_state = origstate;
3541 if (clone->tech->fixup){
3542 res = clone->tech->fixup(original, clone);
3543 if (res)
3544 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3547 /* Start by disconnecting the original's physical side */
3548 if (clone->tech->hangup)
3549 res = clone->tech->hangup(clone);
3550 if (res) {
3551 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
3552 ast_channel_unlock(clone);
3553 return -1;
3556 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3557 /* Mangle the name of the clone channel */
3558 ast_string_field_set(clone, name, zombn);
3559 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3561 /* Update the type. */
3562 t_pvt = original->monitor;
3563 original->monitor = clone->monitor;
3564 clone->monitor = t_pvt;
3566 /* Keep the same language. */
3567 ast_string_field_set(original, language, clone->language);
3568 /* Copy the FD's other than the generator fd */
3569 for (x = 0; x < AST_MAX_FDS; x++) {
3570 if (x != AST_GENERATOR_FD)
3571 original->fds[x] = clone->fds[x];
3574 ast_app_group_update(clone, original);
3575 /* Move data stores over */
3576 if (AST_LIST_FIRST(&clone->datastores)) {
3577 struct ast_datastore *ds;
3578 AST_LIST_APPEND_LIST(&original->datastores, &clone->datastores, entry);
3579 AST_LIST_TRAVERSE(&original->datastores, ds, entry) {
3580 if (ds->info->chan_fixup)
3581 ds->info->chan_fixup(ds->data, clone, original);
3585 clone_variables(original, clone);
3586 /* Presense of ADSI capable CPE follows clone */
3587 original->adsicpe = clone->adsicpe;
3588 /* Bridge remains the same */
3589 /* CDR fields remain the same */
3590 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3591 /* Application and data remain the same */
3592 /* Clone exception becomes real one, as with fdno */
3593 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3594 original->fdno = clone->fdno;
3595 /* Schedule context remains the same */
3596 /* Stream stuff stays the same */
3597 /* Keep the original state. The fixup code will need to work with it most likely */
3599 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3600 out. */
3601 tmpcid = original->cid;
3602 original->cid = clone->cid;
3603 clone->cid = tmpcid;
3605 /* Restore original timing file descriptor */
3606 original->fds[AST_TIMING_FD] = original->timingfd;
3608 /* Our native formats are different now */
3609 original->nativeformats = clone->nativeformats;
3611 /* Context, extension, priority, app data, jump table, remain the same */
3612 /* pvt switches. pbx stays the same, as does next */
3614 /* Set the write format */
3615 ast_set_write_format(original, wformat);
3617 /* Set the read format */
3618 ast_set_read_format(original, rformat);
3620 /* Copy the music class */
3621 ast_string_field_set(original, musicclass, clone->musicclass);
3623 if (option_debug)
3624 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3626 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3627 can fix up everything as best as possible */
3628 if (original->tech->fixup) {
3629 res = original->tech->fixup(clone, original);
3630 if (res) {
3631 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3632 original->tech->type, original->name);
3633 ast_channel_unlock(clone);
3634 return -1;
3636 } else
3637 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3638 original->tech->type, original->name);
3640 /* If an indication is currently playing maintain it on the channel that is taking the place of original */
3641 if (original->visible_indication)
3642 ast_indicate(original, original->visible_indication);
3644 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3645 a zombie so nothing tries to touch it. If it's already been marked as a
3646 zombie, then free it now (since it already is considered invalid). */
3647 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3648 if (option_debug)
3649 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3650 ast_channel_unlock(clone);
3651 manager_event(EVENT_FLAG_CALL, "Hangup",
3652 "Channel: %s\r\n"
3653 "Uniqueid: %s\r\n"
3654 "Cause: %d\r\n"
3655 "Cause-txt: %s\r\n",
3656 clone->name,
3657 clone->uniqueid,
3658 clone->hangupcause,
3659 ast_cause2str(clone->hangupcause)
3661 ast_channel_free(clone);
3662 } else {
3663 if (option_debug)
3664 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3665 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3666 ast_queue_frame(clone, &ast_null_frame);
3667 ast_channel_unlock(clone);
3670 /* Signal any blocker */
3671 if (ast_test_flag(original, AST_FLAG_BLOCKING))
3672 pthread_kill(original->blocker, SIGURG);
3673 if (option_debug)
3674 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3675 return 0;
3678 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3680 ast_channel_lock(chan);
3682 if (callerid) {
3683 if (chan->cid.cid_num)
3684 free(chan->cid.cid_num);
3685 chan->cid.cid_num = ast_strdup(callerid);
3687 if (calleridname) {
3688 if (chan->cid.cid_name)
3689 free(chan->cid.cid_name);
3690 chan->cid.cid_name = ast_strdup(calleridname);
3692 if (ani) {
3693 if (chan->cid.cid_ani)
3694 free(chan->cid.cid_ani);
3695 chan->cid.cid_ani = ast_strdup(ani);
3697 manager_event(EVENT_FLAG_CALL, "Newcallerid",
3698 "Channel: %s\r\n"
3699 "CallerID: %s\r\n"
3700 "CallerIDName: %s\r\n"
3701 "Uniqueid: %s\r\n"
3702 "CID-CallingPres: %d (%s)\r\n",
3703 chan->name,
3704 S_OR(chan->cid.cid_num, "<Unknown>"),
3705 S_OR(chan->cid.cid_name, "<Unknown>"),
3706 chan->uniqueid,
3707 chan->cid.cid_pres,
3708 ast_describe_caller_presentation(chan->cid.cid_pres)
3711 ast_channel_unlock(chan);
3714 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
3716 char name[AST_CHANNEL_NAME], *dashptr;
3717 int oldstate = chan->_state;
3719 if (oldstate == state)
3720 return 0;
3722 ast_copy_string(name, chan->name, sizeof(name));
3723 if ((dashptr = strrchr(name, '-'))) {
3724 *dashptr = '\0';
3727 chan->_state = state;
3728 ast_device_state_changed_literal(name);
3729 /* setstate used to conditionally report Newchannel; this is no more */
3730 manager_event(EVENT_FLAG_CALL,
3731 "Newstate",
3732 "Channel: %s\r\n"
3733 "State: %s\r\n"
3734 "CallerID: %s\r\n"
3735 "CallerIDName: %s\r\n"
3736 "Uniqueid: %s\r\n",
3737 chan->name, ast_state2str(chan->_state),
3738 S_OR(chan->cid.cid_num, "<unknown>"),
3739 S_OR(chan->cid.cid_name, "<unknown>"),
3740 chan->uniqueid);
3742 return 0;
3745 /*! \brief Find bridged channel */
3746 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3748 struct ast_channel *bridged;
3749 bridged = chan->_bridge;
3750 if (bridged && bridged->tech->bridged_channel)
3751 bridged = bridged->tech->bridged_channel(chan, bridged);
3752 return bridged;
3755 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3757 int min = 0, sec = 0, check;
3759 check = ast_autoservice_start(peer);
3760 if (check)
3761 return;
3763 if (remain > 0) {
3764 if (remain / 60 > 1) {
3765 min = remain / 60;
3766 sec = remain % 60;
3767 } else {
3768 sec = remain;
3772 if (!strcmp(sound,"timeleft")) { /* Queue support */
3773 ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
3774 if (min) {
3775 ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
3776 ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
3778 if (sec) {
3779 ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
3780 ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
3782 } else {
3783 ast_stream_and_wait(chan, sound, chan->language, "");
3786 ast_autoservice_stop(peer);
3789 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3790 struct ast_bridge_config *config, struct ast_frame **fo,
3791 struct ast_channel **rc, struct timeval bridge_end)
3793 /* Copy voice back and forth between the two channels. */
3794 struct ast_channel *cs[3];
3795 struct ast_frame *f;
3796 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3797 int o0nativeformats;
3798 int o1nativeformats;
3799 int watch_c0_dtmf;
3800 int watch_c1_dtmf;
3801 void *pvt0, *pvt1;
3802 /* Indicates whether a frame was queued into a jitterbuffer */
3803 int frame_put_in_jb = 0;
3804 int jb_in_use;
3805 int to;
3807 cs[0] = c0;
3808 cs[1] = c1;
3809 pvt0 = c0->tech_pvt;
3810 pvt1 = c1->tech_pvt;
3811 o0nativeformats = c0->nativeformats;
3812 o1nativeformats = c1->nativeformats;
3813 watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3814 watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3816 /* Check the need of a jitterbuffer for each channel */
3817 jb_in_use = ast_jb_do_usecheck(c0, c1);
3818 if (jb_in_use)
3819 ast_jb_empty_and_reset(c0, c1);
3821 for (;;) {
3822 struct ast_channel *who, *other;
3824 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3825 (o0nativeformats != c0->nativeformats) ||
3826 (o1nativeformats != c1->nativeformats)) {
3827 /* Check for Masquerade, codec changes, etc */
3828 res = AST_BRIDGE_RETRY;
3829 break;
3831 if (bridge_end.tv_sec) {
3832 to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3833 if (to <= 0) {
3834 if (config->timelimit)
3835 res = AST_BRIDGE_RETRY;
3836 else
3837 res = AST_BRIDGE_COMPLETE;
3838 break;
3840 } else
3841 to = -1;
3842 /* Calculate the appropriate max sleep interval - in general, this is the time,
3843 left to the closest jb delivery moment */
3844 if (jb_in_use)
3845 to = ast_jb_get_when_to_wakeup(c0, c1, to);
3846 who = ast_waitfor_n(cs, 2, &to);
3847 if (!who) {
3848 /* No frame received within the specified timeout - check if we have to deliver now */
3849 if (jb_in_use)
3850 ast_jb_get_and_deliver(c0, c1);
3851 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3852 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3853 c0->_softhangup = 0;
3854 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3855 c1->_softhangup = 0;
3856 c0->_bridge = c1;
3857 c1->_bridge = c0;
3859 continue;
3861 f = ast_read(who);
3862 if (!f) {
3863 *fo = NULL;
3864 *rc = who;
3865 if (option_debug)
3866 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3867 break;
3870 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3871 /* Try add the frame info the who's bridged channel jitterbuff */
3872 if (jb_in_use)
3873 frame_put_in_jb = !ast_jb_put(other, f);
3875 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3876 int bridge_exit = 0;
3878 switch (f->subclass) {
3879 case AST_CONTROL_HOLD:
3880 case AST_CONTROL_UNHOLD:
3881 case AST_CONTROL_VIDUPDATE:
3882 case AST_CONTROL_SRCUPDATE:
3883 ast_indicate_data(other, f->subclass, f->data, f->datalen);
3884 if (jb_in_use) {
3885 ast_jb_empty_and_reset(c0, c1);
3887 break;
3888 default:
3889 *fo = f;
3890 *rc = who;
3891 bridge_exit = 1;
3892 if (option_debug)
3893 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3894 break;
3896 if (bridge_exit)
3897 break;
3899 if ((f->frametype == AST_FRAME_VOICE) ||
3900 (f->frametype == AST_FRAME_DTMF_BEGIN) ||
3901 (f->frametype == AST_FRAME_DTMF) ||
3902 (f->frametype == AST_FRAME_VIDEO) ||
3903 (f->frametype == AST_FRAME_IMAGE) ||
3904 (f->frametype == AST_FRAME_HTML) ||
3905 (f->frametype == AST_FRAME_MODEM) ||
3906 (f->frametype == AST_FRAME_TEXT)) {
3907 /* monitored dtmf causes exit from bridge */
3908 int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
3910 if (monitored_source &&
3911 (f->frametype == AST_FRAME_DTMF_END ||
3912 f->frametype == AST_FRAME_DTMF_BEGIN)) {
3913 *fo = f;
3914 *rc = who;
3915 if (option_debug)
3916 ast_log(LOG_DEBUG, "Got DTMF %s on channel (%s)\n",
3917 f->frametype == AST_FRAME_DTMF_END ? "end" : "begin",
3918 who->name);
3919 break;
3921 /* Write immediately frames, not passed through jb */
3922 if (!frame_put_in_jb)
3923 ast_write(other, f);
3925 /* Check if we have to deliver now */
3926 if (jb_in_use)
3927 ast_jb_get_and_deliver(c0, c1);
3929 /* XXX do we want to pass on also frames not matched above ? */
3930 ast_frfree(f);
3932 /* Swap who gets priority */
3933 cs[2] = cs[0];
3934 cs[0] = cs[1];
3935 cs[1] = cs[2];
3937 return res;
3940 /*! \brief Bridge two channels together */
3941 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3942 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
3944 struct ast_channel *who = NULL;
3945 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3946 int nativefailed=0;
3947 int firstpass;
3948 int o0nativeformats;
3949 int o1nativeformats;
3950 long time_left_ms=0;
3951 struct timeval nexteventts = { 0, };
3952 char caller_warning = 0;
3953 char callee_warning = 0;
3955 if (c0->_bridge) {
3956 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3957 c0->name, c0->_bridge->name);
3958 return -1;
3960 if (c1->_bridge) {
3961 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3962 c1->name, c1->_bridge->name);
3963 return -1;
3966 /* Stop if we're a zombie or need a soft hangup */
3967 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3968 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3969 return -1;
3971 *fo = NULL;
3972 firstpass = config->firstpass;
3973 config->firstpass = 0;
3975 if (ast_tvzero(config->start_time))
3976 config->start_time = ast_tvnow();
3977 time_left_ms = config->timelimit;
3979 caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3980 callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3982 if (config->start_sound && firstpass) {
3983 if (caller_warning)
3984 bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3985 if (callee_warning)
3986 bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3989 /* Keep track of bridge */
3990 c0->_bridge = c1;
3991 c1->_bridge = c0;
3993 /* \todo XXX here should check that cid_num is not NULL */
3994 manager_event(EVENT_FLAG_CALL, "Link",
3995 "Channel1: %s\r\n"
3996 "Channel2: %s\r\n"
3997 "Uniqueid1: %s\r\n"
3998 "Uniqueid2: %s\r\n"
3999 "CallerID1: %s\r\n"
4000 "CallerID2: %s\r\n",
4001 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4003 o0nativeformats = c0->nativeformats;
4004 o1nativeformats = c1->nativeformats;
4006 if (config->feature_timer) {
4007 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->feature_timer, 1000));
4008 } else if (config->timelimit) {
4009 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
4010 if (caller_warning || callee_warning)
4011 nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
4014 if (!c0->tech->send_digit_begin)
4015 ast_set_flag(c1, AST_FLAG_END_DTMF_ONLY);
4016 if (!c1->tech->send_digit_begin)
4017 ast_set_flag(c0, AST_FLAG_END_DTMF_ONLY);
4019 /* Before we enter in and bridge these two together tell them both the source of audio has changed */
4020 ast_indicate(c0, AST_CONTROL_SRCUPDATE);
4021 ast_indicate(c1, AST_CONTROL_SRCUPDATE);
4023 for (/* ever */;;) {
4024 struct timeval now = { 0, };
4025 int to;
4027 to = -1;
4029 if (!ast_tvzero(nexteventts)) {
4030 now = ast_tvnow();
4031 to = ast_tvdiff_ms(nexteventts, now);
4032 if (to <= 0) {
4033 if (!config->timelimit) {
4034 res = AST_BRIDGE_COMPLETE;
4035 break;
4037 to = 0;
4041 if (config->timelimit) {
4042 time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
4043 if (time_left_ms < to)
4044 to = time_left_ms;
4046 if (time_left_ms <= 0) {
4047 if (caller_warning && config->end_sound)
4048 bridge_playfile(c0, c1, config->end_sound, 0);
4049 if (callee_warning && config->end_sound)
4050 bridge_playfile(c1, c0, config->end_sound, 0);
4051 *fo = NULL;
4052 if (who)
4053 *rc = who;
4054 res = 0;
4055 break;
4058 if (!to) {
4059 if (time_left_ms >= 5000 && config->warning_sound && config->play_warning) {
4060 int t = (time_left_ms + 500) / 1000; /* round to nearest second */
4061 if (caller_warning)
4062 bridge_playfile(c0, c1, config->warning_sound, t);
4063 if (callee_warning)
4064 bridge_playfile(c1, c0, config->warning_sound, t);
4066 if (config->warning_freq && (time_left_ms > (config->warning_freq + 5000)))
4067 nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
4068 else
4069 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
4073 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
4074 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4075 c0->_softhangup = 0;
4076 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4077 c1->_softhangup = 0;
4078 c0->_bridge = c1;
4079 c1->_bridge = c0;
4080 if (option_debug)
4081 ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
4082 continue;
4085 /* Stop if we're a zombie or need a soft hangup */
4086 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
4087 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
4088 *fo = NULL;
4089 if (who)
4090 *rc = who;
4091 res = 0;
4092 if (option_debug)
4093 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",
4094 c0->name, c1->name,
4095 ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
4096 ast_check_hangup(c0) ? "Yes" : "No",
4097 ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
4098 ast_check_hangup(c1) ? "Yes" : "No");
4099 break;
4102 /* See if the BRIDGEPEER variable needs to be updated */
4103 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER")))
4104 pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1->name);
4105 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER")))
4106 pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0->name);
4108 if (c0->tech->bridge &&
4109 (config->timelimit == 0) &&
4110 (c0->tech->bridge == c1->tech->bridge) &&
4111 !nativefailed && !c0->monitor && !c1->monitor &&
4112 !c0->audiohooks && !c1->audiohooks && !ast_test_flag(&(config->features_callee),AST_FEATURE_REDIRECT) &&
4113 !ast_test_flag(&(config->features_caller),AST_FEATURE_REDIRECT) &&
4114 !c0->masq && !c0->masqr && !c1->masq && !c1->masqr) {
4115 /* Looks like they share a bridge method and nothing else is in the way */
4116 ast_set_flag(c0, AST_FLAG_NBRIDGE);
4117 ast_set_flag(c1, AST_FLAG_NBRIDGE);
4118 if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, to)) == AST_BRIDGE_COMPLETE) {
4119 /* \todo XXX here should check that cid_num is not NULL */
4120 manager_event(EVENT_FLAG_CALL, "Unlink",
4121 "Channel1: %s\r\n"
4122 "Channel2: %s\r\n"
4123 "Uniqueid1: %s\r\n"
4124 "Uniqueid2: %s\r\n"
4125 "CallerID1: %s\r\n"
4126 "CallerID2: %s\r\n",
4127 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4128 if (option_debug)
4129 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
4131 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
4132 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
4134 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4135 continue;
4137 c0->_bridge = NULL;
4138 c1->_bridge = NULL;
4140 return res;
4141 } else {
4142 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
4143 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
4145 switch (res) {
4146 case AST_BRIDGE_RETRY:
4147 continue;
4148 default:
4149 if (option_verbose > 2)
4150 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s ended\n",
4151 c0->name, c1->name);
4152 /* fallthrough */
4153 case AST_BRIDGE_FAILED_NOWARN:
4154 nativefailed++;
4155 break;
4159 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
4160 (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
4161 !(c0->generator || c1->generator)) {
4162 if (ast_channel_make_compatible(c0, c1)) {
4163 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
4164 /* \todo XXX here should check that cid_num is not NULL */
4165 manager_event(EVENT_FLAG_CALL, "Unlink",
4166 "Channel1: %s\r\n"
4167 "Channel2: %s\r\n"
4168 "Uniqueid1: %s\r\n"
4169 "Uniqueid2: %s\r\n"
4170 "CallerID1: %s\r\n"
4171 "CallerID2: %s\r\n",
4172 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4173 return AST_BRIDGE_FAILED;
4175 o0nativeformats = c0->nativeformats;
4176 o1nativeformats = c1->nativeformats;
4179 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER")))
4180 pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1->name);
4181 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER")))
4182 pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0->name);
4184 res = ast_generic_bridge(c0, c1, config, fo, rc, nexteventts);
4185 if (res != AST_BRIDGE_RETRY)
4186 break;
4189 ast_clear_flag(c0, AST_FLAG_END_DTMF_ONLY);
4190 ast_clear_flag(c1, AST_FLAG_END_DTMF_ONLY);
4192 /* Now that we have broken the bridge the source will change yet again */
4193 ast_indicate(c0, AST_CONTROL_SRCUPDATE);
4194 ast_indicate(c1, AST_CONTROL_SRCUPDATE);
4196 c0->_bridge = NULL;
4197 c1->_bridge = NULL;
4199 /* \todo XXX here should check that cid_num is not NULL */
4200 manager_event(EVENT_FLAG_CALL, "Unlink",
4201 "Channel1: %s\r\n"
4202 "Channel2: %s\r\n"
4203 "Uniqueid1: %s\r\n"
4204 "Uniqueid2: %s\r\n"
4205 "CallerID1: %s\r\n"
4206 "CallerID2: %s\r\n",
4207 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4208 if (option_debug)
4209 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
4211 return res;
4214 /*! \brief Sets an option on a channel */
4215 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
4217 int res;
4219 if (chan->tech->setoption) {
4220 res = chan->tech->setoption(chan, option, data, datalen);
4221 if (res < 0)
4222 return res;
4223 } else {
4224 errno = ENOSYS;
4225 return -1;
4227 if (block) {
4228 /* XXX Implement blocking -- just wait for our option frame reply, discarding
4229 intermediate packets. XXX */
4230 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
4231 return -1;
4233 return 0;
4236 struct tonepair_def {
4237 int freq1;
4238 int freq2;
4239 int duration;
4240 int vol;
4243 struct tonepair_state {
4244 int fac1;
4245 int fac2;
4246 int v1_1;
4247 int v2_1;
4248 int v3_1;
4249 int v1_2;
4250 int v2_2;
4251 int v3_2;
4252 int origwfmt;
4253 int pos;
4254 int duration;
4255 int modulate;
4256 struct ast_frame f;
4257 unsigned char offset[AST_FRIENDLY_OFFSET];
4258 short data[4000];
4261 static void tonepair_release(struct ast_channel *chan, void *params)
4263 struct tonepair_state *ts = params;
4265 if (chan)
4266 ast_set_write_format(chan, ts->origwfmt);
4267 free(ts);
4270 static void *tonepair_alloc(struct ast_channel *chan, void *params)
4272 struct tonepair_state *ts;
4273 struct tonepair_def *td = params;
4275 if (!(ts = ast_calloc(1, sizeof(*ts))))
4276 return NULL;
4277 ts->origwfmt = chan->writeformat;
4278 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
4279 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
4280 tonepair_release(NULL, ts);
4281 ts = NULL;
4282 } else {
4283 ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
4284 ts->v1_1 = 0;
4285 ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4286 ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4287 ts->v2_1 = 0;
4288 ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
4289 ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4290 ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4291 ts->duration = td->duration;
4292 ts->modulate = 0;
4294 /* Let interrupts interrupt :) */
4295 ast_set_flag(chan, AST_FLAG_WRITE_INT);
4296 return ts;
4299 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
4301 struct tonepair_state *ts = data;
4302 int x;
4304 /* we need to prepare a frame with 16 * timelen samples as we're
4305 * generating SLIN audio
4307 len = samples * 2;
4309 if (len > sizeof(ts->data) / 2 - 1) {
4310 ast_log(LOG_WARNING, "Can't generate that much data!\n");
4311 return -1;
4313 memset(&ts->f, 0, sizeof(ts->f));
4314 for (x=0;x<len/2;x++) {
4315 ts->v1_1 = ts->v2_1;
4316 ts->v2_1 = ts->v3_1;
4317 ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;
4319 ts->v1_2 = ts->v2_2;
4320 ts->v2_2 = ts->v3_2;
4321 ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
4322 if (ts->modulate) {
4323 int p;
4324 p = ts->v3_2 - 32768;
4325 if (p < 0) p = -p;
4326 p = ((p * 9) / 10) + 1;
4327 ts->data[x] = (ts->v3_1 * p) >> 15;
4328 } else
4329 ts->data[x] = ts->v3_1 + ts->v3_2;
4331 ts->f.frametype = AST_FRAME_VOICE;
4332 ts->f.subclass = AST_FORMAT_SLINEAR;
4333 ts->f.datalen = len;
4334 ts->f.samples = samples;
4335 ts->f.offset = AST_FRIENDLY_OFFSET;
4336 ts->f.data = ts->data;
4337 ast_write(chan, &ts->f);
4338 ts->pos += x;
4339 if (ts->duration > 0) {
4340 if (ts->pos >= ts->duration * 8)
4341 return -1;
4343 return 0;
4346 static struct ast_generator tonepair = {
4347 alloc: tonepair_alloc,
4348 release: tonepair_release,
4349 generate: tonepair_generator,
4352 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4354 struct tonepair_def d = { 0, };
4356 d.freq1 = freq1;
4357 d.freq2 = freq2;
4358 d.duration = duration;
4359 d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
4360 if (ast_activate_generator(chan, &tonepair, &d))
4361 return -1;
4362 return 0;
4365 void ast_tonepair_stop(struct ast_channel *chan)
4367 ast_deactivate_generator(chan);
4370 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4372 int res;
4374 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
4375 return res;
4377 /* Give us some wiggle room */
4378 while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
4379 struct ast_frame *f = ast_read(chan);
4380 if (f)
4381 ast_frfree(f);
4382 else
4383 return -1;
4385 return 0;
4388 ast_group_t ast_get_group(const char *s)
4390 char *piece;
4391 char *c;
4392 int start=0, finish=0, x;
4393 ast_group_t group = 0;
4395 if (ast_strlen_zero(s))
4396 return 0;
4398 c = ast_strdupa(s);
4400 while ((piece = strsep(&c, ","))) {
4401 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
4402 /* Range */
4403 } else if (sscanf(piece, "%d", &start)) {
4404 /* Just one */
4405 finish = start;
4406 } else {
4407 ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
4408 continue;
4410 for (x = start; x <= finish; x++) {
4411 if ((x > 63) || (x < 0)) {
4412 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
4413 } else
4414 group |= ((ast_group_t) 1 << x);
4417 return group;
4420 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
4421 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
4422 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
4424 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
4425 void (*stop_ptr)(struct ast_channel *),
4426 void (*cleanup_ptr)(struct ast_channel *))
4428 ast_moh_start_ptr = start_ptr;
4429 ast_moh_stop_ptr = stop_ptr;
4430 ast_moh_cleanup_ptr = cleanup_ptr;
4433 void ast_uninstall_music_functions(void)
4435 ast_moh_start_ptr = NULL;
4436 ast_moh_stop_ptr = NULL;
4437 ast_moh_cleanup_ptr = NULL;
4440 /*! \brief Turn on music on hold on a given channel */
4441 int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
4443 if (ast_moh_start_ptr)
4444 return ast_moh_start_ptr(chan, mclass, interpclass);
4446 if (option_verbose > 2) {
4447 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n",
4448 mclass ? mclass : (interpclass ? interpclass : "default"));
4451 return 0;
4454 /*! \brief Turn off music on hold on a given channel */
4455 void ast_moh_stop(struct ast_channel *chan)
4457 if (ast_moh_stop_ptr)
4458 ast_moh_stop_ptr(chan);
4461 void ast_moh_cleanup(struct ast_channel *chan)
4463 if (ast_moh_cleanup_ptr)
4464 ast_moh_cleanup_ptr(chan);
4467 void ast_channels_init(void)
4469 ast_cli_register_multiple(cli_channel, sizeof(cli_channel) / sizeof(struct ast_cli_entry));
4472 /*! \brief Print call group and pickup group ---*/
4473 char *ast_print_group(char *buf, int buflen, ast_group_t group)
4475 unsigned int i;
4476 int first=1;
4477 char num[3];
4479 buf[0] = '\0';
4481 if (!group) /* Return empty string if no group */
4482 return buf;
4484 for (i = 0; i <= 63; i++) { /* Max group is 63 */
4485 if (group & ((ast_group_t) 1 << i)) {
4486 if (!first) {
4487 strncat(buf, ", ", buflen - strlen(buf) - 1);
4488 } else {
4489 first=0;
4491 snprintf(num, sizeof(num), "%u", i);
4492 strncat(buf, num, buflen - strlen(buf) - 1);
4495 return buf;
4498 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
4500 struct ast_variable *cur;
4502 for (cur = vars; cur; cur = cur->next)
4503 pbx_builtin_setvar_helper(chan, cur->name, cur->value);
4506 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
4508 /* just store the data pointer in the channel structure */
4509 return data;
4512 static void silence_generator_release(struct ast_channel *chan, void *data)
4514 /* nothing to do */
4517 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
4519 short buf[samples];
4520 struct ast_frame frame = {
4521 .frametype = AST_FRAME_VOICE,
4522 .subclass = AST_FORMAT_SLINEAR,
4523 .data = buf,
4524 .samples = samples,
4525 .datalen = sizeof(buf),
4527 memset(buf, 0, sizeof(buf));
4528 if (ast_write(chan, &frame))
4529 return -1;
4530 return 0;
4533 static struct ast_generator silence_generator = {
4534 .alloc = silence_generator_alloc,
4535 .release = silence_generator_release,
4536 .generate = silence_generator_generate,
4539 struct ast_silence_generator {
4540 int old_write_format;
4543 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
4545 struct ast_silence_generator *state;
4547 if (!(state = ast_calloc(1, sizeof(*state)))) {
4548 return NULL;
4551 state->old_write_format = chan->writeformat;
4553 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
4554 ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
4555 free(state);
4556 return NULL;
4559 ast_activate_generator(chan, &silence_generator, state);
4561 if (option_debug)
4562 ast_log(LOG_DEBUG, "Started silence generator on '%s'\n", chan->name);
4564 return state;
4567 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
4569 if (!state)
4570 return;
4572 ast_deactivate_generator(chan);
4574 if (option_debug)
4575 ast_log(LOG_DEBUG, "Stopped silence generator on '%s'\n", chan->name);
4577 if (ast_set_write_format(chan, state->old_write_format) < 0)
4578 ast_log(LOG_ERROR, "Could not return write format to its original state\n");
4580 free(state);
4584 int ast_send_message(const char *type, void *data, char *to, char *from, char *message, int ispdu) {
4585 struct ast_channel *chan = NULL;
4586 int status;
4587 int res = -1;
4589 chan = ast_request(type, AST_FORMAT_SLINEAR, data, &status);
4590 if (chan) {
4591 if (from) {
4592 ast_set_callerid(chan, from, from, from);
4594 res = ast_sendmessage(chan, to, message, ispdu);
4595 /* XXX what about message CDRs ??? XXX */
4596 ast_hangup(chan);
4597 return res;
4600 return res;
4603 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
4604 const char *channelreloadreason2txt(enum channelreloadreason reason)
4606 switch (reason) {
4607 case CHANNEL_MODULE_LOAD:
4608 return "LOAD (Channel module load)";
4610 case CHANNEL_MODULE_RELOAD:
4611 return "RELOAD (Channel module reload)";
4613 case CHANNEL_CLI_RELOAD:
4614 return "CLIRELOAD (Channel module reload by CLI command)";
4616 default:
4617 return "MANAGERRELOAD (Channel module reload by manager)";
4621 #ifdef DEBUG_CHANNEL_LOCKS
4623 /*! \brief Unlock AST channel (and print debugging output)
4624 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
4626 int __ast_channel_unlock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
4628 int res = 0;
4629 if (option_debug > 2)
4630 ast_log(LOG_DEBUG, "::::==== Unlocking AST channel %s\n", chan->name);
4632 if (!chan) {
4633 if (option_debug)
4634 ast_log(LOG_DEBUG, "::::==== Unlocking non-existing channel \n");
4635 return 0;
4637 #ifdef DEBUG_THREADS
4638 res = __ast_pthread_mutex_unlock(filename, lineno, func, "(channel lock)", &chan->lock);
4639 #else
4640 res = ast_mutex_unlock(&chan->lock);
4641 #endif
4643 if (option_debug > 2) {
4644 #ifdef DEBUG_THREADS
4645 int count = 0;
4646 if ((count = chan->lock.reentrancy))
4647 ast_log(LOG_DEBUG, ":::=== Still have %d locks (recursive)\n", count);
4648 #endif
4649 if (!res)
4650 if (option_debug)
4651 ast_log(LOG_DEBUG, "::::==== Channel %s was unlocked\n", chan->name);
4652 if (res == EINVAL) {
4653 if (option_debug)
4654 ast_log(LOG_DEBUG, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan->name);
4657 if (res == EPERM) {
4658 /* We had no lock, so okay any way*/
4659 if (option_debug > 3)
4660 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked at all \n", chan->name);
4661 res = 0;
4663 return res;
4666 /*! \brief Lock AST channel (and print debugging output)
4667 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4668 int __ast_channel_lock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
4670 int res;
4672 if (option_debug > 3)
4673 ast_log(LOG_DEBUG, "====:::: Locking AST channel %s\n", chan->name);
4675 #ifdef DEBUG_THREADS
4676 res = __ast_pthread_mutex_lock(filename, lineno, func, "(channel lock)", &chan->lock);
4677 #else
4678 res = ast_mutex_lock(&chan->lock);
4679 #endif
4681 if (option_debug > 3) {
4682 #ifdef DEBUG_THREADS
4683 int count = 0;
4684 if ((count = chan->lock.reentrancy))
4685 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4686 #endif
4687 if (!res)
4688 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4689 if (res == EDEADLK) {
4690 /* We had no lock, so okey any way */
4691 if (option_debug > 3)
4692 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan->name);
4694 if (res == EINVAL) {
4695 if (option_debug > 3)
4696 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4699 return res;
4702 /*! \brief Lock AST channel (and print debugging output)
4703 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4704 int __ast_channel_trylock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
4706 int res;
4708 if (option_debug > 2)
4709 ast_log(LOG_DEBUG, "====:::: Trying to lock AST channel %s\n", chan->name);
4710 #ifdef DEBUG_THREADS
4711 res = __ast_pthread_mutex_trylock(filename, lineno, func, "(channel lock)", &chan->lock);
4712 #else
4713 res = ast_mutex_trylock(&chan->lock);
4714 #endif
4716 if (option_debug > 2) {
4717 #ifdef DEBUG_THREADS
4718 int count = 0;
4719 if ((count = chan->lock.reentrancy))
4720 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4721 #endif
4722 if (!res)
4723 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4724 if (res == EBUSY) {
4725 /* We failed to lock */
4726 if (option_debug > 2)
4727 ast_log(LOG_DEBUG, "::::==== Channel %s failed to lock. Not waiting around...\n", chan->name);
4729 if (res == EDEADLK) {
4730 /* We had no lock, so okey any way*/
4731 if (option_debug > 2)
4732 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan->name);
4734 if (res == EINVAL && option_debug > 2)
4735 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4737 return res;
4740 #endif
4743 * Wrappers for various ast_say_*() functions that call the full version
4744 * of the same functions.
4745 * The proper place would be say.c, but that file is optional and one
4746 * must be able to build asterisk even without it (using a loadable 'say'
4747 * implementation that only supplies the 'full' version of the functions.
4750 int ast_say_number(struct ast_channel *chan, int num,
4751 const char *ints, const char *language, const char *options)
4753 return ast_say_number_full(chan, num, ints, language, options, -1, -1);
4756 int ast_say_enumeration(struct ast_channel *chan, int num,
4757 const char *ints, const char *language, const char *options)
4759 return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
4762 int ast_say_digits(struct ast_channel *chan, int num,
4763 const char *ints, const char *lang)
4765 return ast_say_digits_full(chan, num, ints, lang, -1, -1);
4768 int ast_say_digit_str(struct ast_channel *chan, const char *str,
4769 const char *ints, const char *lang)
4771 return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
4774 int ast_say_character_str(struct ast_channel *chan, const char *str,
4775 const char *ints, const char *lang)
4777 return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
4780 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
4781 const char *ints, const char *lang)
4783 return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
4786 int ast_say_digits_full(struct ast_channel *chan, int num,
4787 const char *ints, const char *lang, int audiofd, int ctrlfd)
4789 char buf[256];
4791 snprintf(buf, sizeof(buf), "%d", num);
4792 return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);