a whole pile of Zaptel/DAHDI compatibility work, with lots more to come... this tree...
[asterisk-bristuff.git] / main / channel.c
blob9a5d70125314080f496965f38c3fe7c3a0220ed1
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)
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 AST_LIST_LOCK(&channels);
1047 AST_LIST_TRAVERSE(&channels, c, chan_list) {
1048 prev = _prev;
1049 if (prev) { /* look for next item */
1050 if (c != prev) /* not this one */
1051 continue;
1052 /* found, prepare to return c->next */
1053 if ((c = AST_LIST_NEXT(c, chan_list)) == NULL) break;
1054 /* If prev was the last item on the channel list, then we just
1055 * want to return NULL, instead of trying to deref NULL in the
1056 * next section.
1058 prev = NULL;
1059 /* We want prev to be NULL in case we end up doing more searching through
1060 * the channel list to find the channel (ie: name searching). If we didn't
1061 * set this to NULL the logic would just blow up
1062 * XXX Need a better explanation for this ...
1065 if (name) { /* want match by name */
1066 if ((!namelen && strcasecmp(c->name, name)) ||
1067 (namelen && strncasecmp(c->name, name, namelen)))
1068 continue; /* name match failed */
1069 } else if (exten) {
1070 if (context && strcasecmp(c->context, context) &&
1071 strcasecmp(c->macrocontext, context))
1072 continue; /* context match failed */
1073 if (strcasecmp(c->exten, exten) &&
1074 strcasecmp(c->macroexten, exten))
1075 continue; /* exten match failed */
1077 /* if we get here, c points to the desired record */
1078 break;
1080 /* exit if chan not found or mutex acquired successfully */
1081 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1082 done = c == NULL || ast_channel_trylock(c) == 0;
1083 if (!done) {
1084 if (option_debug)
1085 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
1086 if (retries == 199) {
1087 /* We are about to fail due to a deadlock, so report this
1088 * while we still have the list lock.
1090 if (option_debug)
1091 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n", c, retries);
1092 /* As we have deadlocked, we will skip this channel and
1093 * see if there is another match.
1094 * NOTE: No point doing this for a full-name match,
1095 * as there can be no more matches.
1097 if (!(name && !namelen)) {
1098 prev = c;
1099 retries = -1;
1103 AST_LIST_UNLOCK(&channels);
1104 if (done)
1105 return c;
1106 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1107 * starting from the beginning of the list we can restore our saved pointer to the previous
1108 * channel and start from there.
1110 prev = _prev;
1111 usleep(1); /* give other threads a chance before retrying */
1114 return NULL;
1117 /*! \brief Browse channels in use */
1118 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1120 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1123 /*! \brief Get channel by name and lock it */
1124 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1126 return channel_find_locked(NULL, name, 0, NULL, NULL);
1129 /*! \brief Get channel by name prefix and lock it */
1130 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1132 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1135 /*! \brief Get next channel by name prefix and lock it */
1136 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1137 const int namelen)
1139 return channel_find_locked(chan, name, namelen, NULL, NULL);
1142 /*! \brief Get channel by exten (and optionally context) and lock it */
1143 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1145 return channel_find_locked(NULL, NULL, 0, context, exten);
1148 /*! \brief Get next channel by exten (and optionally context) and lock it */
1149 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1150 const char *context)
1152 return channel_find_locked(chan, NULL, 0, context, exten);
1155 /*! \brief Wait, look for hangups and condition arg */
1156 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1158 struct ast_frame *f;
1160 while (ms > 0) {
1161 if (cond && ((*cond)(data) == 0))
1162 return 0;
1163 ms = ast_waitfor(chan, ms);
1164 if (ms < 0)
1165 return -1;
1166 if (ms > 0) {
1167 f = ast_read(chan);
1168 if (!f)
1169 return -1;
1170 ast_frfree(f);
1173 return 0;
1176 /*! \brief Wait, look for hangups */
1177 int ast_safe_sleep(struct ast_channel *chan, int ms)
1179 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1182 static void free_cid(struct ast_callerid *cid)
1184 if (cid->cid_dnid)
1185 free(cid->cid_dnid);
1186 if (cid->cid_num)
1187 free(cid->cid_num);
1188 if (cid->cid_name)
1189 free(cid->cid_name);
1190 if (cid->cid_ani)
1191 free(cid->cid_ani);
1192 if (cid->cid_rdnis)
1193 free(cid->cid_rdnis);
1196 /*! \brief Free a channel structure */
1197 void ast_channel_free(struct ast_channel *chan)
1199 int fd;
1200 struct ast_var_t *vardata;
1201 struct ast_frame *f;
1202 struct varshead *headp;
1203 struct ast_datastore *datastore = NULL;
1204 char name[AST_CHANNEL_NAME];
1206 headp=&chan->varshead;
1208 AST_LIST_LOCK(&channels);
1209 if (!AST_LIST_REMOVE(&channels, chan, chan_list)) {
1210 AST_LIST_UNLOCK(&channels);
1211 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1213 /* Lock and unlock the channel just to be sure nobody has it locked still
1214 due to a reference retrieved from the channel list. */
1215 ast_channel_lock(chan);
1216 ast_channel_unlock(chan);
1218 /* Get rid of each of the data stores on the channel */
1219 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1220 /* Free the data store */
1221 ast_channel_datastore_free(datastore);
1223 /* Lock and unlock the channel just to be sure nobody has it locked still
1224 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1225 ast_channel_lock(chan);
1226 ast_channel_unlock(chan);
1228 if (chan->tech_pvt) {
1229 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1230 free(chan->tech_pvt);
1233 if (chan->sched)
1234 sched_context_destroy(chan->sched);
1236 ast_copy_string(name, chan->name, sizeof(name));
1238 /* Stop monitoring */
1239 if (chan->monitor)
1240 chan->monitor->stop( chan, 0 );
1242 /* If there is native format music-on-hold state, free it */
1243 if (chan->music_state)
1244 ast_moh_cleanup(chan);
1246 /* Free translators */
1247 if (chan->readtrans)
1248 ast_translator_free_path(chan->readtrans);
1249 if (chan->writetrans)
1250 ast_translator_free_path(chan->writetrans);
1251 if (chan->pbx)
1252 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1253 free_cid(&chan->cid);
1254 /* Close pipes if appropriate */
1255 if ((fd = chan->alertpipe[0]) > -1)
1256 close(fd);
1257 if ((fd = chan->alertpipe[1]) > -1)
1258 close(fd);
1259 if ((fd = chan->timingfd) > -1)
1260 close(fd);
1261 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1262 ast_frfree(f);
1264 /* loop over the variables list, freeing all data and deleting list items */
1265 /* no need to lock the list, as the channel is already locked */
1267 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1268 ast_var_delete(vardata);
1270 ast_app_group_discard(chan);
1272 /* Destroy the jitterbuffer */
1273 ast_jb_destroy(chan);
1275 ast_mutex_destroy(&chan->lock);
1277 ast_string_field_free_memory(chan);
1278 free(chan);
1279 AST_LIST_UNLOCK(&channels);
1281 ast_device_state_changed_literal(name);
1284 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1286 struct ast_datastore *datastore = NULL;
1288 /* Make sure we at least have type so we can identify this */
1289 if (info == NULL) {
1290 return NULL;
1293 /* Allocate memory for datastore and clear it */
1294 datastore = ast_calloc(1, sizeof(*datastore));
1295 if (datastore == NULL) {
1296 return NULL;
1299 datastore->info = info;
1301 datastore->uid = ast_strdup(uid);
1303 return datastore;
1306 int ast_channel_datastore_free(struct ast_datastore *datastore)
1308 int res = 0;
1310 /* Using the destroy function (if present) destroy the data */
1311 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1312 datastore->info->destroy(datastore->data);
1313 datastore->data = NULL;
1316 /* Free allocated UID memory */
1317 if (datastore->uid != NULL) {
1318 free(datastore->uid);
1319 datastore->uid = NULL;
1322 /* Finally free memory used by ourselves */
1323 free(datastore);
1325 return res;
1328 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1330 struct ast_datastore *datastore = NULL, *datastore2;
1332 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1333 if (datastore->inheritance > 0) {
1334 datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1335 if (datastore2) {
1336 datastore2->data = datastore->info->duplicate(datastore->data);
1337 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1338 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1342 return 0;
1345 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1347 int res = 0;
1349 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1351 return res;
1354 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1356 struct ast_datastore *datastore2 = NULL;
1357 int res = -1;
1359 /* Find our position and remove ourselves */
1360 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1361 if (datastore2 == datastore) {
1362 AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1363 res = 0;
1364 break;
1367 AST_LIST_TRAVERSE_SAFE_END
1369 return res;
1372 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1374 struct ast_datastore *datastore = NULL;
1376 if (info == NULL)
1377 return NULL;
1379 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1380 if (datastore->info == info) {
1381 if (uid != NULL && datastore->uid != NULL) {
1382 if (!strcasecmp(uid, datastore->uid)) {
1383 /* Matched by type AND uid */
1384 break;
1386 } else {
1387 /* Matched by type at least */
1388 break;
1392 AST_LIST_TRAVERSE_SAFE_END
1394 return datastore;
1397 /*! \brief Softly hangup a channel, don't lock */
1398 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1400 if (option_debug)
1401 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1402 /* Inform channel driver that we need to be hung up, if it cares */
1403 chan->_softhangup |= cause;
1404 ast_queue_frame(chan, &ast_null_frame);
1405 /* Interrupt any poll call or such */
1406 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1407 pthread_kill(chan->blocker, SIGURG);
1408 return 0;
1411 /*! \brief Softly hangup a channel, lock */
1412 int ast_softhangup(struct ast_channel *chan, int cause)
1414 int res;
1415 ast_channel_lock(chan);
1416 res = ast_softhangup_nolock(chan, cause);
1417 ast_channel_unlock(chan);
1418 return res;
1421 static void free_translation(struct ast_channel *clone)
1423 if (clone->writetrans)
1424 ast_translator_free_path(clone->writetrans);
1425 if (clone->readtrans)
1426 ast_translator_free_path(clone->readtrans);
1427 clone->writetrans = NULL;
1428 clone->readtrans = NULL;
1429 clone->rawwriteformat = clone->nativeformats;
1430 clone->rawreadformat = clone->nativeformats;
1433 /*! \brief Hangup a channel */
1434 int ast_hangup(struct ast_channel *chan)
1436 int res = 0;
1438 /* Don't actually hang up a channel that will masquerade as someone else, or
1439 if someone is going to masquerade as us */
1440 ast_channel_lock(chan);
1442 if (chan->audiohooks) {
1443 ast_audiohook_detach_list(chan->audiohooks);
1444 chan->audiohooks = NULL;
1447 ast_autoservice_stop(chan);
1449 if (chan->masq) {
1450 if (ast_do_masquerade(chan))
1451 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1454 if (chan->masq) {
1455 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1456 ast_channel_unlock(chan);
1457 return 0;
1459 /* If this channel is one which will be masqueraded into something,
1460 mark it as a zombie already, so we know to free it later */
1461 if (chan->masqr) {
1462 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1463 ast_channel_unlock(chan);
1464 return 0;
1466 free_translation(chan);
1467 /* Close audio stream */
1468 if (chan->stream) {
1469 ast_closestream(chan->stream);
1470 chan->stream = NULL;
1472 /* Close video stream */
1473 if (chan->vstream) {
1474 ast_closestream(chan->vstream);
1475 chan->vstream = NULL;
1477 if (chan->sched) {
1478 sched_context_destroy(chan->sched);
1479 chan->sched = NULL;
1482 if (chan->generatordata) /* Clear any tone stuff remaining */
1483 chan->generator->release(chan, chan->generatordata);
1484 chan->generatordata = NULL;
1485 chan->generator = NULL;
1486 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1487 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1488 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1489 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1490 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
1492 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1493 if (option_debug)
1494 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1495 if (chan->tech->hangup)
1496 res = chan->tech->hangup(chan);
1497 } else {
1498 if (option_debug)
1499 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1502 ast_channel_unlock(chan);
1503 manager_event(EVENT_FLAG_CALL, "Hangup",
1504 "Channel: %s\r\n"
1505 "Uniqueid: %s\r\n"
1506 "Cause: %d\r\n"
1507 "Cause-txt: %s\r\n",
1508 chan->name,
1509 chan->uniqueid,
1510 chan->hangupcause,
1511 ast_cause2str(chan->hangupcause)
1514 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) && !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) && chan->cdr->disposition != AST_CDR_NULL) {
1515 ast_cdr_end(chan->cdr);
1516 ast_cdr_detach(chan->cdr);
1519 ast_channel_free(chan);
1521 return res;
1524 int ast_answer(struct ast_channel *chan)
1526 int res = 0;
1527 ast_channel_lock(chan);
1528 /* You can't answer an outbound call */
1529 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1530 ast_channel_unlock(chan);
1531 return 0;
1533 /* Stop if we're a zombie or need a soft hangup */
1534 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1535 ast_channel_unlock(chan);
1536 return -1;
1538 switch(chan->_state) {
1539 case AST_STATE_RINGING:
1540 case AST_STATE_RING:
1541 if (chan->tech->answer)
1542 res = chan->tech->answer(chan);
1543 ast_setstate(chan, AST_STATE_UP);
1544 ast_cdr_answer(chan->cdr);
1545 break;
1546 case AST_STATE_UP:
1547 break;
1548 default:
1549 break;
1551 chan->visible_indication = 0;
1552 ast_channel_unlock(chan);
1553 return res;
1556 void ast_deactivate_generator(struct ast_channel *chan)
1558 ast_channel_lock(chan);
1559 if (chan->generatordata) {
1560 if (chan->generator && chan->generator->release)
1561 chan->generator->release(chan, chan->generatordata);
1562 chan->generatordata = NULL;
1563 chan->generator = NULL;
1564 chan->fds[AST_GENERATOR_FD] = -1;
1565 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1566 ast_settimeout(chan, 0, NULL, NULL);
1568 ast_channel_unlock(chan);
1571 static int generator_force(const void *data)
1573 /* Called if generator doesn't have data */
1574 void *tmp;
1575 int res;
1576 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1577 struct ast_channel *chan = (struct ast_channel *)data;
1579 ast_channel_lock(chan);
1580 tmp = chan->generatordata;
1581 chan->generatordata = NULL;
1582 if (chan->generator)
1583 generate = chan->generator->generate;
1584 ast_channel_unlock(chan);
1586 if (!tmp || !generate)
1587 return 0;
1589 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
1591 chan->generatordata = tmp;
1593 if (res) {
1594 if (option_debug)
1595 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1596 ast_deactivate_generator(chan);
1599 return 0;
1602 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1604 int res = 0;
1606 ast_channel_lock(chan);
1608 if (chan->generatordata) {
1609 if (chan->generator && chan->generator->release)
1610 chan->generator->release(chan, chan->generatordata);
1611 chan->generatordata = NULL;
1614 ast_prod(chan);
1615 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1616 res = -1;
1619 if (!res) {
1620 ast_settimeout(chan, 160, generator_force, chan);
1621 chan->generator = gen;
1624 ast_channel_unlock(chan);
1626 return res;
1629 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1630 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1632 int winner = -1;
1633 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1634 return winner;
1637 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1638 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1639 int *exception, int *outfd, int *ms)
1641 struct timeval start = { 0 , 0 };
1642 struct pollfd *pfds = NULL;
1643 int res;
1644 long rms;
1645 int x, y, max;
1646 int sz;
1647 time_t now = 0;
1648 long whentohangup = 0, diff;
1649 struct ast_channel *winner = NULL;
1650 struct fdmap {
1651 int chan;
1652 int fdno;
1653 } *fdmap = NULL;
1655 if ((sz = n * AST_MAX_FDS + nfds)) {
1656 pfds = alloca(sizeof(*pfds) * sz);
1657 fdmap = alloca(sizeof(*fdmap) * sz);
1660 if (outfd)
1661 *outfd = -99999;
1662 if (exception)
1663 *exception = 0;
1665 /* Perform any pending masquerades */
1666 for (x=0; x < n; x++) {
1667 ast_channel_lock(c[x]);
1668 if (c[x]->masq) {
1669 if (ast_do_masquerade(c[x])) {
1670 ast_log(LOG_WARNING, "Masquerade failed\n");
1671 *ms = -1;
1672 ast_channel_unlock(c[x]);
1673 return NULL;
1676 if (c[x]->whentohangup) {
1677 if (!whentohangup)
1678 time(&now);
1679 diff = c[x]->whentohangup - now;
1680 if (diff < 1) {
1681 /* Should already be hungup */
1682 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1683 ast_channel_unlock(c[x]);
1684 return c[x];
1686 if (!whentohangup || (diff < whentohangup))
1687 whentohangup = diff;
1689 ast_channel_unlock(c[x]);
1691 /* Wait full interval */
1692 rms = *ms;
1693 if (whentohangup) {
1694 rms = whentohangup * 1000; /* timeout in milliseconds */
1695 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1696 rms = *ms;
1699 * Build the pollfd array, putting the channels' fds first,
1700 * followed by individual fds. Order is important because
1701 * individual fd's must have priority over channel fds.
1703 max = 0;
1704 for (x=0; x<n; x++) {
1705 for (y=0; y<AST_MAX_FDS; y++) {
1706 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1707 fdmap[max].chan = x; /* channel x is linked to this pfds */
1708 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1710 CHECK_BLOCKING(c[x]);
1712 /* Add the individual fds */
1713 for (x=0; x<nfds; x++) {
1714 fdmap[max].chan = -1;
1715 max += ast_add_fd(&pfds[max], fds[x]);
1718 if (*ms > 0)
1719 start = ast_tvnow();
1721 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1722 do {
1723 int kbrms = rms;
1724 if (kbrms > 600000)
1725 kbrms = 600000;
1726 res = poll(pfds, max, kbrms);
1727 if (!res)
1728 rms -= kbrms;
1729 } while (!res && (rms > 0));
1730 } else {
1731 res = poll(pfds, max, rms);
1733 for (x=0; x<n; x++)
1734 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1735 if (res < 0) { /* Simulate a timeout if we were interrupted */
1736 if (errno != EINTR)
1737 *ms = -1;
1738 return NULL;
1740 if (whentohangup) { /* if we have a timeout, check who expired */
1741 time(&now);
1742 for (x=0; x<n; x++) {
1743 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1744 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1745 if (winner == NULL)
1746 winner = c[x];
1750 if (res == 0) { /* no fd ready, reset timeout and done */
1751 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1752 return winner;
1755 * Then check if any channel or fd has a pending event.
1756 * Remember to check channels first and fds last, as they
1757 * must have priority on setting 'winner'
1759 for (x = 0; x < max; x++) {
1760 res = pfds[x].revents;
1761 if (res == 0)
1762 continue;
1763 if (fdmap[x].chan >= 0) { /* this is a channel */
1764 winner = c[fdmap[x].chan]; /* override previous winners */
1765 if (res & POLLPRI)
1766 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1767 else
1768 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1769 winner->fdno = fdmap[x].fdno;
1770 } else { /* this is an fd */
1771 if (outfd)
1772 *outfd = pfds[x].fd;
1773 if (exception)
1774 *exception = (res & POLLPRI) ? -1 : 0;
1775 winner = NULL;
1778 if (*ms > 0) {
1779 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1780 if (*ms < 0)
1781 *ms = 0;
1783 return winner;
1786 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1788 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1791 int ast_waitfor(struct ast_channel *c, int ms)
1793 int oldms = ms; /* -1 if no timeout */
1795 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1796 if ((ms < 0) && (oldms < 0))
1797 ms = 0;
1798 return ms;
1801 /* XXX never to be called with ms = -1 */
1802 int ast_waitfordigit(struct ast_channel *c, int ms)
1804 return ast_waitfordigit_full(c, ms, -1, -1);
1807 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
1809 int res = -1;
1810 #ifdef HAVE_DAHDI
1811 if (c->timingfd > -1) {
1812 if (!func) {
1813 samples = 0;
1814 data = 0;
1816 if (option_debug)
1817 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1818 res = ioctl(c->timingfd, DAHDI_TIMERCONFIG, &samples);
1819 c->timingfunc = func;
1820 c->timingdata = data;
1822 #endif
1823 return res;
1826 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1828 /* Stop if we're a zombie or need a soft hangup */
1829 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1830 return -1;
1832 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
1833 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
1835 /* Wait for a digit, no more than ms milliseconds total. */
1836 while (ms) {
1837 struct ast_channel *rchan;
1838 int outfd;
1840 errno = 0;
1841 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1842 if (!rchan && outfd < 0 && ms) {
1843 if (errno == 0 || errno == EINTR)
1844 continue;
1845 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1846 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1847 return -1;
1848 } else if (outfd > -1) {
1849 /* The FD we were watching has something waiting */
1850 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1851 return 1;
1852 } else if (rchan) {
1853 int res;
1854 struct ast_frame *f = ast_read(c);
1855 if (!f)
1856 return -1;
1858 switch(f->frametype) {
1859 case AST_FRAME_DTMF_BEGIN:
1860 break;
1861 case AST_FRAME_DTMF_END:
1862 res = f->subclass;
1863 ast_frfree(f);
1864 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1865 return res;
1866 case AST_FRAME_CONTROL:
1867 switch(f->subclass) {
1868 case AST_CONTROL_HANGUP:
1869 ast_frfree(f);
1870 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1871 return -1;
1872 case AST_CONTROL_RINGING:
1873 case AST_CONTROL_ANSWER:
1874 case AST_CONTROL_SRCUPDATE:
1875 /* Unimportant */
1876 break;
1877 default:
1878 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1879 break;
1881 break;
1882 case AST_FRAME_VOICE:
1883 /* Write audio if appropriate */
1884 if (audiofd > -1)
1885 write(audiofd, f->data, f->datalen);
1886 default:
1887 /* Ignore */
1888 break;
1890 ast_frfree(f);
1894 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1896 return 0; /* Time is up */
1899 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
1901 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
1902 void *tmp = chan->generatordata;
1903 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1904 int res;
1905 int samples;
1907 if (chan->timingfunc) {
1908 if (option_debug > 1)
1909 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1910 ast_settimeout(chan, 0, NULL, NULL);
1913 chan->generatordata = NULL; /* reset, to let writes go through */
1915 if (f->subclass != chan->writeformat) {
1916 float factor;
1917 factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass));
1918 samples = (int) ( ((float) f->samples) * factor );
1919 } else {
1920 samples = f->samples;
1923 if (chan->generator->generate) {
1924 generate = chan->generator->generate;
1926 /* This unlock is here based on two assumptions that hold true at this point in the
1927 * code. 1) this function is only called from within __ast_read() and 2) all generators
1928 * call ast_write() in their generate callback.
1930 * The reason this is added is so that when ast_write is called, the lock that occurs
1931 * there will not recursively lock the channel. Doing this will cause intended deadlock
1932 * avoidance not to work in deeper functions
1934 ast_channel_unlock(chan);
1935 res = generate(chan, tmp, f->datalen, samples);
1936 ast_channel_lock(chan);
1937 chan->generatordata = tmp;
1938 if (res) {
1939 if (option_debug > 1)
1940 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1941 ast_deactivate_generator(chan);
1944 } else if (f->frametype == AST_FRAME_CNG) {
1945 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1946 if (option_debug > 1)
1947 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
1948 ast_settimeout(chan, 160, generator_force, chan);
1953 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1955 struct ast_frame *f = NULL; /* the return value */
1956 int blah;
1957 int prestate;
1958 int count = 0;
1960 /* this function is very long so make sure there is only one return
1961 * point at the end (there are only two exceptions to this).
1963 while(ast_channel_trylock(chan)) {
1964 if(count++ > 10)
1965 /*cannot goto done since the channel is not locked*/
1966 return &ast_null_frame;
1967 usleep(1);
1970 if (chan->masq) {
1971 if (ast_do_masquerade(chan))
1972 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1973 else
1974 f = &ast_null_frame;
1975 goto done;
1978 /* Stop if we're a zombie or need a soft hangup */
1979 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1980 if (chan->generator)
1981 ast_deactivate_generator(chan);
1982 goto done;
1984 prestate = chan->_state;
1986 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
1987 !ast_strlen_zero(chan->dtmfq) &&
1988 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
1989 /* We have DTMF that has been deferred. Return it now */
1990 chan->dtmff.subclass = chan->dtmfq[0];
1991 /* Drop first digit from the buffer */
1992 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1993 f = &chan->dtmff;
1994 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
1995 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
1996 chan->dtmff.frametype = AST_FRAME_DTMF_END;
1997 } else {
1998 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);
1999 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2000 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2001 chan->emulate_dtmf_digit = f->subclass;
2002 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2004 chan->dtmf_tv = ast_tvnow();
2005 goto done;
2008 /* Read and ignore anything on the alertpipe, but read only
2009 one sizeof(blah) per frame that we send from it */
2010 if (chan->alertpipe[0] > -1) {
2011 int flags = fcntl(chan->alertpipe[0], F_GETFL);
2012 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
2013 * which immediately causes a deadlock scenario. Detect and prevent this. */
2014 if ((flags & O_NONBLOCK) == 0) {
2015 ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
2016 if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2017 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
2018 f = &ast_null_frame;
2019 goto done;
2022 read(chan->alertpipe[0], &blah, sizeof(blah));
2025 #ifdef HAVE_DAHDI
2026 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2027 int res;
2029 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2030 blah = -1;
2031 /* IF we can't get event, assume it's an expired as-per the old interface */
2032 res = ioctl(chan->timingfd, DAHDI_GETEVENT, &blah);
2033 if (res)
2034 blah = DAHDI_EVENT_TIMER_EXPIRED;
2036 if (blah == DAHDI_EVENT_TIMER_PING) {
2037 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2038 /* Acknowledge PONG unless we need it again */
2039 if (ioctl(chan->timingfd, DAHDI_TIMERPONG, &blah)) {
2040 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2043 } else if (blah == DAHDI_EVENT_TIMER_EXPIRED) {
2044 ioctl(chan->timingfd, DAHDI_TIMERACK, &blah);
2045 if (chan->timingfunc) {
2046 /* save a copy of func/data before unlocking the channel */
2047 int (*func)(const void *) = chan->timingfunc;
2048 void *data = chan->timingdata;
2049 ast_channel_unlock(chan);
2050 func(data);
2051 } else {
2052 blah = 0;
2053 ioctl(chan->timingfd, DAHDI_TIMERCONFIG, &blah);
2054 chan->timingdata = NULL;
2055 ast_channel_unlock(chan);
2057 /* cannot 'goto done' because the channel is already unlocked */
2058 return &ast_null_frame;
2059 } else
2060 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2061 } else
2062 #endif
2063 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2064 /* if the AST_GENERATOR_FD is set, call the generator with args
2065 * set to -1 so it can do whatever it needs to.
2067 void *tmp = chan->generatordata;
2068 chan->generatordata = NULL; /* reset to let ast_write get through */
2069 chan->generator->generate(chan, tmp, -1, -1);
2070 chan->generatordata = tmp;
2071 f = &ast_null_frame;
2072 goto done;
2075 /* Check for pending read queue */
2076 if (!AST_LIST_EMPTY(&chan->readq)) {
2077 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2078 /* Interpret hangup and return NULL */
2079 /* XXX why not the same for frames from the channel ? */
2080 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2081 ast_frfree(f);
2082 f = NULL;
2084 } else {
2085 chan->blocker = pthread_self();
2086 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2087 if (chan->tech->exception)
2088 f = chan->tech->exception(chan);
2089 else {
2090 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2091 f = &ast_null_frame;
2093 /* Clear the exception flag */
2094 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2095 } else if (chan->tech->read)
2096 f = chan->tech->read(chan);
2097 else
2098 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2101 if (f) {
2102 /* if the channel driver returned more than one frame, stuff the excess
2103 into the readq for the next ast_read call (note that we can safely assume
2104 that the readq is empty, because otherwise we would not have called into
2105 the channel driver and f would be only a single frame)
2107 if (AST_LIST_NEXT(f, frame_list)) {
2108 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2109 AST_LIST_NEXT(f, frame_list) = NULL;
2112 switch (f->frametype) {
2113 case AST_FRAME_CONTROL:
2114 if (f->subclass == AST_CONTROL_ANSWER) {
2115 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2116 if (option_debug)
2117 ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
2118 ast_frfree(f);
2119 f = &ast_null_frame;
2120 } else if (prestate == AST_STATE_UP) {
2121 if (option_debug)
2122 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
2123 ast_frfree(f);
2124 f = &ast_null_frame;
2125 } else {
2126 /* Answer the CDR */
2127 ast_setstate(chan, AST_STATE_UP);
2128 /* removed a call to ast_cdr_answer(chan->cdr) from here. */
2131 break;
2132 case AST_FRAME_DTMF_END:
2133 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2134 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2135 * However, only let emulation be forced if the other end cares about BEGIN frames */
2136 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2137 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2138 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2139 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2140 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2141 } else
2142 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2143 ast_frfree(f);
2144 f = &ast_null_frame;
2145 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2146 if (!ast_tvzero(chan->dtmf_tv) &&
2147 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2148 /* If it hasn't been long enough, defer this digit */
2149 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2150 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2151 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2152 } else
2153 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2154 ast_frfree(f);
2155 f = &ast_null_frame;
2156 } else {
2157 /* There was no begin, turn this into a begin and send the end later */
2158 f->frametype = AST_FRAME_DTMF_BEGIN;
2159 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2160 chan->emulate_dtmf_digit = f->subclass;
2161 chan->dtmf_tv = ast_tvnow();
2162 if (f->len) {
2163 if (f->len > AST_MIN_DTMF_DURATION)
2164 chan->emulate_dtmf_duration = f->len;
2165 else
2166 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2167 } else
2168 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2169 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2171 if (chan->audiohooks) {
2172 struct ast_frame *old_frame = f;
2173 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2174 if (old_frame != f)
2175 ast_frfree(old_frame);
2177 } else {
2178 struct timeval now = ast_tvnow();
2179 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2180 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2181 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2182 if (!f->len)
2183 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2184 } else if (!f->len) {
2185 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2186 f->len = AST_MIN_DTMF_DURATION;
2188 if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2189 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);
2190 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2191 chan->emulate_dtmf_digit = f->subclass;
2192 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2193 ast_frfree(f);
2194 f = &ast_null_frame;
2195 } else {
2196 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2197 if (f->len < AST_MIN_DTMF_DURATION) {
2198 f->len = AST_MIN_DTMF_DURATION;
2200 chan->dtmf_tv = now;
2202 if (chan->audiohooks) {
2203 struct ast_frame *old_frame = f;
2204 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2205 if (old_frame != f)
2206 ast_frfree(old_frame);
2209 break;
2210 case AST_FRAME_DTMF_BEGIN:
2211 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2212 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
2213 (!ast_tvzero(chan->dtmf_tv) &&
2214 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2215 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2216 ast_frfree(f);
2217 f = &ast_null_frame;
2218 } else {
2219 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2220 chan->dtmf_tv = ast_tvnow();
2221 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2223 break;
2224 case AST_FRAME_NULL:
2225 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2226 * is reached , because we want to make sure we pass at least one
2227 * voice frame through before starting the next digit, to ensure a gap
2228 * between DTMF digits. */
2229 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2230 struct timeval now = ast_tvnow();
2231 if (!chan->emulate_dtmf_duration) {
2232 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2233 chan->emulate_dtmf_digit = 0;
2234 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2235 chan->emulate_dtmf_duration = 0;
2236 ast_frfree(f);
2237 f = &chan->dtmff;
2238 f->frametype = AST_FRAME_DTMF_END;
2239 f->subclass = chan->emulate_dtmf_digit;
2240 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2241 chan->dtmf_tv = now;
2242 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2243 chan->emulate_dtmf_digit = 0;
2244 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2247 break;
2248 case AST_FRAME_VOICE:
2249 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2250 * is reached , because we want to make sure we pass at least one
2251 * voice frame through before starting the next digit, to ensure a gap
2252 * between DTMF digits. */
2253 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2254 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2255 chan->emulate_dtmf_digit = 0;
2258 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2259 if (dropaudio)
2260 ast_read_generator_actions(chan, f);
2261 ast_frfree(f);
2262 f = &ast_null_frame;
2265 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2266 struct timeval now = ast_tvnow();
2267 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2268 chan->emulate_dtmf_duration = 0;
2269 ast_frfree(f);
2270 f = &chan->dtmff;
2271 f->frametype = AST_FRAME_DTMF_END;
2272 f->subclass = chan->emulate_dtmf_digit;
2273 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2274 chan->dtmf_tv = now;
2275 if (chan->audiohooks) {
2276 struct ast_frame *old_frame = f;
2277 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2278 if (old_frame != f)
2279 ast_frfree(old_frame);
2281 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2282 } else {
2283 /* Drop voice frames while we're still in the middle of the digit */
2284 ast_frfree(f);
2285 f = &ast_null_frame;
2287 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2288 /* This frame is not one of the current native formats -- drop it on the floor */
2289 char to[200];
2290 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2291 chan->name, ast_getformatname(f->subclass), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
2292 ast_frfree(f);
2293 f = &ast_null_frame;
2294 } else if ((f->frametype == AST_FRAME_VOICE)) {
2295 if (chan->audiohooks) {
2296 struct ast_frame *old_frame = f;
2297 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2298 if (old_frame != f)
2299 ast_frfree(old_frame);
2301 if (chan->monitor && chan->monitor->read_stream ) {
2302 /* XXX what does this do ? */
2303 #ifndef MONITOR_CONSTANT_DELAY
2304 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2305 if (jump >= 0) {
2306 jump = chan->outsmpl - chan->insmpl;
2307 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2308 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2309 chan->insmpl += jump + f->samples;
2310 } else
2311 chan->insmpl+= f->samples;
2312 #else
2313 int jump = chan->outsmpl - chan->insmpl;
2314 if (jump - MONITOR_DELAY >= 0) {
2315 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2316 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2317 chan->insmpl += jump;
2318 } else
2319 chan->insmpl += f->samples;
2320 #endif
2321 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2322 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2323 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2327 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2328 f = &ast_null_frame;
2330 /* Run generator sitting on the line if timing device not available
2331 * and synchronous generation of outgoing frames is necessary */
2332 ast_read_generator_actions(chan, f);
2334 default:
2335 /* Just pass it on! */
2336 break;
2338 } else {
2339 /* Make sure we always return NULL in the future */
2340 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2341 if (chan->generator)
2342 ast_deactivate_generator(chan);
2343 /* We no longer End the CDR here */
2346 /* High bit prints debugging */
2347 if (chan->fin & DEBUGCHAN_FLAG)
2348 ast_frame_dump(chan->name, f, "<<");
2349 chan->fin = FRAMECOUNT_INC(chan->fin);
2351 done:
2352 ast_channel_unlock(chan);
2353 return f;
2356 int ast_internal_timing_enabled(struct ast_channel *chan)
2358 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2359 if (option_debug > 4)
2360 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);
2361 return ret;
2364 struct ast_frame *ast_read(struct ast_channel *chan)
2366 return __ast_read(chan, 0);
2369 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2371 return __ast_read(chan, 1);
2374 int ast_indicate(struct ast_channel *chan, int condition)
2376 return ast_indicate_data(chan, condition, NULL, 0);
2379 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2381 int res = -1;
2383 ast_channel_lock(chan);
2384 /* Stop if we're a zombie or need a soft hangup */
2385 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2386 ast_channel_unlock(chan);
2387 return -1;
2389 if (chan->tech->indicate)
2390 res = chan->tech->indicate(chan, condition, data, datalen);
2391 ast_channel_unlock(chan);
2392 if (!chan->tech->indicate || res) {
2394 * Device does not support (that) indication, lets fake
2395 * it by doing our own tone generation. (PM2002)
2397 if (condition < 0)
2398 ast_playtones_stop(chan);
2399 else {
2400 const struct ind_tone_zone_sound *ts = NULL;
2401 switch (condition) {
2402 case AST_CONTROL_RINGING:
2403 ts = ast_get_indication_tone(chan->zone, "ring");
2404 break;
2405 case AST_CONTROL_BUSY:
2406 ts = ast_get_indication_tone(chan->zone, "busy");
2407 break;
2408 case AST_CONTROL_CONGESTION:
2409 ts = ast_get_indication_tone(chan->zone, "congestion");
2410 break;
2412 if (ts && ts->data[0]) {
2413 if (option_debug)
2414 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2415 ast_playtones_start(chan,0,ts->data, 1);
2416 res = 0;
2417 chan->visible_indication = condition;
2418 } else if (condition == AST_CONTROL_PROGRESS) {
2419 /* ast_playtones_stop(chan); */
2420 } else if (condition == AST_CONTROL_PROCEEDING) {
2421 /* Do nothing, really */
2422 } else if (condition == AST_CONTROL_HOLD) {
2423 /* Do nothing.... */
2424 } else if (condition == AST_CONTROL_UNHOLD) {
2425 /* Do nothing.... */
2426 } else if (condition == AST_CONTROL_VIDUPDATE) {
2427 /* Do nothing.... */
2428 } else if (condition == AST_CONTROL_SRCUPDATE) {
2429 /* Do nothing... */
2430 } else {
2431 /* not handled */
2432 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2433 res = -1;
2436 } else
2437 chan->visible_indication = condition;
2439 return res;
2442 int ast_recvchar(struct ast_channel *chan, int timeout)
2444 int c;
2445 char *buf = ast_recvtext(chan, timeout);
2446 if (buf == NULL)
2447 return -1; /* error or timeout */
2448 c = *(unsigned char *)buf;
2449 free(buf);
2450 return c;
2453 char *ast_recvtext(struct ast_channel *chan, int timeout)
2455 int res, done = 0;
2456 char *buf = NULL;
2458 while (!done) {
2459 struct ast_frame *f;
2460 if (ast_check_hangup(chan))
2461 break;
2462 res = ast_waitfor(chan, timeout);
2463 if (res <= 0) /* timeout or error */
2464 break;
2465 timeout = res; /* update timeout */
2466 f = ast_read(chan);
2467 if (f == NULL)
2468 break; /* no frame */
2469 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2470 done = 1; /* force a break */
2471 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2472 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2473 done = 1;
2475 ast_frfree(f);
2477 return buf;
2480 int ast_sendtext(struct ast_channel *chan, const char *text)
2482 int res = 0;
2483 /* Stop if we're a zombie or need a soft hangup */
2484 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2485 return -1;
2486 CHECK_BLOCKING(chan);
2487 if (chan->tech->send_text)
2488 res = chan->tech->send_text(chan, text);
2489 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2490 return res;
2493 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2495 /* Device does not support DTMF tones, lets fake
2496 * it by doing our own generation. */
2497 static const char* dtmf_tones[] = {
2498 "941+1336", /* 0 */
2499 "697+1209", /* 1 */
2500 "697+1336", /* 2 */
2501 "697+1477", /* 3 */
2502 "770+1209", /* 4 */
2503 "770+1336", /* 5 */
2504 "770+1477", /* 6 */
2505 "852+1209", /* 7 */
2506 "852+1336", /* 8 */
2507 "852+1477", /* 9 */
2508 "697+1633", /* A */
2509 "770+1633", /* B */
2510 "852+1633", /* C */
2511 "941+1633", /* D */
2512 "941+1209", /* * */
2513 "941+1477" /* # */
2516 if (!chan->tech->send_digit_begin)
2517 return 0;
2519 if (!chan->tech->send_digit_begin(chan, digit))
2520 return 0;
2522 if (digit >= '0' && digit <='9')
2523 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2524 else if (digit >= 'A' && digit <= 'D')
2525 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2526 else if (digit == '*')
2527 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2528 else if (digit == '#')
2529 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2530 else {
2531 /* not handled */
2532 if (option_debug)
2533 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2536 return 0;
2539 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2541 int res = -1;
2543 if (chan->tech->send_digit_end)
2544 res = chan->tech->send_digit_end(chan, digit, duration);
2546 if (res && chan->generator)
2547 ast_playtones_stop(chan);
2549 return 0;
2552 int ast_senddigit(struct ast_channel *chan, char digit)
2554 if (chan->tech->send_digit_begin) {
2555 ast_senddigit_begin(chan, digit);
2556 ast_safe_sleep(chan, AST_DEFAULT_EMULATE_DTMF_DURATION);
2559 return ast_senddigit_end(chan, digit, AST_DEFAULT_EMULATE_DTMF_DURATION);
2562 int ast_prod(struct ast_channel *chan)
2564 struct ast_frame a = { AST_FRAME_VOICE };
2565 char nothing[128];
2567 /* Send an empty audio frame to get things moving */
2568 if (chan->_state != AST_STATE_UP) {
2569 if (option_debug)
2570 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2571 a.subclass = chan->rawwriteformat;
2572 a.data = nothing + AST_FRIENDLY_OFFSET;
2573 a.src = "ast_prod";
2574 if (ast_write(chan, &a))
2575 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2577 return 0;
2580 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2582 int res;
2583 if (!chan->tech->write_video)
2584 return 0;
2585 res = ast_write(chan, fr);
2586 if (!res)
2587 res = 1;
2588 return res;
2591 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2593 int res = -1;
2594 int count = 0;
2595 struct ast_frame *f = NULL, *f2 = NULL;
2597 /*Deadlock avoidance*/
2598 while(ast_channel_trylock(chan)) {
2599 /*cannot goto done since the channel is not locked*/
2600 if(count++ > 10) {
2601 if(option_debug)
2602 ast_log(LOG_DEBUG, "Deadlock avoided for write to channel '%s'\n", chan->name);
2603 return 0;
2605 usleep(1);
2607 /* Stop if we're a zombie or need a soft hangup */
2608 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2609 goto done;
2611 /* Handle any pending masquerades */
2612 if (chan->masq && ast_do_masquerade(chan)) {
2613 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2614 goto done;
2616 if (chan->masqr) {
2617 res = 0; /* XXX explain, why 0 ? */
2618 goto done;
2620 if (chan->generatordata) {
2621 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2622 ast_deactivate_generator(chan);
2623 else {
2624 if (fr->frametype == AST_FRAME_DTMF_END) {
2625 /* There is a generator running while we're in the middle of a digit.
2626 * It's probably inband DTMF, so go ahead and pass it so it can
2627 * stop the generator */
2628 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2629 ast_channel_unlock(chan);
2630 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2631 ast_channel_lock(chan);
2632 CHECK_BLOCKING(chan);
2633 } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2634 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2635 res = (chan->tech->indicate == NULL) ? 0 :
2636 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2638 res = 0; /* XXX explain, why 0 ? */
2639 goto done;
2642 /* High bit prints debugging */
2643 if (chan->fout & DEBUGCHAN_FLAG)
2644 ast_frame_dump(chan->name, fr, ">>");
2645 CHECK_BLOCKING(chan);
2646 switch(fr->frametype) {
2647 case AST_FRAME_CONTROL:
2648 res = (chan->tech->indicate == NULL) ? 0 :
2649 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2650 break;
2651 case AST_FRAME_DTMF_BEGIN:
2652 if (chan->audiohooks) {
2653 struct ast_frame *old_frame = fr;
2654 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2655 if (old_frame != fr)
2656 f = fr;
2658 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2659 ast_channel_unlock(chan);
2660 res = ast_senddigit_begin(chan, fr->subclass);
2661 ast_channel_lock(chan);
2662 CHECK_BLOCKING(chan);
2663 break;
2664 case AST_FRAME_DTMF_END:
2665 if (chan->audiohooks) {
2666 struct ast_frame *old_frame = fr;
2667 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2668 if (old_frame != fr)
2669 f = fr;
2671 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2672 ast_channel_unlock(chan);
2673 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2674 ast_channel_lock(chan);
2675 CHECK_BLOCKING(chan);
2676 break;
2677 case AST_FRAME_TEXT:
2678 res = (chan->tech->send_text == NULL) ? 0 :
2679 chan->tech->send_text(chan, (char *) fr->data);
2680 break;
2681 case AST_FRAME_HTML:
2682 res = (chan->tech->send_html == NULL) ? 0 :
2683 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2684 break;
2685 case AST_FRAME_VIDEO:
2686 /* XXX Handle translation of video codecs one day XXX */
2687 res = (chan->tech->write_video == NULL) ? 0 :
2688 chan->tech->write_video(chan, fr);
2689 break;
2690 case AST_FRAME_MODEM:
2691 res = (chan->tech->write == NULL) ? 0 :
2692 chan->tech->write(chan, fr);
2693 break;
2694 case AST_FRAME_VOICE:
2695 if (chan->tech->write == NULL)
2696 break; /*! \todo XXX should return 0 maybe ? */
2698 if (chan->audiohooks) {
2699 struct ast_frame *old_frame = fr;
2700 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2701 if (old_frame != fr)
2702 f2 = fr;
2705 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2706 if (fr->subclass == chan->rawwriteformat)
2707 f = fr;
2708 else
2709 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2711 /* If we have no frame of audio, then we have to bail out */
2712 if (!f) {
2713 res = 0;
2714 break;
2717 /* If Monitor is running on this channel, then we have to write frames out there too */
2718 if (chan->monitor && chan->monitor->write_stream) {
2719 /* XXX must explain this code */
2720 #ifndef MONITOR_CONSTANT_DELAY
2721 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2722 if (jump >= 0) {
2723 jump = chan->insmpl - chan->outsmpl;
2724 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2725 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2726 chan->outsmpl += jump + f->samples;
2727 } else
2728 chan->outsmpl += f->samples;
2729 #else
2730 int jump = chan->insmpl - chan->outsmpl;
2731 if (jump - MONITOR_DELAY >= 0) {
2732 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2733 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2734 chan->outsmpl += jump;
2735 } else
2736 chan->outsmpl += f->samples;
2737 #endif
2738 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2739 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2740 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2744 if (f)
2745 res = chan->tech->write(chan,f);
2746 else
2747 res = 0;
2748 break;
2749 case AST_FRAME_NULL:
2750 case AST_FRAME_IAX:
2751 /* Ignore these */
2752 res = 0;
2753 break;
2754 default:
2755 /* At this point, fr is the incoming frame and f is NULL. Channels do
2756 * not expect to get NULL as a frame pointer and will segfault. Hence,
2757 * we output the original frame passed in. */
2758 res = chan->tech->write(chan, fr);
2759 break;
2762 if (f && f != fr)
2763 ast_frfree(f);
2764 if (f2)
2765 ast_frfree(f2);
2766 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2767 /* Consider a write failure to force a soft hangup */
2768 if (res < 0)
2769 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2770 else {
2771 chan->fout = FRAMECOUNT_INC(chan->fout);
2773 done:
2774 ast_channel_unlock(chan);
2775 return res;
2778 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2779 struct ast_trans_pvt **trans, const int direction)
2781 int native;
2782 int res;
2783 char from[200], to[200];
2785 /* Make sure we only consider audio */
2786 fmt &= AST_FORMAT_AUDIO_MASK;
2788 native = chan->nativeformats;
2789 /* Find a translation path from the native format to one of the desired formats */
2790 if (!direction)
2791 /* reading */
2792 res = ast_translator_best_choice(&fmt, &native);
2793 else
2794 /* writing */
2795 res = ast_translator_best_choice(&native, &fmt);
2797 if (res < 0) {
2798 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2799 ast_getformatname_multiple(from, sizeof(from), native),
2800 ast_getformatname_multiple(to, sizeof(to), fmt));
2801 return -1;
2804 /* Now we have a good choice for both. */
2805 ast_channel_lock(chan);
2807 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2808 /* the channel is already in these formats, so nothing to do */
2809 ast_channel_unlock(chan);
2810 return 0;
2813 *rawformat = native;
2814 /* User perspective is fmt */
2815 *format = fmt;
2816 /* Free any read translation we have right now */
2817 if (*trans)
2818 ast_translator_free_path(*trans);
2819 /* Build a translation path from the raw format to the desired format */
2820 if (!direction)
2821 /* reading */
2822 *trans = ast_translator_build_path(*format, *rawformat);
2823 else
2824 /* writing */
2825 *trans = ast_translator_build_path(*rawformat, *format);
2826 ast_channel_unlock(chan);
2827 if (option_debug)
2828 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2829 direction ? "write" : "read", ast_getformatname(fmt));
2830 return 0;
2833 int ast_set_read_format(struct ast_channel *chan, int fmt)
2835 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2836 &chan->readtrans, 0);
2839 int ast_set_write_format(struct ast_channel *chan, int fmt)
2841 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2842 &chan->writetrans, 1);
2845 char *ast_channel_reason2str(int reason)
2847 switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
2849 case 0:
2850 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
2851 case AST_CONTROL_HANGUP:
2852 return "Hangup";
2853 case AST_CONTROL_RING:
2854 return "Local Ring";
2855 case AST_CONTROL_RINGING:
2856 return "Remote end Ringing";
2857 case AST_CONTROL_ANSWER:
2858 return "Remote end has Answered";
2859 case AST_CONTROL_BUSY:
2860 return "Remote end is Busy";
2861 case AST_CONTROL_CONGESTION:
2862 return "Congestion (circuits busy)";
2863 default:
2864 return "Unknown Reason!!";
2868 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)
2870 int dummy_outstate;
2871 int cause = 0;
2872 struct ast_channel *chan;
2873 int res = 0;
2874 int last_subclass = 0;
2876 if (outstate)
2877 *outstate = 0;
2878 else
2879 outstate = &dummy_outstate; /* make outstate always a valid pointer */
2881 chan = ast_request(type, format, data, &cause);
2882 if (!chan) {
2883 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2884 /* compute error and return */
2885 if (cause == AST_CAUSE_BUSY)
2886 *outstate = AST_CONTROL_BUSY;
2887 else if (cause == AST_CAUSE_CONGESTION)
2888 *outstate = AST_CONTROL_CONGESTION;
2889 return NULL;
2892 if (oh) {
2893 if (oh->vars)
2894 ast_set_variables(chan, oh->vars);
2895 /* XXX why is this necessary, for the parent_channel perhaps ? */
2896 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2897 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2898 if (oh->parent_channel)
2899 ast_channel_inherit_variables(oh->parent_channel, chan);
2900 if (oh->account)
2901 ast_cdr_setaccount(chan, oh->account);
2903 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2905 if (ast_call(chan, data, 0)) { /* ast_call failed... */
2906 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2907 } else {
2908 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
2909 while (timeout && chan->_state != AST_STATE_UP) {
2910 struct ast_frame *f;
2911 res = ast_waitfor(chan, timeout);
2912 if (res <= 0) /* error, timeout, or done */
2913 break;
2914 if (timeout > -1)
2915 timeout = res;
2916 f = ast_read(chan);
2917 if (!f) {
2918 *outstate = AST_CONTROL_HANGUP;
2919 res = 0;
2920 break;
2922 if (f->frametype == AST_FRAME_CONTROL) {
2923 switch (f->subclass) {
2924 case AST_CONTROL_RINGING: /* record but keep going */
2925 *outstate = f->subclass;
2926 break;
2928 case AST_CONTROL_BUSY:
2929 case AST_CONTROL_CONGESTION:
2930 case AST_CONTROL_ANSWER:
2931 *outstate = f->subclass;
2932 timeout = 0; /* trick to force exit from the while() */
2933 break;
2935 /* Ignore these */
2936 case AST_CONTROL_PROGRESS:
2937 case AST_CONTROL_PROCEEDING:
2938 case AST_CONTROL_HOLD:
2939 case AST_CONTROL_UNHOLD:
2940 case AST_CONTROL_VIDUPDATE:
2941 case AST_CONTROL_SRCUPDATE:
2942 case -1: /* Ignore -- just stopping indications */
2943 break;
2945 default:
2946 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2948 last_subclass = f->subclass;
2950 ast_frfree(f);
2954 /* Final fixups */
2955 if (oh) {
2956 if (!ast_strlen_zero(oh->context))
2957 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2958 if (!ast_strlen_zero(oh->exten))
2959 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2960 if (oh->priority)
2961 chan->priority = oh->priority;
2963 if (chan->_state == AST_STATE_UP)
2964 *outstate = AST_CONTROL_ANSWER;
2966 if (res <= 0) {
2967 if ( AST_CONTROL_RINGING == last_subclass )
2968 chan->hangupcause = AST_CAUSE_NO_ANSWER;
2969 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2970 ast_cdr_init(chan->cdr, chan);
2971 if (chan->cdr) {
2972 char tmp[256];
2973 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2974 ast_cdr_setapp(chan->cdr,"Dial",tmp);
2975 ast_cdr_update(chan);
2976 ast_cdr_start(chan->cdr);
2977 ast_cdr_end(chan->cdr);
2978 /* If the cause wasn't handled properly */
2979 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2980 ast_cdr_failed(chan->cdr);
2982 ast_hangup(chan);
2983 chan = NULL;
2985 return chan;
2988 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2990 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2993 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2995 struct chanlist *chan;
2996 struct ast_channel *c;
2997 int capabilities;
2998 int fmt;
2999 int res;
3000 int foo;
3001 int videoformat = format & AST_FORMAT_VIDEO_MASK;
3003 if (!cause)
3004 cause = &foo;
3005 *cause = AST_CAUSE_NOTDEFINED;
3007 if (AST_LIST_LOCK(&channels)) {
3008 ast_log(LOG_WARNING, "Unable to lock channel list\n");
3009 return NULL;
3012 AST_LIST_TRAVERSE(&backends, chan, list) {
3013 if (strcasecmp(type, chan->tech->type))
3014 continue;
3016 capabilities = chan->tech->capabilities;
3017 fmt = format & AST_FORMAT_AUDIO_MASK;
3018 res = ast_translator_best_choice(&fmt, &capabilities);
3019 if (res < 0) {
3020 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
3021 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3022 AST_LIST_UNLOCK(&channels);
3023 return NULL;
3025 AST_LIST_UNLOCK(&channels);
3026 if (!chan->tech->requester)
3027 return NULL;
3029 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
3030 return NULL;
3032 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3033 return c;
3036 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
3037 *cause = AST_CAUSE_NOSUCHDRIVER;
3038 AST_LIST_UNLOCK(&channels);
3040 return NULL;
3043 int ast_call(struct ast_channel *chan, char *addr, int timeout)
3045 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3046 If the remote end does not answer within the timeout, then do NOT hang up, but
3047 return anyway. */
3048 int res = -1;
3049 /* Stop if we're a zombie or need a soft hangup */
3050 ast_channel_lock(chan);
3051 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3052 if (chan->tech->call)
3053 res = chan->tech->call(chan, addr, timeout);
3054 ast_set_flag(chan, AST_FLAG_OUTGOING);
3056 ast_channel_unlock(chan);
3057 return res;
3061 \brief Transfer a call to dest, if the channel supports transfer
3063 Called by:
3064 \arg app_transfer
3065 \arg the manager interface
3067 int ast_transfer(struct ast_channel *chan, char *dest)
3069 int res = -1;
3071 /* Stop if we're a zombie or need a soft hangup */
3072 ast_channel_lock(chan);
3073 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3074 if (chan->tech->transfer) {
3075 res = chan->tech->transfer(chan, dest);
3076 if (!res)
3077 res = 1;
3078 } else
3079 res = 0;
3081 ast_channel_unlock(chan);
3082 return res;
3085 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3087 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3090 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3092 int pos = 0; /* index in the buffer where we accumulate digits */
3093 int to = ftimeout;
3095 /* Stop if we're a zombie or need a soft hangup */
3096 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3097 return -1;
3098 if (!len)
3099 return -1;
3100 for (;;) {
3101 int d;
3102 if (c->stream) {
3103 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3104 ast_stopstream(c);
3105 usleep(1000);
3106 if (!d)
3107 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3108 } else {
3109 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3111 if (d < 0)
3112 return -1;
3113 if (d == 0) {
3114 s[pos]='\0';
3115 return 1;
3117 if (d == 1) {
3118 s[pos]='\0';
3119 return 2;
3121 if (!strchr(enders, d))
3122 s[pos++] = d;
3123 if (strchr(enders, d) || (pos >= len)) {
3124 s[pos]='\0';
3125 return 0;
3127 to = timeout;
3129 /* Never reached */
3130 return 0;
3133 int ast_channel_supports_html(struct ast_channel *chan)
3135 return (chan->tech->send_html) ? 1 : 0;
3138 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3140 if (chan->tech->send_html)
3141 return chan->tech->send_html(chan, subclass, data, datalen);
3142 return -1;
3145 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3147 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3150 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3152 int src;
3153 int dst;
3155 if (chan->readformat == peer->writeformat && chan->writeformat == peer->readformat) {
3156 /* Already compatible! Moving on ... */
3157 return 0;
3160 /* Set up translation from the chan to the peer */
3161 src = chan->nativeformats;
3162 dst = peer->nativeformats;
3163 if (ast_translator_best_choice(&dst, &src) < 0) {
3164 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
3165 return -1;
3168 /* if the best path is not 'pass through', then
3169 transcoding is needed; if desired, force transcode path
3170 to use SLINEAR between channels, but only if there is
3171 no direct conversion available */
3172 if ((src != dst) && ast_opt_transcode_via_slin &&
3173 (ast_translate_path_steps(dst, src) != 1))
3174 dst = AST_FORMAT_SLINEAR;
3175 if (ast_set_read_format(chan, dst) < 0) {
3176 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
3177 return -1;
3179 if (ast_set_write_format(peer, dst) < 0) {
3180 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
3181 return -1;
3184 /* Set up translation from the peer to the chan */
3185 src = peer->nativeformats;
3186 dst = chan->nativeformats;
3187 if (ast_translator_best_choice(&dst, &src) < 0) {
3188 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
3189 return -1;
3192 /* if the best path is not 'pass through', then
3193 transcoding is needed; if desired, force transcode path
3194 to use SLINEAR between channels, but only if there is
3195 no direct conversion available */
3196 if ((src != dst) && ast_opt_transcode_via_slin &&
3197 (ast_translate_path_steps(dst, src) != 1))
3198 dst = AST_FORMAT_SLINEAR;
3199 if (ast_set_read_format(peer, dst) < 0) {
3200 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
3201 return -1;
3203 if (ast_set_write_format(chan, dst) < 0) {
3204 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
3205 return -1;
3207 return 0;
3210 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3212 int res = -1;
3213 struct ast_channel *final_orig, *final_clone, *base;
3215 retrymasq:
3216 final_orig = original;
3217 final_clone = clone;
3219 ast_channel_lock(original);
3220 while (ast_channel_trylock(clone)) {
3221 ast_channel_unlock(original);
3222 usleep(1);
3223 ast_channel_lock(original);
3226 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3227 and if so, we don't really want to masquerade it, but its proxy */
3228 if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
3229 final_orig = original->_bridge;
3231 if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)) && (clone->_bridge->_bridge != clone))
3232 final_clone = clone->_bridge;
3234 if (final_clone->tech->get_base_channel && (base = final_clone->tech->get_base_channel(final_clone))) {
3235 final_clone = base;
3238 if ((final_orig != original) || (final_clone != clone)) {
3239 /* Lots and lots of deadlock avoidance. The main one we're competing with
3240 * is ast_write(), which locks channels recursively, when working with a
3241 * proxy channel. */
3242 if (ast_channel_trylock(final_orig)) {
3243 ast_channel_unlock(clone);
3244 ast_channel_unlock(original);
3245 goto retrymasq;
3247 if (ast_channel_trylock(final_clone)) {
3248 ast_channel_unlock(final_orig);
3249 ast_channel_unlock(clone);
3250 ast_channel_unlock(original);
3251 goto retrymasq;
3253 ast_channel_unlock(clone);
3254 ast_channel_unlock(original);
3255 original = final_orig;
3256 clone = final_clone;
3259 if (original == clone) {
3260 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3261 ast_channel_unlock(clone);
3262 ast_channel_unlock(original);
3263 return -1;
3266 if (option_debug)
3267 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
3268 clone->name, original->name);
3269 if (original->masq) {
3270 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3271 original->masq->name, original->name);
3272 } else if (clone->masqr) {
3273 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3274 clone->name, clone->masqr->name);
3275 } else {
3276 original->masq = clone;
3277 clone->masqr = original;
3278 ast_queue_frame(original, &ast_null_frame);
3279 ast_queue_frame(clone, &ast_null_frame);
3280 if (option_debug)
3281 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3282 res = 0;
3285 ast_channel_unlock(clone);
3286 ast_channel_unlock(original);
3288 return res;
3291 void ast_change_name(struct ast_channel *chan, char *newname)
3293 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3294 ast_string_field_set(chan, name, newname);
3297 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3299 struct ast_var_t *current, *newvar;
3300 const char *varname;
3302 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3303 int vartype = 0;
3305 varname = ast_var_full_name(current);
3306 if (!varname)
3307 continue;
3309 if (varname[0] == '_') {
3310 vartype = 1;
3311 if (varname[1] == '_')
3312 vartype = 2;
3315 switch (vartype) {
3316 case 1:
3317 newvar = ast_var_assign(&varname[1], ast_var_value(current));
3318 if (newvar) {
3319 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3320 if (option_debug)
3321 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3323 break;
3324 case 2:
3325 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
3326 if (newvar) {
3327 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3328 if (option_debug)
3329 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3331 break;
3332 default:
3333 if (option_debug)
3334 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
3335 break;
3341 \brief Clone channel variables from 'clone' channel into 'original' channel
3343 All variables except those related to app_groupcount are cloned.
3344 Variables are actually _removed_ from 'clone' channel, presumably
3345 because it will subsequently be destroyed.
3347 \note Assumes locks will be in place on both channels when called.
3349 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3351 struct ast_var_t *current, *newvar;
3352 /* Append variables from clone channel into original channel */
3353 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3354 if (AST_LIST_FIRST(&clone->varshead))
3355 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3357 /* then, dup the varshead list into the clone */
3359 AST_LIST_TRAVERSE(&original->varshead, current, entries) {
3360 newvar = ast_var_assign(current->name, current->value);
3361 if (newvar)
3362 AST_LIST_INSERT_TAIL(&clone->varshead, newvar, entries);
3367 \brief Masquerade a channel
3369 \note Assumes channel will be locked when called
3371 int ast_do_masquerade(struct ast_channel *original)
3373 int x,i;
3374 int res=0;
3375 int origstate;
3376 struct ast_frame *cur;
3377 const struct ast_channel_tech *t;
3378 void *t_pvt;
3379 struct ast_callerid tmpcid;
3380 struct ast_channel *clone = original->masq;
3381 struct ast_cdr *cdr;
3382 int rformat = original->readformat;
3383 int wformat = original->writeformat;
3384 char newn[100];
3385 char orig[100];
3386 char masqn[100];
3387 char zombn[100];
3389 if (option_debug > 3)
3390 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3391 clone->name, clone->_state, original->name, original->_state);
3393 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3394 the clone channel into the original channel. Start by killing off the original
3395 channel's backend. I'm not sure we're going to keep this function, because
3396 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3398 /* We need the clone's lock, too */
3399 ast_channel_lock(clone);
3401 if (option_debug > 1)
3402 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3404 /* Having remembered the original read/write formats, we turn off any translation on either
3405 one */
3406 free_translation(clone);
3407 free_translation(original);
3410 /* Unlink the masquerade */
3411 original->masq = NULL;
3412 clone->masqr = NULL;
3414 /* Save the original name */
3415 ast_copy_string(orig, original->name, sizeof(orig));
3416 /* Save the new name */
3417 ast_copy_string(newn, clone->name, sizeof(newn));
3418 /* Create the masq name */
3419 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3421 /* Copy the name from the clone channel */
3422 ast_string_field_set(original, name, newn);
3424 /* Mangle the name of the clone channel */
3425 ast_string_field_set(clone, name, masqn);
3427 /* Notify any managers of the change, first the masq then the other */
3428 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3429 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3431 /* Swap the technologies */
3432 t = original->tech;
3433 original->tech = clone->tech;
3434 clone->tech = t;
3436 /* Swap the cdrs */
3437 cdr = original->cdr;
3438 original->cdr = clone->cdr;
3439 clone->cdr = cdr;
3441 t_pvt = original->tech_pvt;
3442 original->tech_pvt = clone->tech_pvt;
3443 clone->tech_pvt = t_pvt;
3445 /* Swap the alertpipes */
3446 for (i = 0; i < 2; i++) {
3447 x = original->alertpipe[i];
3448 original->alertpipe[i] = clone->alertpipe[i];
3449 clone->alertpipe[i] = x;
3453 * Swap the readq's. The end result should be this:
3455 * 1) All frames should be on the new (original) channel.
3456 * 2) Any frames that were already on the new channel before this
3457 * masquerade need to be at the end of the readq, after all of the
3458 * frames on the old (clone) channel.
3459 * 3) The alertpipe needs to get poked for every frame that was already
3460 * on the new channel, since we are now using the alert pipe from the
3461 * old (clone) channel.
3464 AST_LIST_HEAD_NOLOCK(, ast_frame) tmp_readq;
3465 AST_LIST_HEAD_SET_NOLOCK(&tmp_readq, NULL);
3467 AST_LIST_APPEND_LIST(&tmp_readq, &original->readq, frame_list);
3468 AST_LIST_APPEND_LIST(&original->readq, &clone->readq, frame_list);
3470 while ((cur = AST_LIST_REMOVE_HEAD(&tmp_readq, frame_list))) {
3471 AST_LIST_INSERT_TAIL(&original->readq, cur, frame_list);
3472 if (original->alertpipe[1] > -1) {
3473 int poke = 0;
3474 write(original->alertpipe[1], &poke, sizeof(poke));
3479 /* Swap the raw formats */
3480 x = original->rawreadformat;
3481 original->rawreadformat = clone->rawreadformat;
3482 clone->rawreadformat = x;
3483 x = original->rawwriteformat;
3484 original->rawwriteformat = clone->rawwriteformat;
3485 clone->rawwriteformat = x;
3487 clone->_softhangup = AST_SOFTHANGUP_DEV;
3489 /* And of course, so does our current state. Note we need not
3490 call ast_setstate since the event manager doesn't really consider
3491 these separate. We do this early so that the clone has the proper
3492 state of the original channel. */
3493 origstate = original->_state;
3494 original->_state = clone->_state;
3495 clone->_state = origstate;
3497 if (clone->tech->fixup){
3498 res = clone->tech->fixup(original, clone);
3499 if (res)
3500 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3503 /* Start by disconnecting the original's physical side */
3504 if (clone->tech->hangup)
3505 res = clone->tech->hangup(clone);
3506 if (res) {
3507 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
3508 ast_channel_unlock(clone);
3509 return -1;
3512 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3513 /* Mangle the name of the clone channel */
3514 ast_string_field_set(clone, name, zombn);
3515 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3517 /* Update the type. */
3518 t_pvt = original->monitor;
3519 original->monitor = clone->monitor;
3520 clone->monitor = t_pvt;
3522 /* Keep the same language. */
3523 ast_string_field_set(original, language, clone->language);
3524 /* Copy the FD's other than the generator fd */
3525 for (x = 0; x < AST_MAX_FDS; x++) {
3526 if (x != AST_GENERATOR_FD)
3527 original->fds[x] = clone->fds[x];
3530 ast_app_group_update(clone, original);
3531 /* Move data stores over */
3532 if (AST_LIST_FIRST(&clone->datastores)) {
3533 struct ast_datastore *ds;
3534 AST_LIST_APPEND_LIST(&original->datastores, &clone->datastores, entry);
3535 AST_LIST_TRAVERSE(&original->datastores, ds, entry) {
3536 if (ds->info->chan_fixup)
3537 ds->info->chan_fixup(ds->data, clone, original);
3541 clone_variables(original, clone);
3542 /* Presense of ADSI capable CPE follows clone */
3543 original->adsicpe = clone->adsicpe;
3544 /* Bridge remains the same */
3545 /* CDR fields remain the same */
3546 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3547 /* Application and data remain the same */
3548 /* Clone exception becomes real one, as with fdno */
3549 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3550 original->fdno = clone->fdno;
3551 /* Schedule context remains the same */
3552 /* Stream stuff stays the same */
3553 /* Keep the original state. The fixup code will need to work with it most likely */
3555 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3556 out. */
3557 tmpcid = original->cid;
3558 original->cid = clone->cid;
3559 clone->cid = tmpcid;
3561 /* Restore original timing file descriptor */
3562 original->fds[AST_TIMING_FD] = original->timingfd;
3564 /* Our native formats are different now */
3565 original->nativeformats = clone->nativeformats;
3567 /* Context, extension, priority, app data, jump table, remain the same */
3568 /* pvt switches. pbx stays the same, as does next */
3570 /* Set the write format */
3571 ast_set_write_format(original, wformat);
3573 /* Set the read format */
3574 ast_set_read_format(original, rformat);
3576 /* Copy the music class */
3577 ast_string_field_set(original, musicclass, clone->musicclass);
3579 if (option_debug)
3580 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3582 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3583 can fix up everything as best as possible */
3584 if (original->tech->fixup) {
3585 res = original->tech->fixup(clone, original);
3586 if (res) {
3587 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3588 original->tech->type, original->name);
3589 ast_channel_unlock(clone);
3590 return -1;
3592 } else
3593 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3594 original->tech->type, original->name);
3596 /* If an indication is currently playing maintain it on the channel that is taking the place of original */
3597 if (original->visible_indication)
3598 ast_indicate(original, original->visible_indication);
3600 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3601 a zombie so nothing tries to touch it. If it's already been marked as a
3602 zombie, then free it now (since it already is considered invalid). */
3603 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3604 if (option_debug)
3605 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3606 ast_channel_unlock(clone);
3607 manager_event(EVENT_FLAG_CALL, "Hangup",
3608 "Channel: %s\r\n"
3609 "Uniqueid: %s\r\n"
3610 "Cause: %d\r\n"
3611 "Cause-txt: %s\r\n",
3612 clone->name,
3613 clone->uniqueid,
3614 clone->hangupcause,
3615 ast_cause2str(clone->hangupcause)
3617 ast_channel_free(clone);
3618 } else {
3619 if (option_debug)
3620 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3621 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3622 ast_queue_frame(clone, &ast_null_frame);
3623 ast_channel_unlock(clone);
3626 /* Signal any blocker */
3627 if (ast_test_flag(original, AST_FLAG_BLOCKING))
3628 pthread_kill(original->blocker, SIGURG);
3629 if (option_debug)
3630 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3631 return 0;
3634 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3636 ast_channel_lock(chan);
3638 if (callerid) {
3639 if (chan->cid.cid_num)
3640 free(chan->cid.cid_num);
3641 chan->cid.cid_num = ast_strdup(callerid);
3643 if (calleridname) {
3644 if (chan->cid.cid_name)
3645 free(chan->cid.cid_name);
3646 chan->cid.cid_name = ast_strdup(calleridname);
3648 if (ani) {
3649 if (chan->cid.cid_ani)
3650 free(chan->cid.cid_ani);
3651 chan->cid.cid_ani = ast_strdup(ani);
3653 manager_event(EVENT_FLAG_CALL, "Newcallerid",
3654 "Channel: %s\r\n"
3655 "CallerID: %s\r\n"
3656 "CallerIDName: %s\r\n"
3657 "Uniqueid: %s\r\n"
3658 "CID-CallingPres: %d (%s)\r\n",
3659 chan->name,
3660 S_OR(chan->cid.cid_num, "<Unknown>"),
3661 S_OR(chan->cid.cid_name, "<Unknown>"),
3662 chan->uniqueid,
3663 chan->cid.cid_pres,
3664 ast_describe_caller_presentation(chan->cid.cid_pres)
3667 ast_channel_unlock(chan);
3670 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
3672 int oldstate = chan->_state;
3674 if (oldstate == state)
3675 return 0;
3677 chan->_state = state;
3678 ast_device_state_changed_literal(chan->name);
3679 /* setstate used to conditionally report Newchannel; this is no more */
3680 manager_event(EVENT_FLAG_CALL,
3681 "Newstate",
3682 "Channel: %s\r\n"
3683 "State: %s\r\n"
3684 "CallerID: %s\r\n"
3685 "CallerIDName: %s\r\n"
3686 "Uniqueid: %s\r\n",
3687 chan->name, ast_state2str(chan->_state),
3688 S_OR(chan->cid.cid_num, "<unknown>"),
3689 S_OR(chan->cid.cid_name, "<unknown>"),
3690 chan->uniqueid);
3692 return 0;
3695 /*! \brief Find bridged channel */
3696 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3698 struct ast_channel *bridged;
3699 bridged = chan->_bridge;
3700 if (bridged && bridged->tech->bridged_channel)
3701 bridged = bridged->tech->bridged_channel(chan, bridged);
3702 return bridged;
3705 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3707 int min = 0, sec = 0, check;
3709 check = ast_autoservice_start(peer);
3710 if (check)
3711 return;
3713 if (remain > 0) {
3714 if (remain / 60 > 1) {
3715 min = remain / 60;
3716 sec = remain % 60;
3717 } else {
3718 sec = remain;
3722 if (!strcmp(sound,"timeleft")) { /* Queue support */
3723 ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
3724 if (min) {
3725 ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
3726 ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
3728 if (sec) {
3729 ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
3730 ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
3732 } else {
3733 ast_stream_and_wait(chan, sound, chan->language, "");
3736 ast_autoservice_stop(peer);
3739 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3740 struct ast_bridge_config *config, struct ast_frame **fo,
3741 struct ast_channel **rc, struct timeval bridge_end)
3743 /* Copy voice back and forth between the two channels. */
3744 struct ast_channel *cs[3];
3745 struct ast_frame *f;
3746 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3747 int o0nativeformats;
3748 int o1nativeformats;
3749 int watch_c0_dtmf;
3750 int watch_c1_dtmf;
3751 void *pvt0, *pvt1;
3752 /* Indicates whether a frame was queued into a jitterbuffer */
3753 int frame_put_in_jb = 0;
3754 int jb_in_use;
3755 int to;
3757 cs[0] = c0;
3758 cs[1] = c1;
3759 pvt0 = c0->tech_pvt;
3760 pvt1 = c1->tech_pvt;
3761 o0nativeformats = c0->nativeformats;
3762 o1nativeformats = c1->nativeformats;
3763 watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3764 watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3766 /* Check the need of a jitterbuffer for each channel */
3767 jb_in_use = ast_jb_do_usecheck(c0, c1);
3769 for (;;) {
3770 struct ast_channel *who, *other;
3772 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3773 (o0nativeformats != c0->nativeformats) ||
3774 (o1nativeformats != c1->nativeformats)) {
3775 /* Check for Masquerade, codec changes, etc */
3776 res = AST_BRIDGE_RETRY;
3777 break;
3779 if (bridge_end.tv_sec) {
3780 to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3781 if (to <= 0) {
3782 if (config->timelimit)
3783 res = AST_BRIDGE_RETRY;
3784 else
3785 res = AST_BRIDGE_COMPLETE;
3786 break;
3788 } else
3789 to = -1;
3790 /* Calculate the appropriate max sleep interval - in general, this is the time,
3791 left to the closest jb delivery moment */
3792 if (jb_in_use)
3793 to = ast_jb_get_when_to_wakeup(c0, c1, to);
3794 who = ast_waitfor_n(cs, 2, &to);
3795 if (!who) {
3796 /* No frame received within the specified timeout - check if we have to deliver now */
3797 if (jb_in_use)
3798 ast_jb_get_and_deliver(c0, c1);
3799 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3800 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3801 c0->_softhangup = 0;
3802 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3803 c1->_softhangup = 0;
3804 c0->_bridge = c1;
3805 c1->_bridge = c0;
3807 continue;
3809 f = ast_read(who);
3810 if (!f) {
3811 *fo = NULL;
3812 *rc = who;
3813 if (option_debug)
3814 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3815 break;
3818 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3819 /* Try add the frame info the who's bridged channel jitterbuff */
3820 if (jb_in_use)
3821 frame_put_in_jb = !ast_jb_put(other, f);
3823 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3824 int bridge_exit = 0;
3826 switch (f->subclass) {
3827 case AST_CONTROL_HOLD:
3828 case AST_CONTROL_UNHOLD:
3829 case AST_CONTROL_VIDUPDATE:
3830 case AST_CONTROL_SRCUPDATE:
3831 ast_indicate_data(other, f->subclass, f->data, f->datalen);
3832 break;
3833 default:
3834 *fo = f;
3835 *rc = who;
3836 bridge_exit = 1;
3837 if (option_debug)
3838 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3839 break;
3841 if (bridge_exit)
3842 break;
3844 if ((f->frametype == AST_FRAME_VOICE) ||
3845 (f->frametype == AST_FRAME_DTMF_BEGIN) ||
3846 (f->frametype == AST_FRAME_DTMF) ||
3847 (f->frametype == AST_FRAME_VIDEO) ||
3848 (f->frametype == AST_FRAME_IMAGE) ||
3849 (f->frametype == AST_FRAME_HTML) ||
3850 (f->frametype == AST_FRAME_MODEM) ||
3851 (f->frametype == AST_FRAME_TEXT)) {
3852 /* monitored dtmf causes exit from bridge */
3853 int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
3855 if (monitored_source &&
3856 (f->frametype == AST_FRAME_DTMF_END ||
3857 f->frametype == AST_FRAME_DTMF_BEGIN)) {
3858 *fo = f;
3859 *rc = who;
3860 if (option_debug)
3861 ast_log(LOG_DEBUG, "Got DTMF %s on channel (%s)\n",
3862 f->frametype == AST_FRAME_DTMF_END ? "end" : "begin",
3863 who->name);
3864 break;
3866 /* Write immediately frames, not passed through jb */
3867 if (!frame_put_in_jb)
3868 ast_write(other, f);
3870 /* Check if we have to deliver now */
3871 if (jb_in_use)
3872 ast_jb_get_and_deliver(c0, c1);
3874 /* XXX do we want to pass on also frames not matched above ? */
3875 ast_frfree(f);
3877 /* Swap who gets priority */
3878 cs[2] = cs[0];
3879 cs[0] = cs[1];
3880 cs[1] = cs[2];
3882 return res;
3885 /*! \brief Bridge two channels together */
3886 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3887 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
3889 struct ast_channel *who = NULL;
3890 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3891 int nativefailed=0;
3892 int firstpass;
3893 int o0nativeformats;
3894 int o1nativeformats;
3895 long time_left_ms=0;
3896 struct timeval nexteventts = { 0, };
3897 char caller_warning = 0;
3898 char callee_warning = 0;
3900 if (c0->_bridge) {
3901 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3902 c0->name, c0->_bridge->name);
3903 return -1;
3905 if (c1->_bridge) {
3906 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3907 c1->name, c1->_bridge->name);
3908 return -1;
3911 /* Stop if we're a zombie or need a soft hangup */
3912 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3913 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3914 return -1;
3916 *fo = NULL;
3917 firstpass = config->firstpass;
3918 config->firstpass = 0;
3920 if (ast_tvzero(config->start_time))
3921 config->start_time = ast_tvnow();
3922 time_left_ms = config->timelimit;
3924 caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3925 callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3927 if (config->start_sound && firstpass) {
3928 if (caller_warning)
3929 bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3930 if (callee_warning)
3931 bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3934 /* Keep track of bridge */
3935 c0->_bridge = c1;
3936 c1->_bridge = c0;
3938 /* \todo XXX here should check that cid_num is not NULL */
3939 manager_event(EVENT_FLAG_CALL, "Link",
3940 "Channel1: %s\r\n"
3941 "Channel2: %s\r\n"
3942 "Uniqueid1: %s\r\n"
3943 "Uniqueid2: %s\r\n"
3944 "CallerID1: %s\r\n"
3945 "CallerID2: %s\r\n",
3946 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3948 o0nativeformats = c0->nativeformats;
3949 o1nativeformats = c1->nativeformats;
3951 if (config->feature_timer) {
3952 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->feature_timer, 1000));
3953 } else if (config->timelimit) {
3954 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3955 if (caller_warning || callee_warning)
3956 nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
3959 if (!c0->tech->send_digit_begin)
3960 ast_set_flag(c1, AST_FLAG_END_DTMF_ONLY);
3961 if (!c1->tech->send_digit_begin)
3962 ast_set_flag(c0, AST_FLAG_END_DTMF_ONLY);
3964 /* Before we enter in and bridge these two together tell them both the source of audio has changed */
3965 ast_indicate(c0, AST_CONTROL_SRCUPDATE);
3966 ast_indicate(c1, AST_CONTROL_SRCUPDATE);
3968 for (/* ever */;;) {
3969 struct timeval now = { 0, };
3970 int to;
3972 to = -1;
3974 if (!ast_tvzero(nexteventts)) {
3975 now = ast_tvnow();
3976 to = ast_tvdiff_ms(nexteventts, now);
3977 if (to <= 0) {
3978 if (!config->timelimit) {
3979 res = AST_BRIDGE_COMPLETE;
3980 break;
3982 to = 0;
3986 if (config->timelimit) {
3987 time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
3988 if (time_left_ms < to)
3989 to = time_left_ms;
3991 if (time_left_ms <= 0) {
3992 if (caller_warning && config->end_sound)
3993 bridge_playfile(c0, c1, config->end_sound, 0);
3994 if (callee_warning && config->end_sound)
3995 bridge_playfile(c1, c0, config->end_sound, 0);
3996 *fo = NULL;
3997 if (who)
3998 *rc = who;
3999 res = 0;
4000 break;
4003 if (!to) {
4004 if (time_left_ms >= 5000 && config->warning_sound && config->play_warning) {
4005 int t = (time_left_ms + 500) / 1000; /* round to nearest second */
4006 if (caller_warning)
4007 bridge_playfile(c0, c1, config->warning_sound, t);
4008 if (callee_warning)
4009 bridge_playfile(c1, c0, config->warning_sound, t);
4011 if (config->warning_freq && (time_left_ms > (config->warning_freq + 5000)))
4012 nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
4013 else
4014 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
4018 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
4019 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4020 c0->_softhangup = 0;
4021 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4022 c1->_softhangup = 0;
4023 c0->_bridge = c1;
4024 c1->_bridge = c0;
4025 if (option_debug)
4026 ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
4027 continue;
4030 /* Stop if we're a zombie or need a soft hangup */
4031 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
4032 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
4033 *fo = NULL;
4034 if (who)
4035 *rc = who;
4036 res = 0;
4037 if (option_debug)
4038 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",
4039 c0->name, c1->name,
4040 ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
4041 ast_check_hangup(c0) ? "Yes" : "No",
4042 ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
4043 ast_check_hangup(c1) ? "Yes" : "No");
4044 break;
4047 /* See if the BRIDGEPEER variable needs to be updated */
4048 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER")))
4049 pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1->name);
4050 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER")))
4051 pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0->name);
4053 if (c0->tech->bridge &&
4054 (config->timelimit == 0) &&
4055 (c0->tech->bridge == c1->tech->bridge) &&
4056 !nativefailed && !c0->monitor && !c1->monitor &&
4057 !c0->audiohooks && !c1->audiohooks && !ast_test_flag(&(config->features_callee),AST_FEATURE_REDIRECT) &&
4058 !ast_test_flag(&(config->features_caller),AST_FEATURE_REDIRECT) &&
4059 !c0->masq && !c0->masqr && !c1->masq && !c1->masqr) {
4060 /* Looks like they share a bridge method and nothing else is in the way */
4061 ast_set_flag(c0, AST_FLAG_NBRIDGE);
4062 ast_set_flag(c1, AST_FLAG_NBRIDGE);
4063 if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, to)) == AST_BRIDGE_COMPLETE) {
4064 /* \todo XXX here should check that cid_num is not NULL */
4065 manager_event(EVENT_FLAG_CALL, "Unlink",
4066 "Channel1: %s\r\n"
4067 "Channel2: %s\r\n"
4068 "Uniqueid1: %s\r\n"
4069 "Uniqueid2: %s\r\n"
4070 "CallerID1: %s\r\n"
4071 "CallerID2: %s\r\n",
4072 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4073 if (option_debug)
4074 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
4076 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
4077 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
4079 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4080 continue;
4082 c0->_bridge = NULL;
4083 c1->_bridge = NULL;
4085 return res;
4086 } else {
4087 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
4088 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
4090 switch (res) {
4091 case AST_BRIDGE_RETRY:
4092 continue;
4093 default:
4094 if (option_verbose > 2)
4095 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s ended\n",
4096 c0->name, c1->name);
4097 /* fallthrough */
4098 case AST_BRIDGE_FAILED_NOWARN:
4099 nativefailed++;
4100 break;
4104 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
4105 (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
4106 !(c0->generator || c1->generator)) {
4107 if (ast_channel_make_compatible(c0, c1)) {
4108 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
4109 /* \todo XXX here should check that cid_num is not NULL */
4110 manager_event(EVENT_FLAG_CALL, "Unlink",
4111 "Channel1: %s\r\n"
4112 "Channel2: %s\r\n"
4113 "Uniqueid1: %s\r\n"
4114 "Uniqueid2: %s\r\n"
4115 "CallerID1: %s\r\n"
4116 "CallerID2: %s\r\n",
4117 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4118 return AST_BRIDGE_FAILED;
4120 o0nativeformats = c0->nativeformats;
4121 o1nativeformats = c1->nativeformats;
4124 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER")))
4125 pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1->name);
4126 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER")))
4127 pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0->name);
4129 res = ast_generic_bridge(c0, c1, config, fo, rc, nexteventts);
4130 if (res != AST_BRIDGE_RETRY)
4131 break;
4134 ast_clear_flag(c0, AST_FLAG_END_DTMF_ONLY);
4135 ast_clear_flag(c1, AST_FLAG_END_DTMF_ONLY);
4137 /* Now that we have broken the bridge the source will change yet again */
4138 ast_indicate(c0, AST_CONTROL_SRCUPDATE);
4139 ast_indicate(c1, AST_CONTROL_SRCUPDATE);
4141 c0->_bridge = NULL;
4142 c1->_bridge = NULL;
4144 /* \todo XXX here should check that cid_num is not NULL */
4145 manager_event(EVENT_FLAG_CALL, "Unlink",
4146 "Channel1: %s\r\n"
4147 "Channel2: %s\r\n"
4148 "Uniqueid1: %s\r\n"
4149 "Uniqueid2: %s\r\n"
4150 "CallerID1: %s\r\n"
4151 "CallerID2: %s\r\n",
4152 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4153 if (option_debug)
4154 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
4156 return res;
4159 /*! \brief Sets an option on a channel */
4160 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
4162 int res;
4164 if (chan->tech->setoption) {
4165 res = chan->tech->setoption(chan, option, data, datalen);
4166 if (res < 0)
4167 return res;
4168 } else {
4169 errno = ENOSYS;
4170 return -1;
4172 if (block) {
4173 /* XXX Implement blocking -- just wait for our option frame reply, discarding
4174 intermediate packets. XXX */
4175 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
4176 return -1;
4178 return 0;
4181 struct tonepair_def {
4182 int freq1;
4183 int freq2;
4184 int duration;
4185 int vol;
4188 struct tonepair_state {
4189 int fac1;
4190 int fac2;
4191 int v1_1;
4192 int v2_1;
4193 int v3_1;
4194 int v1_2;
4195 int v2_2;
4196 int v3_2;
4197 int origwfmt;
4198 int pos;
4199 int duration;
4200 int modulate;
4201 struct ast_frame f;
4202 unsigned char offset[AST_FRIENDLY_OFFSET];
4203 short data[4000];
4206 static void tonepair_release(struct ast_channel *chan, void *params)
4208 struct tonepair_state *ts = params;
4210 if (chan)
4211 ast_set_write_format(chan, ts->origwfmt);
4212 free(ts);
4215 static void *tonepair_alloc(struct ast_channel *chan, void *params)
4217 struct tonepair_state *ts;
4218 struct tonepair_def *td = params;
4220 if (!(ts = ast_calloc(1, sizeof(*ts))))
4221 return NULL;
4222 ts->origwfmt = chan->writeformat;
4223 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
4224 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
4225 tonepair_release(NULL, ts);
4226 ts = NULL;
4227 } else {
4228 ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
4229 ts->v1_1 = 0;
4230 ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4231 ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4232 ts->v2_1 = 0;
4233 ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
4234 ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4235 ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4236 ts->duration = td->duration;
4237 ts->modulate = 0;
4239 /* Let interrupts interrupt :) */
4240 ast_set_flag(chan, AST_FLAG_WRITE_INT);
4241 return ts;
4244 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
4246 struct tonepair_state *ts = data;
4247 int x;
4249 /* we need to prepare a frame with 16 * timelen samples as we're
4250 * generating SLIN audio
4252 len = samples * 2;
4254 if (len > sizeof(ts->data) / 2 - 1) {
4255 ast_log(LOG_WARNING, "Can't generate that much data!\n");
4256 return -1;
4258 memset(&ts->f, 0, sizeof(ts->f));
4259 for (x=0;x<len/2;x++) {
4260 ts->v1_1 = ts->v2_1;
4261 ts->v2_1 = ts->v3_1;
4262 ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;
4264 ts->v1_2 = ts->v2_2;
4265 ts->v2_2 = ts->v3_2;
4266 ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
4267 if (ts->modulate) {
4268 int p;
4269 p = ts->v3_2 - 32768;
4270 if (p < 0) p = -p;
4271 p = ((p * 9) / 10) + 1;
4272 ts->data[x] = (ts->v3_1 * p) >> 15;
4273 } else
4274 ts->data[x] = ts->v3_1 + ts->v3_2;
4276 ts->f.frametype = AST_FRAME_VOICE;
4277 ts->f.subclass = AST_FORMAT_SLINEAR;
4278 ts->f.datalen = len;
4279 ts->f.samples = samples;
4280 ts->f.offset = AST_FRIENDLY_OFFSET;
4281 ts->f.data = ts->data;
4282 ast_write(chan, &ts->f);
4283 ts->pos += x;
4284 if (ts->duration > 0) {
4285 if (ts->pos >= ts->duration * 8)
4286 return -1;
4288 return 0;
4291 static struct ast_generator tonepair = {
4292 alloc: tonepair_alloc,
4293 release: tonepair_release,
4294 generate: tonepair_generator,
4297 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4299 struct tonepair_def d = { 0, };
4301 d.freq1 = freq1;
4302 d.freq2 = freq2;
4303 d.duration = duration;
4304 d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
4305 if (ast_activate_generator(chan, &tonepair, &d))
4306 return -1;
4307 return 0;
4310 void ast_tonepair_stop(struct ast_channel *chan)
4312 ast_deactivate_generator(chan);
4315 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4317 int res;
4319 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
4320 return res;
4322 /* Give us some wiggle room */
4323 while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
4324 struct ast_frame *f = ast_read(chan);
4325 if (f)
4326 ast_frfree(f);
4327 else
4328 return -1;
4330 return 0;
4333 ast_group_t ast_get_group(const char *s)
4335 char *piece;
4336 char *c;
4337 int start=0, finish=0, x;
4338 ast_group_t group = 0;
4340 if (ast_strlen_zero(s))
4341 return 0;
4343 c = ast_strdupa(s);
4345 while ((piece = strsep(&c, ","))) {
4346 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
4347 /* Range */
4348 } else if (sscanf(piece, "%d", &start)) {
4349 /* Just one */
4350 finish = start;
4351 } else {
4352 ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
4353 continue;
4355 for (x = start; x <= finish; x++) {
4356 if ((x > 63) || (x < 0)) {
4357 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
4358 } else
4359 group |= ((ast_group_t) 1 << x);
4362 return group;
4365 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
4366 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
4367 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
4369 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
4370 void (*stop_ptr)(struct ast_channel *),
4371 void (*cleanup_ptr)(struct ast_channel *))
4373 ast_moh_start_ptr = start_ptr;
4374 ast_moh_stop_ptr = stop_ptr;
4375 ast_moh_cleanup_ptr = cleanup_ptr;
4378 void ast_uninstall_music_functions(void)
4380 ast_moh_start_ptr = NULL;
4381 ast_moh_stop_ptr = NULL;
4382 ast_moh_cleanup_ptr = NULL;
4385 /*! \brief Turn on music on hold on a given channel */
4386 int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
4388 if (ast_moh_start_ptr)
4389 return ast_moh_start_ptr(chan, mclass, interpclass);
4391 if (option_verbose > 2) {
4392 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n",
4393 mclass ? mclass : (interpclass ? interpclass : "default"));
4396 return 0;
4399 /*! \brief Turn off music on hold on a given channel */
4400 void ast_moh_stop(struct ast_channel *chan)
4402 if (ast_moh_stop_ptr)
4403 ast_moh_stop_ptr(chan);
4406 void ast_moh_cleanup(struct ast_channel *chan)
4408 if (ast_moh_cleanup_ptr)
4409 ast_moh_cleanup_ptr(chan);
4412 void ast_channels_init(void)
4414 ast_cli_register_multiple(cli_channel, sizeof(cli_channel) / sizeof(struct ast_cli_entry));
4417 /*! \brief Print call group and pickup group ---*/
4418 char *ast_print_group(char *buf, int buflen, ast_group_t group)
4420 unsigned int i;
4421 int first=1;
4422 char num[3];
4424 buf[0] = '\0';
4426 if (!group) /* Return empty string if no group */
4427 return buf;
4429 for (i = 0; i <= 63; i++) { /* Max group is 63 */
4430 if (group & ((ast_group_t) 1 << i)) {
4431 if (!first) {
4432 strncat(buf, ", ", buflen - strlen(buf) - 1);
4433 } else {
4434 first=0;
4436 snprintf(num, sizeof(num), "%u", i);
4437 strncat(buf, num, buflen - strlen(buf) - 1);
4440 return buf;
4443 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
4445 struct ast_variable *cur;
4447 for (cur = vars; cur; cur = cur->next)
4448 pbx_builtin_setvar_helper(chan, cur->name, cur->value);
4451 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
4453 /* just store the data pointer in the channel structure */
4454 return data;
4457 static void silence_generator_release(struct ast_channel *chan, void *data)
4459 /* nothing to do */
4462 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
4464 short buf[samples];
4465 struct ast_frame frame = {
4466 .frametype = AST_FRAME_VOICE,
4467 .subclass = AST_FORMAT_SLINEAR,
4468 .data = buf,
4469 .samples = samples,
4470 .datalen = sizeof(buf),
4472 memset(buf, 0, sizeof(buf));
4473 if (ast_write(chan, &frame))
4474 return -1;
4475 return 0;
4478 static struct ast_generator silence_generator = {
4479 .alloc = silence_generator_alloc,
4480 .release = silence_generator_release,
4481 .generate = silence_generator_generate,
4484 struct ast_silence_generator {
4485 int old_write_format;
4488 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
4490 struct ast_silence_generator *state;
4492 if (!(state = ast_calloc(1, sizeof(*state)))) {
4493 return NULL;
4496 state->old_write_format = chan->writeformat;
4498 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
4499 ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
4500 free(state);
4501 return NULL;
4504 ast_activate_generator(chan, &silence_generator, state);
4506 if (option_debug)
4507 ast_log(LOG_DEBUG, "Started silence generator on '%s'\n", chan->name);
4509 return state;
4512 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
4514 if (!state)
4515 return;
4517 ast_deactivate_generator(chan);
4519 if (option_debug)
4520 ast_log(LOG_DEBUG, "Stopped silence generator on '%s'\n", chan->name);
4522 if (ast_set_write_format(chan, state->old_write_format) < 0)
4523 ast_log(LOG_ERROR, "Could not return write format to its original state\n");
4525 free(state);
4529 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
4530 const char *channelreloadreason2txt(enum channelreloadreason reason)
4532 switch (reason) {
4533 case CHANNEL_MODULE_LOAD:
4534 return "LOAD (Channel module load)";
4536 case CHANNEL_MODULE_RELOAD:
4537 return "RELOAD (Channel module reload)";
4539 case CHANNEL_CLI_RELOAD:
4540 return "CLIRELOAD (Channel module reload by CLI command)";
4542 default:
4543 return "MANAGERRELOAD (Channel module reload by manager)";
4547 #ifdef DEBUG_CHANNEL_LOCKS
4549 /*! \brief Unlock AST channel (and print debugging output)
4550 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
4552 int __ast_channel_unlock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
4554 int res = 0;
4555 if (option_debug > 2)
4556 ast_log(LOG_DEBUG, "::::==== Unlocking AST channel %s\n", chan->name);
4558 if (!chan) {
4559 if (option_debug)
4560 ast_log(LOG_DEBUG, "::::==== Unlocking non-existing channel \n");
4561 return 0;
4563 #ifdef DEBUG_THREADS
4564 res = __ast_pthread_mutex_unlock(filename, lineno, func, "(channel lock)", &chan->lock);
4565 #else
4566 res = ast_mutex_unlock(&chan->lock);
4567 #endif
4569 if (option_debug > 2) {
4570 #ifdef DEBUG_THREADS
4571 int count = 0;
4572 if ((count = chan->lock.reentrancy))
4573 ast_log(LOG_DEBUG, ":::=== Still have %d locks (recursive)\n", count);
4574 #endif
4575 if (!res)
4576 if (option_debug)
4577 ast_log(LOG_DEBUG, "::::==== Channel %s was unlocked\n", chan->name);
4578 if (res == EINVAL) {
4579 if (option_debug)
4580 ast_log(LOG_DEBUG, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan->name);
4583 if (res == EPERM) {
4584 /* We had no lock, so okay any way*/
4585 if (option_debug > 3)
4586 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked at all \n", chan->name);
4587 res = 0;
4589 return res;
4592 /*! \brief Lock AST channel (and print debugging output)
4593 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4594 int __ast_channel_lock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
4596 int res;
4598 if (option_debug > 3)
4599 ast_log(LOG_DEBUG, "====:::: Locking AST channel %s\n", chan->name);
4601 #ifdef DEBUG_THREADS
4602 res = __ast_pthread_mutex_lock(filename, lineno, func, "(channel lock)", &chan->lock);
4603 #else
4604 res = ast_mutex_lock(&chan->lock);
4605 #endif
4607 if (option_debug > 3) {
4608 #ifdef DEBUG_THREADS
4609 int count = 0;
4610 if ((count = chan->lock.reentrancy))
4611 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4612 #endif
4613 if (!res)
4614 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4615 if (res == EDEADLK) {
4616 /* We had no lock, so okey any way */
4617 if (option_debug > 3)
4618 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan->name);
4620 if (res == EINVAL) {
4621 if (option_debug > 3)
4622 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4625 return res;
4628 /*! \brief Lock AST channel (and print debugging output)
4629 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4630 int __ast_channel_trylock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
4632 int res;
4634 if (option_debug > 2)
4635 ast_log(LOG_DEBUG, "====:::: Trying to lock AST channel %s\n", chan->name);
4636 #ifdef DEBUG_THREADS
4637 res = __ast_pthread_mutex_trylock(filename, lineno, func, "(channel lock)", &chan->lock);
4638 #else
4639 res = ast_mutex_trylock(&chan->lock);
4640 #endif
4642 if (option_debug > 2) {
4643 #ifdef DEBUG_THREADS
4644 int count = 0;
4645 if ((count = chan->lock.reentrancy))
4646 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4647 #endif
4648 if (!res)
4649 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4650 if (res == EBUSY) {
4651 /* We failed to lock */
4652 if (option_debug > 2)
4653 ast_log(LOG_DEBUG, "::::==== Channel %s failed to lock. Not waiting around...\n", chan->name);
4655 if (res == EDEADLK) {
4656 /* We had no lock, so okey any way*/
4657 if (option_debug > 2)
4658 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan->name);
4660 if (res == EINVAL && option_debug > 2)
4661 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4663 return res;
4666 #endif
4669 * Wrappers for various ast_say_*() functions that call the full version
4670 * of the same functions.
4671 * The proper place would be say.c, but that file is optional and one
4672 * must be able to build asterisk even without it (using a loadable 'say'
4673 * implementation that only supplies the 'full' version of the functions.
4676 int ast_say_number(struct ast_channel *chan, int num,
4677 const char *ints, const char *language, const char *options)
4679 return ast_say_number_full(chan, num, ints, language, options, -1, -1);
4682 int ast_say_enumeration(struct ast_channel *chan, int num,
4683 const char *ints, const char *language, const char *options)
4685 return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
4688 int ast_say_digits(struct ast_channel *chan, int num,
4689 const char *ints, const char *lang)
4691 return ast_say_digits_full(chan, num, ints, lang, -1, -1);
4694 int ast_say_digit_str(struct ast_channel *chan, const char *str,
4695 const char *ints, const char *lang)
4697 return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
4700 int ast_say_character_str(struct ast_channel *chan, const char *str,
4701 const char *ints, const char *lang)
4703 return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
4706 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
4707 const char *ints, const char *lang)
4709 return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
4712 int ast_say_digits_full(struct ast_channel *chan, int num,
4713 const char *ints, const char *lang, int audiofd, int ctrlfd)
4715 char buf[256];
4717 snprintf(buf, sizeof(buf), "%d", num);
4718 return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);