when a PRI call must be moved to a different B channel at the request of the other...
[asterisk-bristuff.git] / main / channel.c
blob16881a3d5575c23f82ec36de88cf333bfd782016
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 #ifdef HAVE_ZAPTEL
41 #include <sys/ioctl.h>
42 #include <zaptel/zaptel.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_ZAPTEL
746 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
747 if (tmp->timingfd > -1) {
748 /* Check if timing interface supports new
749 ping/pong scheme */
750 flags = 1;
751 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
752 needqueue = 0;
754 #else
755 tmp->timingfd = -1;
756 #endif
758 if (needqueue) {
759 if (pipe(tmp->alertpipe)) {
760 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
761 #ifdef HAVE_ZAPTEL
762 if (tmp->timingfd > -1)
763 close(tmp->timingfd);
764 #endif
765 sched_context_destroy(tmp->sched);
766 ast_string_field_free_memory(tmp);
767 free(tmp);
768 return NULL;
769 } else {
770 flags = fcntl(tmp->alertpipe[0], F_GETFL);
771 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
772 flags = fcntl(tmp->alertpipe[1], F_GETFL);
773 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
775 } else /* Make sure we've got it done right if they don't */
776 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
778 /* Always watch the alertpipe */
779 tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
780 /* And timing pipe */
781 tmp->fds[AST_TIMING_FD] = tmp->timingfd;
782 ast_string_field_set(tmp, name, "**Unknown**");
784 /* Initial state */
785 tmp->_state = state;
787 tmp->streamid = -1;
789 tmp->fin = global_fin;
790 tmp->fout = global_fout;
792 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
793 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
794 ast_atomic_fetchadd_int(&uniqueint, 1));
795 } else {
796 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
797 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
800 tmp->cid.cid_name = ast_strdup(cid_name);
801 tmp->cid.cid_num = ast_strdup(cid_num);
803 if (!ast_strlen_zero(name_fmt)) {
804 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
805 * And they all use slightly different formats for their name string.
806 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
807 * This means, that the stringfields must have a routine that takes the va_lists directly, and
808 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
809 * This new function was written so this can be accomplished.
811 va_start(ap1, name_fmt);
812 va_start(ap2, name_fmt);
813 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
814 va_end(ap1);
815 va_end(ap2);
818 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
820 /* These 4 variables need to be set up for the cdr_init() to work right */
821 if (amaflag)
822 tmp->amaflags = amaflag;
823 else
824 tmp->amaflags = ast_default_amaflags;
826 if (!ast_strlen_zero(acctcode))
827 ast_string_field_set(tmp, accountcode, acctcode);
828 else
829 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
831 if (!ast_strlen_zero(context))
832 ast_copy_string(tmp->context, context, sizeof(tmp->context));
833 else
834 strcpy(tmp->context, "default");
836 if (!ast_strlen_zero(exten))
837 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
838 else
839 strcpy(tmp->exten, "s");
841 tmp->priority = 1;
843 tmp->cdr = ast_cdr_alloc();
844 ast_cdr_init(tmp->cdr, tmp);
845 ast_cdr_start(tmp->cdr);
847 headp = &tmp->varshead;
848 AST_LIST_HEAD_INIT_NOLOCK(headp);
850 ast_mutex_init(&tmp->lock);
852 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
854 ast_string_field_set(tmp, language, defaultlanguage);
856 tmp->tech = &null_tech;
858 AST_LIST_LOCK(&channels);
859 AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
860 AST_LIST_UNLOCK(&channels);
862 /*\!note
863 * and now, since the channel structure is built, and has its name, let's
864 * call the manager event generator with this Newchannel event. This is the
865 * proper and correct place to make this call, but you sure do have to pass
866 * a lot of data into this func to do it here!
868 if (!ast_strlen_zero(name_fmt)) {
869 manager_event(EVENT_FLAG_CALL, "Newchannel",
870 "Channel: %s\r\n"
871 "State: %s\r\n"
872 "CallerIDNum: %s\r\n"
873 "CallerIDName: %s\r\n"
874 "Uniqueid: %s\r\n",
875 tmp->name, ast_state2str(state),
876 S_OR(cid_num, "<unknown>"),
877 S_OR(cid_name, "<unknown>"),
878 tmp->uniqueid);
881 return tmp;
884 /*! \brief Queue an outgoing media frame */
885 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
887 struct ast_frame *f;
888 struct ast_frame *cur;
889 int blah = 1;
890 int qlen = 0;
892 /* Build us a copy and free the original one */
893 if (!(f = ast_frdup(fin))) {
894 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
895 return -1;
897 ast_channel_lock(chan);
899 /* See if the last frame on the queue is a hangup, if so don't queue anything */
900 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
901 ast_frfree(f);
902 ast_channel_unlock(chan);
903 return 0;
906 /* Count how many frames exist on the queue */
907 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
908 qlen++;
911 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
912 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
913 if (fin->frametype != AST_FRAME_VOICE) {
914 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
915 CRASH;
916 } else {
917 if (option_debug)
918 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
919 ast_frfree(f);
920 ast_channel_unlock(chan);
921 return 0;
924 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
925 if (chan->alertpipe[1] > -1) {
926 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
927 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
928 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
929 #ifdef HAVE_ZAPTEL
930 } else if (chan->timingfd > -1) {
931 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
932 #endif
933 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
934 pthread_kill(chan->blocker, SIGURG);
936 ast_channel_unlock(chan);
937 return 0;
940 /*! \brief Queue a hangup frame for channel */
941 int ast_queue_hangup(struct ast_channel *chan)
943 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
944 /* Yeah, let's not change a lock-critical value without locking */
945 if (!ast_channel_trylock(chan)) {
946 chan->_softhangup |= AST_SOFTHANGUP_DEV;
947 ast_channel_unlock(chan);
949 return ast_queue_frame(chan, &f);
952 /*! \brief Queue a control frame */
953 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
955 struct ast_frame f = { AST_FRAME_CONTROL, };
957 f.subclass = control;
959 return ast_queue_frame(chan, &f);
962 /*! \brief Queue a control frame with payload */
963 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
964 const void *data, size_t datalen)
966 struct ast_frame f = { AST_FRAME_CONTROL, };
968 f.subclass = control;
969 f.data = (void *) data;
970 f.datalen = datalen;
972 return ast_queue_frame(chan, &f);
975 /*! \brief Set defer DTMF flag on channel */
976 int ast_channel_defer_dtmf(struct ast_channel *chan)
978 int pre = 0;
980 if (chan) {
981 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
982 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
984 return pre;
987 /*! \brief Unset defer DTMF flag on channel */
988 void ast_channel_undefer_dtmf(struct ast_channel *chan)
990 if (chan)
991 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
995 * \brief Helper function to find channels.
997 * It supports these modes:
999 * prev != NULL : get channel next in list after prev
1000 * name != NULL : get channel with matching name
1001 * name != NULL && namelen != 0 : get channel whose name starts with prefix
1002 * exten != NULL : get channel whose exten or macroexten matches
1003 * context != NULL && exten != NULL : get channel whose context or macrocontext
1005 * It returns with the channel's lock held. If getting the individual lock fails,
1006 * unlock and retry quickly up to 10 times, then give up.
1008 * \note XXX Note that this code has cost O(N) because of the need to verify
1009 * that the object is still on the global list.
1011 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
1012 * can only be done with the lock held or someone could delete the
1013 * object while we work on it. This causes some ugliness in the code.
1014 * Note that removing the first ast_log() may be harmful, as it would
1015 * shorten the retry period and possibly cause failures.
1016 * We should definitely go for a better scheme that is deadlock-free.
1018 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
1019 const char *name, const int namelen,
1020 const char *context, const char *exten)
1022 const char *msg = prev ? "deadlock" : "initial deadlock";
1023 int retries;
1024 struct ast_channel *c;
1025 const struct ast_channel *_prev = prev;
1027 for (retries = 0; retries < 10; retries++) {
1028 int done;
1029 AST_LIST_LOCK(&channels);
1030 AST_LIST_TRAVERSE(&channels, c, chan_list) {
1031 prev = _prev;
1032 if (prev) { /* look for next item */
1033 if (c != prev) /* not this one */
1034 continue;
1035 /* found, prepare to return c->next */
1036 if ((c = AST_LIST_NEXT(c, chan_list)) == NULL) break;
1037 /* If prev was the last item on the channel list, then we just
1038 * want to return NULL, instead of trying to deref NULL in the
1039 * next section.
1041 prev = NULL;
1042 /* We want prev to be NULL in case we end up doing more searching through
1043 * the channel list to find the channel (ie: name searching). If we didn't
1044 * set this to NULL the logic would just blow up
1045 * XXX Need a better explanation for this ...
1048 if (name) { /* want match by name */
1049 if ((!namelen && strcasecmp(c->name, name)) ||
1050 (namelen && strncasecmp(c->name, name, namelen)))
1051 continue; /* name match failed */
1052 } else if (exten) {
1053 if (context && strcasecmp(c->context, context) &&
1054 strcasecmp(c->macrocontext, context))
1055 continue; /* context match failed */
1056 if (strcasecmp(c->exten, exten) &&
1057 strcasecmp(c->macroexten, exten))
1058 continue; /* exten match failed */
1060 /* if we get here, c points to the desired record */
1061 break;
1063 /* exit if chan not found or mutex acquired successfully */
1064 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1065 done = c == NULL || ast_channel_trylock(c) == 0;
1066 if (!done) {
1067 if (option_debug)
1068 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
1069 if (retries == 9) {
1070 /* We are about to fail due to a deadlock, so report this
1071 * while we still have the list lock.
1073 if (option_debug)
1074 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n", c, retries);
1075 /* As we have deadlocked, we will skip this channel and
1076 * see if there is another match.
1077 * NOTE: No point doing this for a full-name match,
1078 * as there can be no more matches.
1080 if (!(name && !namelen)) {
1081 prev = c;
1082 retries = -1;
1086 AST_LIST_UNLOCK(&channels);
1087 if (done)
1088 return c;
1089 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1090 * starting from the beginning of the list we can restore our saved pointer to the previous
1091 * channel and start from there.
1093 prev = _prev;
1094 usleep(1); /* give other threads a chance before retrying */
1097 return NULL;
1100 /*! \brief Browse channels in use */
1101 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1103 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1106 /*! \brief Get channel by name and lock it */
1107 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1109 return channel_find_locked(NULL, name, 0, NULL, NULL);
1112 /*! \brief Get channel by name prefix and lock it */
1113 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1115 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1118 /*! \brief Get next channel by name prefix and lock it */
1119 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1120 const int namelen)
1122 return channel_find_locked(chan, name, namelen, NULL, NULL);
1125 /*! \brief Get channel by exten (and optionally context) and lock it */
1126 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1128 return channel_find_locked(NULL, NULL, 0, context, exten);
1131 /*! \brief Get next channel by exten (and optionally context) and lock it */
1132 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1133 const char *context)
1135 return channel_find_locked(chan, NULL, 0, context, exten);
1138 /*! \brief Wait, look for hangups and condition arg */
1139 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1141 struct ast_frame *f;
1143 while (ms > 0) {
1144 if (cond && ((*cond)(data) == 0))
1145 return 0;
1146 ms = ast_waitfor(chan, ms);
1147 if (ms < 0)
1148 return -1;
1149 if (ms > 0) {
1150 f = ast_read(chan);
1151 if (!f)
1152 return -1;
1153 ast_frfree(f);
1156 return 0;
1159 /*! \brief Wait, look for hangups */
1160 int ast_safe_sleep(struct ast_channel *chan, int ms)
1162 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1165 static void free_cid(struct ast_callerid *cid)
1167 if (cid->cid_dnid)
1168 free(cid->cid_dnid);
1169 if (cid->cid_num)
1170 free(cid->cid_num);
1171 if (cid->cid_name)
1172 free(cid->cid_name);
1173 if (cid->cid_ani)
1174 free(cid->cid_ani);
1175 if (cid->cid_rdnis)
1176 free(cid->cid_rdnis);
1179 /*! \brief Free a channel structure */
1180 void ast_channel_free(struct ast_channel *chan)
1182 int fd;
1183 struct ast_var_t *vardata;
1184 struct ast_frame *f;
1185 struct varshead *headp;
1186 struct ast_datastore *datastore = NULL;
1187 char name[AST_CHANNEL_NAME];
1189 headp=&chan->varshead;
1191 AST_LIST_LOCK(&channels);
1192 if (!AST_LIST_REMOVE(&channels, chan, chan_list)) {
1193 AST_LIST_UNLOCK(&channels);
1194 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1196 /* Lock and unlock the channel just to be sure nobody
1197 has it locked still */
1198 ast_channel_lock(chan);
1199 ast_channel_unlock(chan);
1200 if (chan->tech_pvt) {
1201 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1202 free(chan->tech_pvt);
1205 if (chan->sched)
1206 sched_context_destroy(chan->sched);
1208 ast_copy_string(name, chan->name, sizeof(name));
1210 /* Stop monitoring */
1211 if (chan->monitor)
1212 chan->monitor->stop( chan, 0 );
1214 /* If there is native format music-on-hold state, free it */
1215 if (chan->music_state)
1216 ast_moh_cleanup(chan);
1218 /* Free translators */
1219 if (chan->readtrans)
1220 ast_translator_free_path(chan->readtrans);
1221 if (chan->writetrans)
1222 ast_translator_free_path(chan->writetrans);
1223 if (chan->pbx)
1224 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1225 free_cid(&chan->cid);
1226 ast_mutex_destroy(&chan->lock);
1227 /* Close pipes if appropriate */
1228 if ((fd = chan->alertpipe[0]) > -1)
1229 close(fd);
1230 if ((fd = chan->alertpipe[1]) > -1)
1231 close(fd);
1232 if ((fd = chan->timingfd) > -1)
1233 close(fd);
1234 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1235 ast_frfree(f);
1237 /* Get rid of each of the data stores on the channel */
1238 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1239 /* Free the data store */
1240 ast_channel_datastore_free(datastore);
1241 AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1243 /* loop over the variables list, freeing all data and deleting list items */
1244 /* no need to lock the list, as the channel is already locked */
1246 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1247 ast_var_delete(vardata);
1249 ast_app_group_discard(chan);
1251 /* Destroy the jitterbuffer */
1252 ast_jb_destroy(chan);
1254 ast_string_field_free_memory(chan);
1255 free(chan);
1256 AST_LIST_UNLOCK(&channels);
1258 ast_device_state_changed_literal(name);
1261 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1263 struct ast_datastore *datastore = NULL;
1265 /* Make sure we at least have type so we can identify this */
1266 if (info == NULL) {
1267 return NULL;
1270 /* Allocate memory for datastore and clear it */
1271 datastore = ast_calloc(1, sizeof(*datastore));
1272 if (datastore == NULL) {
1273 return NULL;
1276 datastore->info = info;
1278 datastore->uid = ast_strdup(uid);
1280 return datastore;
1283 int ast_channel_datastore_free(struct ast_datastore *datastore)
1285 int res = 0;
1287 /* Using the destroy function (if present) destroy the data */
1288 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1289 datastore->info->destroy(datastore->data);
1290 datastore->data = NULL;
1293 /* Free allocated UID memory */
1294 if (datastore->uid != NULL) {
1295 free(datastore->uid);
1296 datastore->uid = NULL;
1299 /* Finally free memory used by ourselves */
1300 free(datastore);
1302 return res;
1305 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1307 struct ast_datastore *datastore = NULL, *datastore2;
1309 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1310 if (datastore->inheritance > 0) {
1311 datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1312 if (datastore2) {
1313 datastore2->data = datastore->info->duplicate(datastore->data);
1314 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1315 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1319 return 0;
1322 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1324 int res = 0;
1326 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1328 return res;
1331 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1333 struct ast_datastore *datastore2 = NULL;
1334 int res = -1;
1336 /* Find our position and remove ourselves */
1337 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1338 if (datastore2 == datastore) {
1339 AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1340 res = 0;
1341 break;
1344 AST_LIST_TRAVERSE_SAFE_END
1346 return res;
1349 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1351 struct ast_datastore *datastore = NULL;
1353 if (info == NULL)
1354 return NULL;
1356 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1357 if (datastore->info == info) {
1358 if (uid != NULL && datastore->uid != NULL) {
1359 if (!strcasecmp(uid, datastore->uid)) {
1360 /* Matched by type AND uid */
1361 break;
1363 } else {
1364 /* Matched by type at least */
1365 break;
1369 AST_LIST_TRAVERSE_SAFE_END
1371 return datastore;
1374 /*! \brief Softly hangup a channel, don't lock */
1375 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1377 if (option_debug)
1378 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1379 /* Inform channel driver that we need to be hung up, if it cares */
1380 chan->_softhangup |= cause;
1381 ast_queue_frame(chan, &ast_null_frame);
1382 /* Interrupt any poll call or such */
1383 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1384 pthread_kill(chan->blocker, SIGURG);
1385 return 0;
1388 /*! \brief Softly hangup a channel, lock */
1389 int ast_softhangup(struct ast_channel *chan, int cause)
1391 int res;
1392 ast_channel_lock(chan);
1393 res = ast_softhangup_nolock(chan, cause);
1394 ast_channel_unlock(chan);
1395 return res;
1398 static void free_translation(struct ast_channel *clone)
1400 if (clone->writetrans)
1401 ast_translator_free_path(clone->writetrans);
1402 if (clone->readtrans)
1403 ast_translator_free_path(clone->readtrans);
1404 clone->writetrans = NULL;
1405 clone->readtrans = NULL;
1406 clone->rawwriteformat = clone->nativeformats;
1407 clone->rawreadformat = clone->nativeformats;
1410 /*! \brief Hangup a channel */
1411 int ast_hangup(struct ast_channel *chan)
1413 int res = 0;
1414 struct ast_cdr *cdr = NULL;
1416 /* Don't actually hang up a channel that will masquerade as someone else, or
1417 if someone is going to masquerade as us */
1418 ast_channel_lock(chan);
1420 if (chan->audiohooks) {
1421 ast_audiohook_detach_list(chan->audiohooks);
1422 chan->audiohooks = NULL;
1425 ast_autoservice_stop(chan);
1427 if (chan->masq) {
1428 if (ast_do_masquerade(chan))
1429 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1432 if (chan->masq) {
1433 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1434 ast_channel_unlock(chan);
1435 return 0;
1437 /* If this channel is one which will be masqueraded into something,
1438 mark it as a zombie already, so we know to free it later */
1439 if (chan->masqr) {
1440 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1441 ast_channel_unlock(chan);
1442 return 0;
1444 free_translation(chan);
1445 /* Close audio stream */
1446 if (chan->stream) {
1447 ast_closestream(chan->stream);
1448 chan->stream = NULL;
1450 /* Close video stream */
1451 if (chan->vstream) {
1452 ast_closestream(chan->vstream);
1453 chan->vstream = NULL;
1455 if (chan->sched) {
1456 sched_context_destroy(chan->sched);
1457 chan->sched = NULL;
1460 if (chan->generatordata) /* Clear any tone stuff remaining */
1461 chan->generator->release(chan, chan->generatordata);
1462 chan->generatordata = NULL;
1463 chan->generator = NULL;
1464 if (chan->cdr) { /* End the CDR if it hasn't already */
1465 ast_cdr_end(chan->cdr);
1466 cdr = chan->cdr;
1467 chan->cdr = NULL;
1469 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1470 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1471 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1472 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1473 CRASH;
1475 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1476 if (option_debug)
1477 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1478 if (chan->tech->hangup)
1479 res = chan->tech->hangup(chan);
1480 } else {
1481 if (option_debug)
1482 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1485 ast_channel_unlock(chan);
1486 manager_event(EVENT_FLAG_CALL, "Hangup",
1487 "Channel: %s\r\n"
1488 "Uniqueid: %s\r\n"
1489 "Cause: %d\r\n"
1490 "Cause-txt: %s\r\n",
1491 chan->name,
1492 chan->uniqueid,
1493 chan->hangupcause,
1494 ast_cause2str(chan->hangupcause)
1496 ast_channel_free(chan);
1498 if (cdr)
1499 ast_cdr_detach(cdr);
1501 return res;
1504 int ast_answer(struct ast_channel *chan)
1506 int res = 0;
1507 ast_channel_lock(chan);
1508 /* You can't answer an outbound call */
1509 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1510 ast_channel_unlock(chan);
1511 return 0;
1513 /* Stop if we're a zombie or need a soft hangup */
1514 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1515 ast_channel_unlock(chan);
1516 return -1;
1518 switch(chan->_state) {
1519 case AST_STATE_RINGING:
1520 case AST_STATE_RING:
1521 if (chan->tech->answer)
1522 res = chan->tech->answer(chan);
1523 ast_setstate(chan, AST_STATE_UP);
1524 ast_cdr_answer(chan->cdr);
1525 break;
1526 case AST_STATE_UP:
1527 ast_cdr_answer(chan->cdr);
1528 break;
1529 default:
1530 break;
1532 chan->visible_indication = 0;
1533 ast_channel_unlock(chan);
1534 return res;
1537 void ast_deactivate_generator(struct ast_channel *chan)
1539 ast_channel_lock(chan);
1540 if (chan->generatordata) {
1541 if (chan->generator && chan->generator->release)
1542 chan->generator->release(chan, chan->generatordata);
1543 chan->generatordata = NULL;
1544 chan->generator = NULL;
1545 chan->fds[AST_GENERATOR_FD] = -1;
1546 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1547 ast_settimeout(chan, 0, NULL, NULL);
1549 ast_channel_unlock(chan);
1552 static int generator_force(const void *data)
1554 /* Called if generator doesn't have data */
1555 void *tmp;
1556 int res;
1557 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1558 struct ast_channel *chan = (struct ast_channel *)data;
1560 ast_channel_lock(chan);
1561 tmp = chan->generatordata;
1562 chan->generatordata = NULL;
1563 generate = chan->generator->generate;
1564 ast_channel_unlock(chan);
1566 res = generate(chan, tmp, 0, 160);
1568 chan->generatordata = tmp;
1570 if (res) {
1571 if (option_debug)
1572 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1573 ast_deactivate_generator(chan);
1576 return 0;
1579 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1581 int res = 0;
1583 ast_channel_lock(chan);
1585 if (chan->generatordata) {
1586 if (chan->generator && chan->generator->release)
1587 chan->generator->release(chan, chan->generatordata);
1588 chan->generatordata = NULL;
1591 ast_prod(chan);
1592 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1593 res = -1;
1596 if (!res) {
1597 ast_settimeout(chan, 160, generator_force, chan);
1598 chan->generator = gen;
1601 ast_channel_unlock(chan);
1603 return res;
1606 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1607 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1609 int winner = -1;
1610 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1611 return winner;
1614 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1615 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1616 int *exception, int *outfd, int *ms)
1618 struct timeval start = { 0 , 0 };
1619 struct pollfd *pfds = NULL;
1620 int res;
1621 long rms;
1622 int x, y, max;
1623 int sz;
1624 time_t now = 0;
1625 long whentohangup = 0, diff;
1626 struct ast_channel *winner = NULL;
1627 struct fdmap {
1628 int chan;
1629 int fdno;
1630 } *fdmap = NULL;
1632 if ((sz = n * AST_MAX_FDS + nfds)) {
1633 pfds = alloca(sizeof(*pfds) * sz);
1634 fdmap = alloca(sizeof(*fdmap) * sz);
1637 if (outfd)
1638 *outfd = -99999;
1639 if (exception)
1640 *exception = 0;
1642 /* Perform any pending masquerades */
1643 for (x=0; x < n; x++) {
1644 ast_channel_lock(c[x]);
1645 if (c[x]->masq) {
1646 if (ast_do_masquerade(c[x])) {
1647 ast_log(LOG_WARNING, "Masquerade failed\n");
1648 *ms = -1;
1649 ast_channel_unlock(c[x]);
1650 return NULL;
1653 if (c[x]->whentohangup) {
1654 if (!whentohangup)
1655 time(&now);
1656 diff = c[x]->whentohangup - now;
1657 if (diff < 1) {
1658 /* Should already be hungup */
1659 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1660 ast_channel_unlock(c[x]);
1661 return c[x];
1663 if (!whentohangup || (diff < whentohangup))
1664 whentohangup = diff;
1666 ast_channel_unlock(c[x]);
1668 /* Wait full interval */
1669 rms = *ms;
1670 if (whentohangup) {
1671 rms = whentohangup * 1000; /* timeout in milliseconds */
1672 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1673 rms = *ms;
1676 * Build the pollfd array, putting the channels' fds first,
1677 * followed by individual fds. Order is important because
1678 * individual fd's must have priority over channel fds.
1680 max = 0;
1681 for (x=0; x<n; x++) {
1682 for (y=0; y<AST_MAX_FDS; y++) {
1683 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1684 fdmap[max].chan = x; /* channel x is linked to this pfds */
1685 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1687 CHECK_BLOCKING(c[x]);
1689 /* Add the individual fds */
1690 for (x=0; x<nfds; x++) {
1691 fdmap[max].chan = -1;
1692 max += ast_add_fd(&pfds[max], fds[x]);
1695 if (*ms > 0)
1696 start = ast_tvnow();
1698 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1699 do {
1700 int kbrms = rms;
1701 if (kbrms > 600000)
1702 kbrms = 600000;
1703 res = poll(pfds, max, kbrms);
1704 if (!res)
1705 rms -= kbrms;
1706 } while (!res && (rms > 0));
1707 } else {
1708 res = poll(pfds, max, rms);
1710 for (x=0; x<n; x++)
1711 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1712 if (res < 0) { /* Simulate a timeout if we were interrupted */
1713 if (errno != EINTR)
1714 *ms = -1;
1715 return NULL;
1717 if (whentohangup) { /* if we have a timeout, check who expired */
1718 time(&now);
1719 for (x=0; x<n; x++) {
1720 if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1721 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1722 if (winner == NULL)
1723 winner = c[x];
1727 if (res == 0) { /* no fd ready, reset timeout and done */
1728 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1729 return winner;
1732 * Then check if any channel or fd has a pending event.
1733 * Remember to check channels first and fds last, as they
1734 * must have priority on setting 'winner'
1736 for (x = 0; x < max; x++) {
1737 res = pfds[x].revents;
1738 if (res == 0)
1739 continue;
1740 if (fdmap[x].chan >= 0) { /* this is a channel */
1741 winner = c[fdmap[x].chan]; /* override previous winners */
1742 if (res & POLLPRI)
1743 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1744 else
1745 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1746 winner->fdno = fdmap[x].fdno;
1747 } else { /* this is an fd */
1748 if (outfd)
1749 *outfd = pfds[x].fd;
1750 if (exception)
1751 *exception = (res & POLLPRI) ? -1 : 0;
1752 winner = NULL;
1755 if (*ms > 0) {
1756 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1757 if (*ms < 0)
1758 *ms = 0;
1760 return winner;
1763 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1765 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1768 int ast_waitfor(struct ast_channel *c, int ms)
1770 int oldms = ms; /* -1 if no timeout */
1772 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1773 if ((ms < 0) && (oldms < 0))
1774 ms = 0;
1775 return ms;
1778 /* XXX never to be called with ms = -1 */
1779 int ast_waitfordigit(struct ast_channel *c, int ms)
1781 return ast_waitfordigit_full(c, ms, -1, -1);
1784 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
1786 int res = -1;
1787 #ifdef HAVE_ZAPTEL
1788 if (c->timingfd > -1) {
1789 if (!func) {
1790 samples = 0;
1791 data = 0;
1793 if (option_debug)
1794 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1795 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1796 c->timingfunc = func;
1797 c->timingdata = data;
1799 #endif
1800 return res;
1803 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1805 /* Stop if we're a zombie or need a soft hangup */
1806 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1807 return -1;
1809 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
1810 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
1812 /* Wait for a digit, no more than ms milliseconds total. */
1813 while (ms) {
1814 struct ast_channel *rchan;
1815 int outfd;
1817 errno = 0;
1818 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1819 if (!rchan && outfd < 0 && ms) {
1820 if (errno == 0 || errno == EINTR)
1821 continue;
1822 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1823 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1824 return -1;
1825 } else if (outfd > -1) {
1826 /* The FD we were watching has something waiting */
1827 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1828 return 1;
1829 } else if (rchan) {
1830 int res;
1831 struct ast_frame *f = ast_read(c);
1832 if (!f)
1833 return -1;
1835 switch(f->frametype) {
1836 case AST_FRAME_DTMF_BEGIN:
1837 break;
1838 case AST_FRAME_DTMF_END:
1839 res = f->subclass;
1840 ast_frfree(f);
1841 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1842 return res;
1843 case AST_FRAME_CONTROL:
1844 switch(f->subclass) {
1845 case AST_CONTROL_HANGUP:
1846 ast_frfree(f);
1847 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1848 return -1;
1849 case AST_CONTROL_RINGING:
1850 case AST_CONTROL_ANSWER:
1851 /* Unimportant */
1852 break;
1853 default:
1854 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1855 break;
1857 break;
1858 case AST_FRAME_VOICE:
1859 /* Write audio if appropriate */
1860 if (audiofd > -1)
1861 write(audiofd, f->data, f->datalen);
1862 default:
1863 /* Ignore */
1864 break;
1866 ast_frfree(f);
1870 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1872 return 0; /* Time is up */
1875 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
1877 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
1878 void *tmp = chan->generatordata;
1879 int res;
1881 if (chan->timingfunc) {
1882 if (option_debug > 1)
1883 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1884 ast_settimeout(chan, 0, NULL, NULL);
1887 chan->generatordata = NULL; /* reset, to let writes go through */
1888 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
1889 chan->generatordata = tmp;
1890 if (res) {
1891 if (option_debug > 1)
1892 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1893 ast_deactivate_generator(chan);
1896 } else if (f->frametype == AST_FRAME_CNG) {
1897 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1898 if (option_debug > 1)
1899 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
1900 ast_settimeout(chan, 160, generator_force, chan);
1905 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1907 struct ast_frame *f = NULL; /* the return value */
1908 int blah;
1909 int prestate;
1910 int count = 0;
1912 /* this function is very long so make sure there is only one return
1913 * point at the end (there are only two exceptions to this).
1915 while(ast_channel_trylock(chan)) {
1916 if(count++ > 10)
1917 /*cannot goto done since the channel is not locked*/
1918 return &ast_null_frame;
1919 usleep(1);
1922 if (chan->masq) {
1923 if (ast_do_masquerade(chan))
1924 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1925 else
1926 f = &ast_null_frame;
1927 goto done;
1930 /* Stop if we're a zombie or need a soft hangup */
1931 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1932 if (chan->generator)
1933 ast_deactivate_generator(chan);
1934 goto done;
1936 prestate = chan->_state;
1938 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
1939 !ast_strlen_zero(chan->dtmfq) &&
1940 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
1941 /* We have DTMF that has been deferred. Return it now */
1942 chan->dtmff.subclass = chan->dtmfq[0];
1943 /* Drop first digit from the buffer */
1944 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1945 f = &chan->dtmff;
1946 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
1947 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
1948 chan->dtmff.frametype = AST_FRAME_DTMF_END;
1949 } else {
1950 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);
1951 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
1952 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
1953 chan->emulate_dtmf_digit = f->subclass;
1954 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
1956 chan->dtmf_tv = ast_tvnow();
1957 goto done;
1960 /* Read and ignore anything on the alertpipe, but read only
1961 one sizeof(blah) per frame that we send from it */
1962 if (chan->alertpipe[0] > -1)
1963 read(chan->alertpipe[0], &blah, sizeof(blah));
1965 #ifdef HAVE_ZAPTEL
1966 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1967 int res;
1969 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1970 blah = -1;
1971 /* IF we can't get event, assume it's an expired as-per the old interface */
1972 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1973 if (res)
1974 blah = ZT_EVENT_TIMER_EXPIRED;
1976 if (blah == ZT_EVENT_TIMER_PING) {
1977 if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
1978 /* Acknowledge PONG unless we need it again */
1979 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1980 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1983 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1984 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1985 if (chan->timingfunc) {
1986 /* save a copy of func/data before unlocking the channel */
1987 int (*func)(const void *) = chan->timingfunc;
1988 void *data = chan->timingdata;
1989 ast_channel_unlock(chan);
1990 func(data);
1991 } else {
1992 blah = 0;
1993 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1994 chan->timingdata = NULL;
1995 ast_channel_unlock(chan);
1997 /* cannot 'goto done' because the channel is already unlocked */
1998 return &ast_null_frame;
1999 } else
2000 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2001 } else
2002 #endif
2003 if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2004 /* if the AST_GENERATOR_FD is set, call the generator with args
2005 * set to -1 so it can do whatever it needs to.
2007 void *tmp = chan->generatordata;
2008 chan->generatordata = NULL; /* reset to let ast_write get through */
2009 chan->generator->generate(chan, tmp, -1, -1);
2010 chan->generatordata = tmp;
2011 f = &ast_null_frame;
2012 goto done;
2015 /* Check for pending read queue */
2016 if (!AST_LIST_EMPTY(&chan->readq)) {
2017 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2018 /* Interpret hangup and return NULL */
2019 /* XXX why not the same for frames from the channel ? */
2020 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2021 ast_frfree(f);
2022 f = NULL;
2024 } else {
2025 chan->blocker = pthread_self();
2026 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2027 if (chan->tech->exception)
2028 f = chan->tech->exception(chan);
2029 else {
2030 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2031 f = &ast_null_frame;
2033 /* Clear the exception flag */
2034 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2035 } else if (chan->tech->read)
2036 f = chan->tech->read(chan);
2037 else
2038 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2041 if (f) {
2042 /* if the channel driver returned more than one frame, stuff the excess
2043 into the readq for the next ast_read call (note that we can safely assume
2044 that the readq is empty, because otherwise we would not have called into
2045 the channel driver and f would be only a single frame)
2047 if (AST_LIST_NEXT(f, frame_list)) {
2048 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2049 AST_LIST_NEXT(f, frame_list) = NULL;
2052 switch (f->frametype) {
2053 case AST_FRAME_CONTROL:
2054 if (f->subclass == AST_CONTROL_ANSWER) {
2055 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2056 if (option_debug)
2057 ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
2058 ast_frfree(f);
2059 f = &ast_null_frame;
2060 } else if (prestate == AST_STATE_UP) {
2061 if (option_debug)
2062 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
2063 ast_frfree(f);
2064 f = &ast_null_frame;
2065 } else {
2066 /* Answer the CDR */
2067 ast_setstate(chan, AST_STATE_UP);
2068 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2069 to keep from throwing off the basic order of the universe,
2070 we will try to keep this cdr from getting posted. */
2071 chan->cdr = ast_cdr_alloc();
2072 ast_cdr_init(chan->cdr, chan);
2073 ast_cdr_start(chan->cdr);
2076 ast_cdr_answer(chan->cdr);
2079 break;
2080 case AST_FRAME_DTMF_END:
2081 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2082 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2083 * However, only let emulation be forced if the other end cares about BEGIN frames */
2084 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2085 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2086 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2087 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2088 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2089 } else
2090 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2091 ast_frfree(f);
2092 f = &ast_null_frame;
2093 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2094 if (!ast_tvzero(chan->dtmf_tv) &&
2095 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2096 /* If it hasn't been long enough, defer this digit */
2097 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2098 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2099 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2100 } else
2101 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2102 ast_frfree(f);
2103 f = &ast_null_frame;
2104 } else {
2105 /* There was no begin, turn this into a begin and send the end later */
2106 f->frametype = AST_FRAME_DTMF_BEGIN;
2107 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2108 chan->emulate_dtmf_digit = f->subclass;
2109 chan->dtmf_tv = ast_tvnow();
2110 if (f->len) {
2111 if (f->len > AST_MIN_DTMF_DURATION)
2112 chan->emulate_dtmf_duration = f->len;
2113 else
2114 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2115 } else
2116 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2117 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2119 if (chan->audiohooks) {
2120 struct ast_frame *old_frame = f;
2121 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2122 if (old_frame != f)
2123 ast_frfree(old_frame);
2125 } else {
2126 struct timeval now = ast_tvnow();
2127 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2128 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2129 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2130 if (!f->len)
2131 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2132 } else if (!f->len) {
2133 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2134 f->len = AST_MIN_DTMF_DURATION;
2136 if (f->len < AST_MIN_DTMF_DURATION) {
2137 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);
2138 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2139 chan->emulate_dtmf_digit = f->subclass;
2140 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2141 ast_frfree(f);
2142 f = &ast_null_frame;
2143 } else {
2144 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2145 chan->dtmf_tv = now;
2147 if (chan->audiohooks) {
2148 struct ast_frame *old_frame = f;
2149 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2150 if (old_frame != f)
2151 ast_frfree(old_frame);
2154 break;
2155 case AST_FRAME_DTMF_BEGIN:
2156 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2157 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
2158 (!ast_tvzero(chan->dtmf_tv) &&
2159 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2160 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2161 ast_frfree(f);
2162 f = &ast_null_frame;
2163 } else {
2164 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2165 chan->dtmf_tv = ast_tvnow();
2166 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2168 break;
2169 case AST_FRAME_NULL:
2170 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2171 * is reached , because we want to make sure we pass at least one
2172 * voice frame through before starting the next digit, to ensure a gap
2173 * between DTMF digits. */
2174 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2175 struct timeval now = ast_tvnow();
2176 if (!chan->emulate_dtmf_duration) {
2177 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2178 chan->emulate_dtmf_digit = 0;
2179 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2180 chan->emulate_dtmf_duration = 0;
2181 ast_frfree(f);
2182 f = &chan->dtmff;
2183 f->frametype = AST_FRAME_DTMF_END;
2184 f->subclass = chan->emulate_dtmf_digit;
2185 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2186 chan->dtmf_tv = now;
2187 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2188 chan->emulate_dtmf_digit = 0;
2189 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2192 break;
2193 case AST_FRAME_VOICE:
2194 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2195 * is reached , because we want to make sure we pass at least one
2196 * voice frame through before starting the next digit, to ensure a gap
2197 * between DTMF digits. */
2198 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2199 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2200 chan->emulate_dtmf_digit = 0;
2203 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2204 if (dropaudio)
2205 ast_read_generator_actions(chan, f);
2206 ast_frfree(f);
2207 f = &ast_null_frame;
2210 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2211 struct timeval now = ast_tvnow();
2212 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2213 chan->emulate_dtmf_duration = 0;
2214 ast_frfree(f);
2215 f = &chan->dtmff;
2216 f->frametype = AST_FRAME_DTMF_END;
2217 f->subclass = chan->emulate_dtmf_digit;
2218 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2219 chan->dtmf_tv = now;
2220 if (chan->audiohooks) {
2221 struct ast_frame *old_frame = f;
2222 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2223 if (old_frame != f)
2224 ast_frfree(old_frame);
2226 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2227 } else {
2228 /* Drop voice frames while we're still in the middle of the digit */
2229 ast_frfree(f);
2230 f = &ast_null_frame;
2232 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2233 /* This frame can't be from the current native formats -- drop it on the
2234 floor */
2235 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2236 chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2237 ast_frfree(f);
2238 f = &ast_null_frame;
2239 } else if ((f->frametype == AST_FRAME_VOICE)) {
2240 if (chan->audiohooks) {
2241 struct ast_frame *old_frame = f;
2242 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2243 if (old_frame != f)
2244 ast_frfree(old_frame);
2246 if (chan->monitor && chan->monitor->read_stream ) {
2247 /* XXX what does this do ? */
2248 #ifndef MONITOR_CONSTANT_DELAY
2249 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2250 if (jump >= 0) {
2251 jump = chan->outsmpl - chan->insmpl;
2252 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2253 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2254 chan->insmpl += jump + f->samples;
2255 } else
2256 chan->insmpl+= f->samples;
2257 #else
2258 int jump = chan->outsmpl - chan->insmpl;
2259 if (jump - MONITOR_DELAY >= 0) {
2260 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2261 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2262 chan->insmpl += jump;
2263 } else
2264 chan->insmpl += f->samples;
2265 #endif
2266 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2267 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2268 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2272 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2273 f = &ast_null_frame;
2275 /* Run generator sitting on the line if timing device not available
2276 * and synchronous generation of outgoing frames is necessary */
2277 ast_read_generator_actions(chan, f);
2279 default:
2280 /* Just pass it on! */
2281 break;
2283 } else {
2284 /* Make sure we always return NULL in the future */
2285 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2286 if (chan->generator)
2287 ast_deactivate_generator(chan);
2288 /* End the CDR if appropriate */
2289 if (chan->cdr)
2290 ast_cdr_end(chan->cdr);
2293 /* High bit prints debugging */
2294 if (chan->fin & DEBUGCHAN_FLAG)
2295 ast_frame_dump(chan->name, f, "<<");
2296 chan->fin = FRAMECOUNT_INC(chan->fin);
2298 done:
2299 ast_channel_unlock(chan);
2300 return f;
2303 int ast_internal_timing_enabled(struct ast_channel *chan)
2305 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2306 if (option_debug > 4)
2307 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);
2308 return ret;
2311 struct ast_frame *ast_read(struct ast_channel *chan)
2313 return __ast_read(chan, 0);
2316 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2318 return __ast_read(chan, 1);
2321 int ast_indicate(struct ast_channel *chan, int condition)
2323 return ast_indicate_data(chan, condition, NULL, 0);
2326 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2328 int res = -1;
2330 ast_channel_lock(chan);
2331 /* Stop if we're a zombie or need a soft hangup */
2332 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2333 ast_channel_unlock(chan);
2334 return -1;
2336 if (chan->tech->indicate)
2337 res = chan->tech->indicate(chan, condition, data, datalen);
2338 ast_channel_unlock(chan);
2339 if (!chan->tech->indicate || res) {
2341 * Device does not support (that) indication, lets fake
2342 * it by doing our own tone generation. (PM2002)
2344 if (condition < 0)
2345 ast_playtones_stop(chan);
2346 else {
2347 const struct tone_zone_sound *ts = NULL;
2348 switch (condition) {
2349 case AST_CONTROL_RINGING:
2350 ts = ast_get_indication_tone(chan->zone, "ring");
2351 break;
2352 case AST_CONTROL_BUSY:
2353 ts = ast_get_indication_tone(chan->zone, "busy");
2354 break;
2355 case AST_CONTROL_CONGESTION:
2356 ts = ast_get_indication_tone(chan->zone, "congestion");
2357 break;
2359 if (ts && ts->data[0]) {
2360 if (option_debug)
2361 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2362 ast_playtones_start(chan,0,ts->data, 1);
2363 res = 0;
2364 chan->visible_indication = condition;
2365 } else if (condition == AST_CONTROL_PROGRESS) {
2366 /* ast_playtones_stop(chan); */
2367 } else if (condition == AST_CONTROL_PROCEEDING) {
2368 /* Do nothing, really */
2369 } else if (condition == AST_CONTROL_HOLD) {
2370 /* Do nothing.... */
2371 } else if (condition == AST_CONTROL_UNHOLD) {
2372 /* Do nothing.... */
2373 } else if (condition == AST_CONTROL_VIDUPDATE) {
2374 /* Do nothing.... */
2375 } else {
2376 /* not handled */
2377 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2378 res = -1;
2381 } else
2382 chan->visible_indication = condition;
2384 return res;
2387 int ast_recvchar(struct ast_channel *chan, int timeout)
2389 int c;
2390 char *buf = ast_recvtext(chan, timeout);
2391 if (buf == NULL)
2392 return -1; /* error or timeout */
2393 c = *(unsigned char *)buf;
2394 free(buf);
2395 return c;
2398 char *ast_recvtext(struct ast_channel *chan, int timeout)
2400 int res, done = 0;
2401 char *buf = NULL;
2403 while (!done) {
2404 struct ast_frame *f;
2405 if (ast_check_hangup(chan))
2406 break;
2407 res = ast_waitfor(chan, timeout);
2408 if (res <= 0) /* timeout or error */
2409 break;
2410 timeout = res; /* update timeout */
2411 f = ast_read(chan);
2412 if (f == NULL)
2413 break; /* no frame */
2414 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2415 done = 1; /* force a break */
2416 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2417 buf = ast_strndup((char *) f->data, f->datalen); /* dup and break */
2418 done = 1;
2420 ast_frfree(f);
2422 return buf;
2425 int ast_sendtext(struct ast_channel *chan, const char *text)
2427 int res = 0;
2428 /* Stop if we're a zombie or need a soft hangup */
2429 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2430 return -1;
2431 CHECK_BLOCKING(chan);
2432 if (chan->tech->send_text)
2433 res = chan->tech->send_text(chan, text);
2434 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2435 return res;
2438 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2440 /* Device does not support DTMF tones, lets fake
2441 * it by doing our own generation. */
2442 static const char* dtmf_tones[] = {
2443 "941+1336", /* 0 */
2444 "697+1209", /* 1 */
2445 "697+1336", /* 2 */
2446 "697+1477", /* 3 */
2447 "770+1209", /* 4 */
2448 "770+1336", /* 5 */
2449 "770+1477", /* 6 */
2450 "852+1209", /* 7 */
2451 "852+1336", /* 8 */
2452 "852+1477", /* 9 */
2453 "697+1633", /* A */
2454 "770+1633", /* B */
2455 "852+1633", /* C */
2456 "941+1633", /* D */
2457 "941+1209", /* * */
2458 "941+1477" /* # */
2461 if (!chan->tech->send_digit_begin)
2462 return 0;
2464 if (!chan->tech->send_digit_begin(chan, digit))
2465 return 0;
2467 if (digit >= '0' && digit <='9')
2468 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2469 else if (digit >= 'A' && digit <= 'D')
2470 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2471 else if (digit == '*')
2472 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2473 else if (digit == '#')
2474 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2475 else {
2476 /* not handled */
2477 if (option_debug)
2478 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2481 return 0;
2484 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2486 int res = -1;
2488 if (chan->tech->send_digit_end)
2489 res = chan->tech->send_digit_end(chan, digit, duration);
2491 if (res && chan->generator)
2492 ast_playtones_stop(chan);
2494 return 0;
2497 int ast_senddigit(struct ast_channel *chan, char digit)
2499 if (chan->tech->send_digit_begin) {
2500 ast_senddigit_begin(chan, digit);
2501 ast_safe_sleep(chan, AST_DEFAULT_EMULATE_DTMF_DURATION);
2504 return ast_senddigit_end(chan, digit, AST_DEFAULT_EMULATE_DTMF_DURATION);
2507 int ast_prod(struct ast_channel *chan)
2509 struct ast_frame a = { AST_FRAME_VOICE };
2510 char nothing[128];
2512 /* Send an empty audio frame to get things moving */
2513 if (chan->_state != AST_STATE_UP) {
2514 if (option_debug)
2515 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2516 a.subclass = chan->rawwriteformat;
2517 a.data = nothing + AST_FRIENDLY_OFFSET;
2518 a.src = "ast_prod";
2519 if (ast_write(chan, &a))
2520 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2522 return 0;
2525 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2527 int res;
2528 if (!chan->tech->write_video)
2529 return 0;
2530 res = ast_write(chan, fr);
2531 if (!res)
2532 res = 1;
2533 return res;
2536 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2538 int res = -1;
2539 int count = 0;
2540 struct ast_frame *f = NULL, *f2 = NULL;
2542 /*Deadlock avoidance*/
2543 while(ast_channel_trylock(chan)) {
2544 /*cannot goto done since the channel is not locked*/
2545 if(count++ > 10) {
2546 if(option_debug)
2547 ast_log(LOG_DEBUG, "Deadlock avoided for write to channel '%s'\n", chan->name);
2548 return 0;
2550 usleep(1);
2552 /* Stop if we're a zombie or need a soft hangup */
2553 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2554 goto done;
2556 /* Handle any pending masquerades */
2557 if (chan->masq && ast_do_masquerade(chan)) {
2558 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2559 goto done;
2561 if (chan->masqr) {
2562 res = 0; /* XXX explain, why 0 ? */
2563 goto done;
2565 if (chan->generatordata) {
2566 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2567 ast_deactivate_generator(chan);
2568 else {
2569 if (fr->frametype == AST_FRAME_DTMF_END) {
2570 /* There is a generator running while we're in the middle of a digit.
2571 * It's probably inband DTMF, so go ahead and pass it so it can
2572 * stop the generator */
2573 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2574 ast_channel_unlock(chan);
2575 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2576 ast_channel_lock(chan);
2577 CHECK_BLOCKING(chan);
2578 } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2579 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2580 res = (chan->tech->indicate == NULL) ? 0 :
2581 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2583 res = 0; /* XXX explain, why 0 ? */
2584 goto done;
2587 /* High bit prints debugging */
2588 if (chan->fout & DEBUGCHAN_FLAG)
2589 ast_frame_dump(chan->name, fr, ">>");
2590 CHECK_BLOCKING(chan);
2591 switch(fr->frametype) {
2592 case AST_FRAME_CONTROL:
2593 res = (chan->tech->indicate == NULL) ? 0 :
2594 chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2595 break;
2596 case AST_FRAME_DTMF_BEGIN:
2597 if (chan->audiohooks) {
2598 struct ast_frame *old_frame = fr;
2599 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2600 if (old_frame != fr)
2601 f = fr;
2603 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2604 ast_channel_unlock(chan);
2605 res = ast_senddigit_begin(chan, fr->subclass);
2606 ast_channel_lock(chan);
2607 CHECK_BLOCKING(chan);
2608 break;
2609 case AST_FRAME_DTMF_END:
2610 if (chan->audiohooks) {
2611 struct ast_frame *old_frame = fr;
2612 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2613 if (old_frame != fr)
2614 f = fr;
2616 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2617 ast_channel_unlock(chan);
2618 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2619 ast_channel_lock(chan);
2620 CHECK_BLOCKING(chan);
2621 break;
2622 case AST_FRAME_TEXT:
2623 res = (chan->tech->send_text == NULL) ? 0 :
2624 chan->tech->send_text(chan, (char *) fr->data);
2625 break;
2626 case AST_FRAME_HTML:
2627 res = (chan->tech->send_html == NULL) ? 0 :
2628 chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2629 break;
2630 case AST_FRAME_VIDEO:
2631 /* XXX Handle translation of video codecs one day XXX */
2632 res = (chan->tech->write_video == NULL) ? 0 :
2633 chan->tech->write_video(chan, fr);
2634 break;
2635 case AST_FRAME_MODEM:
2636 res = (chan->tech->write == NULL) ? 0 :
2637 chan->tech->write(chan, fr);
2638 break;
2639 case AST_FRAME_VOICE:
2640 if (chan->tech->write == NULL)
2641 break; /*! \todo XXX should return 0 maybe ? */
2643 if (chan->audiohooks) {
2644 struct ast_frame *old_frame = fr;
2645 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2646 if (old_frame != fr)
2647 f2 = fr;
2650 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2651 if (fr->subclass == chan->rawwriteformat)
2652 f = fr;
2653 else
2654 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2656 /* If we have no frame of audio, then we have to bail out */
2657 if (!f) {
2658 res = 0;
2659 break;
2662 /* If Monitor is running on this channel, then we have to write frames out there too */
2663 if (chan->monitor && chan->monitor->write_stream) {
2664 /* XXX must explain this code */
2665 #ifndef MONITOR_CONSTANT_DELAY
2666 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2667 if (jump >= 0) {
2668 jump = chan->insmpl - chan->outsmpl;
2669 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2670 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2671 chan->outsmpl += jump + f->samples;
2672 } else
2673 chan->outsmpl += f->samples;
2674 #else
2675 int jump = chan->insmpl - chan->outsmpl;
2676 if (jump - MONITOR_DELAY >= 0) {
2677 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2678 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2679 chan->outsmpl += jump;
2680 } else
2681 chan->outsmpl += f->samples;
2682 #endif
2683 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2684 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2685 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2689 if (f)
2690 res = chan->tech->write(chan,f);
2691 else
2692 res = 0;
2693 break;
2694 case AST_FRAME_NULL:
2695 case AST_FRAME_IAX:
2696 /* Ignore these */
2697 res = 0;
2698 break;
2699 default:
2700 /* At this point, fr is the incoming frame and f is NULL. Channels do
2701 * not expect to get NULL as a frame pointer and will segfault. Hence,
2702 * we output the original frame passed in. */
2703 res = chan->tech->write(chan, fr);
2704 break;
2707 if (f && f != fr)
2708 ast_frfree(f);
2709 if (f2)
2710 ast_frfree(f2);
2711 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2712 /* Consider a write failure to force a soft hangup */
2713 if (res < 0)
2714 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2715 else {
2716 chan->fout = FRAMECOUNT_INC(chan->fout);
2718 done:
2719 ast_channel_unlock(chan);
2720 return res;
2723 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2724 struct ast_trans_pvt **trans, const int direction)
2726 int native;
2727 int res;
2729 /* Make sure we only consider audio */
2730 fmt &= AST_FORMAT_AUDIO_MASK;
2732 native = chan->nativeformats;
2733 /* Find a translation path from the native format to one of the desired formats */
2734 if (!direction)
2735 /* reading */
2736 res = ast_translator_best_choice(&fmt, &native);
2737 else
2738 /* writing */
2739 res = ast_translator_best_choice(&native, &fmt);
2741 if (res < 0) {
2742 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2743 ast_getformatname(native), ast_getformatname(fmt));
2744 return -1;
2747 /* Now we have a good choice for both. */
2748 ast_channel_lock(chan);
2750 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2751 /* the channel is already in these formats, so nothing to do */
2752 ast_channel_unlock(chan);
2753 return 0;
2756 *rawformat = native;
2757 /* User perspective is fmt */
2758 *format = fmt;
2759 /* Free any read translation we have right now */
2760 if (*trans)
2761 ast_translator_free_path(*trans);
2762 /* Build a translation path from the raw format to the desired format */
2763 if (!direction)
2764 /* reading */
2765 *trans = ast_translator_build_path(*format, *rawformat);
2766 else
2767 /* writing */
2768 *trans = ast_translator_build_path(*rawformat, *format);
2769 ast_channel_unlock(chan);
2770 if (option_debug)
2771 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2772 direction ? "write" : "read", ast_getformatname(fmt));
2773 return 0;
2776 int ast_set_read_format(struct ast_channel *chan, int fmt)
2778 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2779 &chan->readtrans, 0);
2782 int ast_set_write_format(struct ast_channel *chan, int fmt)
2784 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2785 &chan->writetrans, 1);
2788 char *ast_channel_reason2str(int reason)
2790 switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
2792 case 0:
2793 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
2794 case AST_CONTROL_HANGUP:
2795 return "Hangup";
2796 case AST_CONTROL_RING:
2797 return "Local Ring";
2798 case AST_CONTROL_RINGING:
2799 return "Remote end Ringing";
2800 case AST_CONTROL_ANSWER:
2801 return "Remote end has Answered";
2802 case AST_CONTROL_BUSY:
2803 return "Remote end is Busy";
2804 case AST_CONTROL_CONGESTION:
2805 return "Congestion (circuits busy)";
2806 default:
2807 return "Unknown Reason!!";
2811 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)
2813 int dummy_outstate;
2814 int cause = 0;
2815 struct ast_channel *chan;
2816 int res = 0;
2817 int last_subclass = 0;
2819 if (outstate)
2820 *outstate = 0;
2821 else
2822 outstate = &dummy_outstate; /* make outstate always a valid pointer */
2824 chan = ast_request(type, format, data, &cause);
2825 if (!chan) {
2826 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2827 /* compute error and return */
2828 if (cause == AST_CAUSE_BUSY)
2829 *outstate = AST_CONTROL_BUSY;
2830 else if (cause == AST_CAUSE_CONGESTION)
2831 *outstate = AST_CONTROL_CONGESTION;
2832 return NULL;
2835 if (oh) {
2836 if (oh->vars)
2837 ast_set_variables(chan, oh->vars);
2838 /* XXX why is this necessary, for the parent_channel perhaps ? */
2839 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2840 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2841 if (oh->parent_channel)
2842 ast_channel_inherit_variables(oh->parent_channel, chan);
2843 if (oh->account)
2844 ast_cdr_setaccount(chan, oh->account);
2846 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2850 if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2851 to keep from throwing off the basic order of the universe,
2852 we will try to keep this cdr from getting posted. */
2853 chan->cdr = ast_cdr_alloc();
2854 ast_cdr_init(chan->cdr, chan);
2855 ast_cdr_start(chan->cdr);
2857 if (ast_call(chan, data, 0)) { /* ast_call failed... */
2858 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2859 } else {
2860 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
2861 while (timeout && chan->_state != AST_STATE_UP) {
2862 struct ast_frame *f;
2863 res = ast_waitfor(chan, timeout);
2864 if (res <= 0) /* error, timeout, or done */
2865 break;
2866 if (timeout > -1)
2867 timeout = res;
2868 f = ast_read(chan);
2869 if (!f) {
2870 *outstate = AST_CONTROL_HANGUP;
2871 res = 0;
2872 break;
2874 if (f->frametype == AST_FRAME_CONTROL) {
2875 switch (f->subclass) {
2876 case AST_CONTROL_RINGING: /* record but keep going */
2877 *outstate = f->subclass;
2878 break;
2880 case AST_CONTROL_BUSY:
2881 case AST_CONTROL_CONGESTION:
2882 case AST_CONTROL_ANSWER:
2883 *outstate = f->subclass;
2884 timeout = 0; /* trick to force exit from the while() */
2885 break;
2887 /* Ignore these */
2888 case AST_CONTROL_PROGRESS:
2889 case AST_CONTROL_PROCEEDING:
2890 case AST_CONTROL_HOLD:
2891 case AST_CONTROL_UNHOLD:
2892 case AST_CONTROL_VIDUPDATE:
2893 case -1: /* Ignore -- just stopping indications */
2894 break;
2896 default:
2897 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2899 last_subclass = f->subclass;
2901 ast_frfree(f);
2905 /* Final fixups */
2906 if (oh) {
2907 if (!ast_strlen_zero(oh->context))
2908 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2909 if (!ast_strlen_zero(oh->exten))
2910 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2911 if (oh->priority)
2912 chan->priority = oh->priority;
2914 if (chan->_state == AST_STATE_UP)
2915 *outstate = AST_CONTROL_ANSWER;
2917 if (res <= 0) {
2918 if ( AST_CONTROL_RINGING == last_subclass )
2919 chan->hangupcause = AST_CAUSE_NO_ANSWER;
2920 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2921 ast_cdr_init(chan->cdr, chan);
2922 if (chan->cdr) {
2923 char tmp[256];
2924 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2925 ast_cdr_setapp(chan->cdr,"Dial",tmp);
2926 ast_cdr_update(chan);
2927 ast_cdr_start(chan->cdr);
2928 ast_cdr_end(chan->cdr);
2929 /* If the cause wasn't handled properly */
2930 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2931 ast_cdr_failed(chan->cdr);
2933 ast_hangup(chan);
2934 chan = NULL;
2936 return chan;
2939 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2941 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2944 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2946 struct chanlist *chan;
2947 struct ast_channel *c;
2948 int capabilities;
2949 int fmt;
2950 int res;
2951 int foo;
2952 int videoformat = format & AST_FORMAT_VIDEO_MASK;
2954 if (!cause)
2955 cause = &foo;
2956 *cause = AST_CAUSE_NOTDEFINED;
2958 if (AST_LIST_LOCK(&channels)) {
2959 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2960 return NULL;
2963 AST_LIST_TRAVERSE(&backends, chan, list) {
2964 if (strcasecmp(type, chan->tech->type))
2965 continue;
2967 capabilities = chan->tech->capabilities;
2968 fmt = format & AST_FORMAT_AUDIO_MASK;
2969 res = ast_translator_best_choice(&fmt, &capabilities);
2970 if (res < 0) {
2971 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2972 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2973 AST_LIST_UNLOCK(&channels);
2974 return NULL;
2976 AST_LIST_UNLOCK(&channels);
2977 if (!chan->tech->requester)
2978 return NULL;
2980 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
2981 return NULL;
2983 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
2984 return c;
2987 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2988 *cause = AST_CAUSE_NOSUCHDRIVER;
2989 AST_LIST_UNLOCK(&channels);
2991 return NULL;
2994 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2996 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2997 If the remote end does not answer within the timeout, then do NOT hang up, but
2998 return anyway. */
2999 int res = -1;
3000 /* Stop if we're a zombie or need a soft hangup */
3001 ast_channel_lock(chan);
3002 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3003 if (chan->tech->call)
3004 res = chan->tech->call(chan, addr, timeout);
3005 ast_set_flag(chan, AST_FLAG_OUTGOING);
3007 ast_channel_unlock(chan);
3008 return res;
3012 \brief Transfer a call to dest, if the channel supports transfer
3014 Called by:
3015 \arg app_transfer
3016 \arg the manager interface
3018 int ast_transfer(struct ast_channel *chan, char *dest)
3020 int res = -1;
3022 /* Stop if we're a zombie or need a soft hangup */
3023 ast_channel_lock(chan);
3024 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3025 if (chan->tech->transfer) {
3026 res = chan->tech->transfer(chan, dest);
3027 if (!res)
3028 res = 1;
3029 } else
3030 res = 0;
3032 ast_channel_unlock(chan);
3033 return res;
3036 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3038 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3041 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3043 int pos = 0; /* index in the buffer where we accumulate digits */
3044 int to = ftimeout;
3046 /* Stop if we're a zombie or need a soft hangup */
3047 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3048 return -1;
3049 if (!len)
3050 return -1;
3051 for (;;) {
3052 int d;
3053 if (c->stream) {
3054 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3055 ast_stopstream(c);
3056 usleep(1000);
3057 if (!d)
3058 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3059 } else {
3060 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3062 if (d < 0)
3063 return -1;
3064 if (d == 0) {
3065 s[pos]='\0';
3066 return 1;
3068 if (d == 1) {
3069 s[pos]='\0';
3070 return 2;
3072 if (!strchr(enders, d))
3073 s[pos++] = d;
3074 if (strchr(enders, d) || (pos >= len)) {
3075 s[pos]='\0';
3076 return 0;
3078 to = timeout;
3080 /* Never reached */
3081 return 0;
3084 int ast_channel_supports_html(struct ast_channel *chan)
3086 return (chan->tech->send_html) ? 1 : 0;
3089 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3091 if (chan->tech->send_html)
3092 return chan->tech->send_html(chan, subclass, data, datalen);
3093 return -1;
3096 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3098 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3101 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3103 int src;
3104 int dst;
3106 if (chan->readformat == peer->writeformat && chan->writeformat == peer->readformat) {
3107 /* Already compatible! Moving on ... */
3108 return 0;
3111 /* Set up translation from the chan to the peer */
3112 src = chan->nativeformats;
3113 dst = peer->nativeformats;
3114 if (ast_translator_best_choice(&dst, &src) < 0) {
3115 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
3116 return -1;
3119 /* if the best path is not 'pass through', then
3120 transcoding is needed; if desired, force transcode path
3121 to use SLINEAR between channels, but only if there is
3122 no direct conversion available */
3123 if ((src != dst) && ast_opt_transcode_via_slin &&
3124 (ast_translate_path_steps(dst, src) != 1))
3125 dst = AST_FORMAT_SLINEAR;
3126 if (ast_set_read_format(chan, dst) < 0) {
3127 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
3128 return -1;
3130 if (ast_set_write_format(peer, dst) < 0) {
3131 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
3132 return -1;
3135 /* Set up translation from the peer to the chan */
3136 src = peer->nativeformats;
3137 dst = chan->nativeformats;
3138 if (ast_translator_best_choice(&dst, &src) < 0) {
3139 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
3140 return -1;
3143 /* if the best path is not 'pass through', then
3144 transcoding is needed; if desired, force transcode path
3145 to use SLINEAR between channels, but only if there is
3146 no direct conversion available */
3147 if ((src != dst) && ast_opt_transcode_via_slin &&
3148 (ast_translate_path_steps(dst, src) != 1))
3149 dst = AST_FORMAT_SLINEAR;
3150 if (ast_set_read_format(peer, dst) < 0) {
3151 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
3152 return -1;
3154 if (ast_set_write_format(chan, dst) < 0) {
3155 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
3156 return -1;
3158 return 0;
3161 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3163 int res = -1;
3164 struct ast_channel *final_orig, *final_clone, *base;
3166 retrymasq:
3167 final_orig = original;
3168 final_clone = clone;
3170 ast_channel_lock(original);
3171 while (ast_channel_trylock(clone)) {
3172 ast_channel_unlock(original);
3173 usleep(1);
3174 ast_channel_lock(original);
3177 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3178 and if so, we don't really want to masquerade it, but its proxy */
3179 if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
3180 final_orig = original->_bridge;
3182 if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)) && (clone->_bridge->_bridge != clone))
3183 final_clone = clone->_bridge;
3185 if (final_clone->tech->get_base_channel && (base = final_clone->tech->get_base_channel(final_clone))) {
3186 final_clone = base;
3189 if ((final_orig != original) || (final_clone != clone)) {
3190 /* Lots and lots of deadlock avoidance. The main one we're competing with
3191 * is ast_write(), which locks channels recursively, when working with a
3192 * proxy channel. */
3193 if (ast_channel_trylock(final_orig)) {
3194 ast_channel_unlock(clone);
3195 ast_channel_unlock(original);
3196 goto retrymasq;
3198 if (ast_channel_trylock(final_clone)) {
3199 ast_channel_unlock(final_orig);
3200 ast_channel_unlock(clone);
3201 ast_channel_unlock(original);
3202 goto retrymasq;
3204 ast_channel_unlock(clone);
3205 ast_channel_unlock(original);
3206 original = final_orig;
3207 clone = final_clone;
3210 if (original == clone) {
3211 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3212 ast_channel_unlock(clone);
3213 ast_channel_unlock(original);
3214 return -1;
3217 if (option_debug)
3218 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
3219 clone->name, original->name);
3220 if (original->masq) {
3221 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3222 original->masq->name, original->name);
3223 } else if (clone->masqr) {
3224 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3225 clone->name, clone->masqr->name);
3226 } else {
3227 original->masq = clone;
3228 clone->masqr = original;
3229 ast_queue_frame(original, &ast_null_frame);
3230 ast_queue_frame(clone, &ast_null_frame);
3231 if (option_debug)
3232 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3233 res = 0;
3236 ast_channel_unlock(clone);
3237 ast_channel_unlock(original);
3239 return res;
3242 void ast_change_name(struct ast_channel *chan, char *newname)
3244 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3245 ast_string_field_set(chan, name, newname);
3248 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3250 struct ast_var_t *current, *newvar;
3251 const char *varname;
3253 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3254 int vartype = 0;
3256 varname = ast_var_full_name(current);
3257 if (!varname)
3258 continue;
3260 if (varname[0] == '_') {
3261 vartype = 1;
3262 if (varname[1] == '_')
3263 vartype = 2;
3266 switch (vartype) {
3267 case 1:
3268 newvar = ast_var_assign(&varname[1], ast_var_value(current));
3269 if (newvar) {
3270 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3271 if (option_debug)
3272 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3274 break;
3275 case 2:
3276 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
3277 if (newvar) {
3278 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3279 if (option_debug)
3280 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3282 break;
3283 default:
3284 if (option_debug)
3285 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
3286 break;
3292 \brief Clone channel variables from 'clone' channel into 'original' channel
3294 All variables except those related to app_groupcount are cloned.
3295 Variables are actually _removed_ from 'clone' channel, presumably
3296 because it will subsequently be destroyed.
3298 \note Assumes locks will be in place on both channels when called.
3300 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3302 struct ast_var_t *current, *newvar;
3303 /* Append variables from clone channel into original channel */
3304 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3305 if (AST_LIST_FIRST(&clone->varshead))
3306 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3308 /* then, dup the varshead list into the clone */
3310 AST_LIST_TRAVERSE(&original->varshead, current, entries) {
3311 newvar = ast_var_assign(current->name, current->value);
3312 if (newvar)
3313 AST_LIST_INSERT_TAIL(&clone->varshead, newvar, entries);
3318 \brief Masquerade a channel
3320 \note Assumes channel will be locked when called
3322 int ast_do_masquerade(struct ast_channel *original)
3324 int x,i;
3325 int res=0;
3326 int origstate;
3327 struct ast_frame *cur;
3328 const struct ast_channel_tech *t;
3329 void *t_pvt;
3330 struct ast_callerid tmpcid;
3331 struct ast_channel *clone = original->masq;
3332 struct ast_cdr *cdr;
3333 int rformat = original->readformat;
3334 int wformat = original->writeformat;
3335 char newn[100];
3336 char orig[100];
3337 char masqn[100];
3338 char zombn[100];
3340 if (option_debug > 3)
3341 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3342 clone->name, clone->_state, original->name, original->_state);
3344 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3345 the clone channel into the original channel. Start by killing off the original
3346 channel's backend. I'm not sure we're going to keep this function, because
3347 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3349 /* We need the clone's lock, too */
3350 ast_channel_lock(clone);
3352 if (option_debug > 1)
3353 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3355 /* Having remembered the original read/write formats, we turn off any translation on either
3356 one */
3357 free_translation(clone);
3358 free_translation(original);
3361 /* Unlink the masquerade */
3362 original->masq = NULL;
3363 clone->masqr = NULL;
3365 /* Save the original name */
3366 ast_copy_string(orig, original->name, sizeof(orig));
3367 /* Save the new name */
3368 ast_copy_string(newn, clone->name, sizeof(newn));
3369 /* Create the masq name */
3370 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3372 /* Copy the name from the clone channel */
3373 ast_string_field_set(original, name, newn);
3375 /* Mangle the name of the clone channel */
3376 ast_string_field_set(clone, name, masqn);
3378 /* Notify any managers of the change, first the masq then the other */
3379 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3380 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3382 /* Swap the technologies */
3383 t = original->tech;
3384 original->tech = clone->tech;
3385 clone->tech = t;
3387 /* Swap the cdrs */
3388 cdr = original->cdr;
3389 original->cdr = clone->cdr;
3390 clone->cdr = cdr;
3392 t_pvt = original->tech_pvt;
3393 original->tech_pvt = clone->tech_pvt;
3394 clone->tech_pvt = t_pvt;
3396 /* Swap the alertpipes */
3397 for (i = 0; i < 2; i++) {
3398 x = original->alertpipe[i];
3399 original->alertpipe[i] = clone->alertpipe[i];
3400 clone->alertpipe[i] = x;
3404 * Swap the readq's. The end result should be this:
3406 * 1) All frames should be on the new (original) channel.
3407 * 2) Any frames that were already on the new channel before this
3408 * masquerade need to be at the end of the readq, after all of the
3409 * frames on the old (clone) channel.
3410 * 3) The alertpipe needs to get poked for every frame that was already
3411 * on the new channel, since we are now using the alert pipe from the
3412 * old (clone) channel.
3415 AST_LIST_HEAD_NOLOCK(, ast_frame) tmp_readq;
3416 AST_LIST_HEAD_SET_NOLOCK(&tmp_readq, NULL);
3418 AST_LIST_APPEND_LIST(&tmp_readq, &original->readq, frame_list);
3419 AST_LIST_APPEND_LIST(&original->readq, &clone->readq, frame_list);
3421 while ((cur = AST_LIST_REMOVE_HEAD(&tmp_readq, frame_list))) {
3422 AST_LIST_INSERT_TAIL(&original->readq, cur, frame_list);
3423 if (original->alertpipe[1] > -1) {
3424 int poke = 0;
3425 write(original->alertpipe[1], &poke, sizeof(poke));
3430 /* Swap the raw formats */
3431 x = original->rawreadformat;
3432 original->rawreadformat = clone->rawreadformat;
3433 clone->rawreadformat = x;
3434 x = original->rawwriteformat;
3435 original->rawwriteformat = clone->rawwriteformat;
3436 clone->rawwriteformat = x;
3438 clone->_softhangup = AST_SOFTHANGUP_DEV;
3440 /* And of course, so does our current state. Note we need not
3441 call ast_setstate since the event manager doesn't really consider
3442 these separate. We do this early so that the clone has the proper
3443 state of the original channel. */
3444 origstate = original->_state;
3445 original->_state = clone->_state;
3446 clone->_state = origstate;
3448 if (clone->tech->fixup){
3449 res = clone->tech->fixup(original, clone);
3450 if (res)
3451 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3454 /* Start by disconnecting the original's physical side */
3455 if (clone->tech->hangup)
3456 res = clone->tech->hangup(clone);
3457 if (res) {
3458 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
3459 ast_channel_unlock(clone);
3460 return -1;
3463 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3464 /* Mangle the name of the clone channel */
3465 ast_string_field_set(clone, name, zombn);
3466 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3468 /* Update the type. */
3469 t_pvt = original->monitor;
3470 original->monitor = clone->monitor;
3471 clone->monitor = t_pvt;
3473 /* Keep the same language. */
3474 ast_string_field_set(original, language, clone->language);
3475 /* Copy the FD's other than the generator fd */
3476 for (x = 0; x < AST_MAX_FDS; x++) {
3477 if (x != AST_GENERATOR_FD)
3478 original->fds[x] = clone->fds[x];
3481 ast_app_group_update(clone, original);
3482 /* Move data stores over */
3483 if (AST_LIST_FIRST(&clone->datastores))
3484 AST_LIST_APPEND_LIST(&original->datastores, &clone->datastores, entry);
3486 clone_variables(original, clone);
3487 /* Presense of ADSI capable CPE follows clone */
3488 original->adsicpe = clone->adsicpe;
3489 /* Bridge remains the same */
3490 /* CDR fields remain the same */
3491 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3492 /* Application and data remain the same */
3493 /* Clone exception becomes real one, as with fdno */
3494 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3495 original->fdno = clone->fdno;
3496 /* Schedule context remains the same */
3497 /* Stream stuff stays the same */
3498 /* Keep the original state. The fixup code will need to work with it most likely */
3500 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3501 out. */
3502 tmpcid = original->cid;
3503 original->cid = clone->cid;
3504 clone->cid = tmpcid;
3506 /* Restore original timing file descriptor */
3507 original->fds[AST_TIMING_FD] = original->timingfd;
3509 /* Our native formats are different now */
3510 original->nativeformats = clone->nativeformats;
3512 /* Context, extension, priority, app data, jump table, remain the same */
3513 /* pvt switches. pbx stays the same, as does next */
3515 /* Set the write format */
3516 ast_set_write_format(original, wformat);
3518 /* Set the read format */
3519 ast_set_read_format(original, rformat);
3521 /* Copy the music class */
3522 ast_string_field_set(original, musicclass, clone->musicclass);
3524 if (option_debug)
3525 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3527 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3528 can fix up everything as best as possible */
3529 if (original->tech->fixup) {
3530 res = original->tech->fixup(clone, original);
3531 if (res) {
3532 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3533 original->tech->type, original->name);
3534 ast_channel_unlock(clone);
3535 return -1;
3537 } else
3538 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
3539 original->tech->type, original->name);
3541 /* If an indication is currently playing maintain it on the channel that is taking the place of original */
3542 if (original->visible_indication)
3543 ast_indicate(original, original->visible_indication);
3545 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
3546 a zombie so nothing tries to touch it. If it's already been marked as a
3547 zombie, then free it now (since it already is considered invalid). */
3548 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3549 if (option_debug)
3550 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3551 ast_channel_unlock(clone);
3552 manager_event(EVENT_FLAG_CALL, "Hangup",
3553 "Channel: %s\r\n"
3554 "Uniqueid: %s\r\n"
3555 "Cause: %d\r\n"
3556 "Cause-txt: %s\r\n",
3557 clone->name,
3558 clone->uniqueid,
3559 clone->hangupcause,
3560 ast_cause2str(clone->hangupcause)
3562 ast_channel_free(clone);
3563 } else {
3564 if (option_debug)
3565 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3566 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3567 ast_queue_frame(clone, &ast_null_frame);
3568 ast_channel_unlock(clone);
3571 /* Signal any blocker */
3572 if (ast_test_flag(original, AST_FLAG_BLOCKING))
3573 pthread_kill(original->blocker, SIGURG);
3574 if (option_debug)
3575 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3576 return 0;
3579 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3581 ast_channel_lock(chan);
3583 if (callerid) {
3584 if (chan->cid.cid_num)
3585 free(chan->cid.cid_num);
3586 chan->cid.cid_num = ast_strdup(callerid);
3588 if (calleridname) {
3589 if (chan->cid.cid_name)
3590 free(chan->cid.cid_name);
3591 chan->cid.cid_name = ast_strdup(calleridname);
3593 if (ani) {
3594 if (chan->cid.cid_ani)
3595 free(chan->cid.cid_ani);
3596 chan->cid.cid_ani = ast_strdup(ani);
3598 if (chan->cdr)
3599 ast_cdr_setcid(chan->cdr, chan);
3600 manager_event(EVENT_FLAG_CALL, "Newcallerid",
3601 "Channel: %s\r\n"
3602 "CallerID: %s\r\n"
3603 "CallerIDName: %s\r\n"
3604 "Uniqueid: %s\r\n"
3605 "CID-CallingPres: %d (%s)\r\n",
3606 chan->name,
3607 S_OR(chan->cid.cid_num, "<Unknown>"),
3608 S_OR(chan->cid.cid_name, "<Unknown>"),
3609 chan->uniqueid,
3610 chan->cid.cid_pres,
3611 ast_describe_caller_presentation(chan->cid.cid_pres)
3614 ast_channel_unlock(chan);
3617 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
3619 int oldstate = chan->_state;
3621 if (oldstate == state)
3622 return 0;
3624 chan->_state = state;
3625 ast_device_state_changed_literal(chan->name);
3626 /* setstate used to conditionally report Newchannel; this is no more */
3627 manager_event(EVENT_FLAG_CALL,
3628 "Newstate",
3629 "Channel: %s\r\n"
3630 "State: %s\r\n"
3631 "CallerID: %s\r\n"
3632 "CallerIDName: %s\r\n"
3633 "Uniqueid: %s\r\n",
3634 chan->name, ast_state2str(chan->_state),
3635 S_OR(chan->cid.cid_num, "<unknown>"),
3636 S_OR(chan->cid.cid_name, "<unknown>"),
3637 chan->uniqueid);
3639 return 0;
3642 /*! \brief Find bridged channel */
3643 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3645 struct ast_channel *bridged;
3646 bridged = chan->_bridge;
3647 if (bridged && bridged->tech->bridged_channel)
3648 bridged = bridged->tech->bridged_channel(chan, bridged);
3649 return bridged;
3652 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3654 int min = 0, sec = 0, check;
3656 check = ast_autoservice_start(peer);
3657 if (check)
3658 return;
3660 if (remain > 0) {
3661 if (remain / 60 > 1) {
3662 min = remain / 60;
3663 sec = remain % 60;
3664 } else {
3665 sec = remain;
3669 if (!strcmp(sound,"timeleft")) { /* Queue support */
3670 ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
3671 if (min) {
3672 ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
3673 ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
3675 if (sec) {
3676 ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
3677 ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
3679 } else {
3680 ast_stream_and_wait(chan, sound, chan->language, "");
3683 ast_autoservice_stop(peer);
3686 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3687 struct ast_bridge_config *config, struct ast_frame **fo,
3688 struct ast_channel **rc, struct timeval bridge_end)
3690 /* Copy voice back and forth between the two channels. */
3691 struct ast_channel *cs[3];
3692 struct ast_frame *f;
3693 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3694 int o0nativeformats;
3695 int o1nativeformats;
3696 int watch_c0_dtmf;
3697 int watch_c1_dtmf;
3698 void *pvt0, *pvt1;
3699 /* Indicates whether a frame was queued into a jitterbuffer */
3700 int frame_put_in_jb = 0;
3701 int jb_in_use;
3702 int to;
3704 cs[0] = c0;
3705 cs[1] = c1;
3706 pvt0 = c0->tech_pvt;
3707 pvt1 = c1->tech_pvt;
3708 o0nativeformats = c0->nativeformats;
3709 o1nativeformats = c1->nativeformats;
3710 watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3711 watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3713 /* Check the need of a jitterbuffer for each channel */
3714 jb_in_use = ast_jb_do_usecheck(c0, c1);
3716 for (;;) {
3717 struct ast_channel *who, *other;
3719 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3720 (o0nativeformats != c0->nativeformats) ||
3721 (o1nativeformats != c1->nativeformats)) {
3722 /* Check for Masquerade, codec changes, etc */
3723 res = AST_BRIDGE_RETRY;
3724 break;
3726 if (bridge_end.tv_sec) {
3727 to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3728 if (to <= 0) {
3729 if (config->timelimit)
3730 res = AST_BRIDGE_RETRY;
3731 else
3732 res = AST_BRIDGE_COMPLETE;
3733 break;
3735 } else
3736 to = -1;
3737 /* Calculate the appropriate max sleep interval - in general, this is the time,
3738 left to the closest jb delivery moment */
3739 if (jb_in_use)
3740 to = ast_jb_get_when_to_wakeup(c0, c1, to);
3741 who = ast_waitfor_n(cs, 2, &to);
3742 if (!who) {
3743 /* No frame received within the specified timeout - check if we have to deliver now */
3744 if (jb_in_use)
3745 ast_jb_get_and_deliver(c0, c1);
3746 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3747 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3748 c0->_softhangup = 0;
3749 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3750 c1->_softhangup = 0;
3751 c0->_bridge = c1;
3752 c1->_bridge = c0;
3754 continue;
3756 f = ast_read(who);
3757 if (!f) {
3758 *fo = NULL;
3759 *rc = who;
3760 if (option_debug)
3761 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3762 break;
3765 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3766 /* Try add the frame info the who's bridged channel jitterbuff */
3767 if (jb_in_use)
3768 frame_put_in_jb = !ast_jb_put(other, f);
3770 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3771 int bridge_exit = 0;
3773 switch (f->subclass) {
3774 case AST_CONTROL_HOLD:
3775 case AST_CONTROL_UNHOLD:
3776 case AST_CONTROL_VIDUPDATE:
3777 ast_indicate_data(other, f->subclass, f->data, f->datalen);
3778 break;
3779 default:
3780 *fo = f;
3781 *rc = who;
3782 bridge_exit = 1;
3783 if (option_debug)
3784 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3785 break;
3787 if (bridge_exit)
3788 break;
3790 if ((f->frametype == AST_FRAME_VOICE) ||
3791 (f->frametype == AST_FRAME_DTMF_BEGIN) ||
3792 (f->frametype == AST_FRAME_DTMF) ||
3793 (f->frametype == AST_FRAME_VIDEO) ||
3794 (f->frametype == AST_FRAME_IMAGE) ||
3795 (f->frametype == AST_FRAME_HTML) ||
3796 (f->frametype == AST_FRAME_MODEM) ||
3797 (f->frametype == AST_FRAME_TEXT)) {
3798 /* monitored dtmf causes exit from bridge */
3799 int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
3801 if (monitored_source &&
3802 (f->frametype == AST_FRAME_DTMF_END ||
3803 f->frametype == AST_FRAME_DTMF_BEGIN)) {
3804 *fo = f;
3805 *rc = who;
3806 if (option_debug)
3807 ast_log(LOG_DEBUG, "Got DTMF %s on channel (%s)\n",
3808 f->frametype == AST_FRAME_DTMF_END ? "end" : "begin",
3809 who->name);
3810 break;
3812 /* Write immediately frames, not passed through jb */
3813 if (!frame_put_in_jb)
3814 ast_write(other, f);
3816 /* Check if we have to deliver now */
3817 if (jb_in_use)
3818 ast_jb_get_and_deliver(c0, c1);
3820 /* XXX do we want to pass on also frames not matched above ? */
3821 ast_frfree(f);
3823 /* Swap who gets priority */
3824 cs[2] = cs[0];
3825 cs[0] = cs[1];
3826 cs[1] = cs[2];
3828 return res;
3831 /*! \brief Bridge two channels together */
3832 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3833 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
3835 struct ast_channel *who = NULL;
3836 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3837 int nativefailed=0;
3838 int firstpass;
3839 int o0nativeformats;
3840 int o1nativeformats;
3841 long time_left_ms=0;
3842 struct timeval nexteventts = { 0, };
3843 char caller_warning = 0;
3844 char callee_warning = 0;
3846 if (c0->_bridge) {
3847 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3848 c0->name, c0->_bridge->name);
3849 return -1;
3851 if (c1->_bridge) {
3852 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3853 c1->name, c1->_bridge->name);
3854 return -1;
3857 /* Stop if we're a zombie or need a soft hangup */
3858 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3859 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3860 return -1;
3862 *fo = NULL;
3863 firstpass = config->firstpass;
3864 config->firstpass = 0;
3866 if (ast_tvzero(config->start_time))
3867 config->start_time = ast_tvnow();
3868 time_left_ms = config->timelimit;
3870 caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3871 callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3873 if (config->start_sound && firstpass) {
3874 if (caller_warning)
3875 bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3876 if (callee_warning)
3877 bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3880 /* Keep track of bridge */
3881 c0->_bridge = c1;
3882 c1->_bridge = c0;
3884 /* \todo XXX here should check that cid_num is not NULL */
3885 manager_event(EVENT_FLAG_CALL, "Link",
3886 "Channel1: %s\r\n"
3887 "Channel2: %s\r\n"
3888 "Uniqueid1: %s\r\n"
3889 "Uniqueid2: %s\r\n"
3890 "CallerID1: %s\r\n"
3891 "CallerID2: %s\r\n",
3892 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3894 o0nativeformats = c0->nativeformats;
3895 o1nativeformats = c1->nativeformats;
3897 if (config->feature_timer) {
3898 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->feature_timer, 1000));
3899 } else if (config->timelimit) {
3900 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3901 if (caller_warning || callee_warning)
3902 nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
3905 if (!c0->tech->send_digit_begin)
3906 ast_set_flag(c1, AST_FLAG_END_DTMF_ONLY);
3907 if (!c1->tech->send_digit_begin)
3908 ast_set_flag(c0, AST_FLAG_END_DTMF_ONLY);
3910 for (/* ever */;;) {
3911 struct timeval now = { 0, };
3912 int to;
3914 to = -1;
3916 if (!ast_tvzero(nexteventts)) {
3917 now = ast_tvnow();
3918 to = ast_tvdiff_ms(nexteventts, now);
3919 if (to <= 0) {
3920 if (!config->timelimit) {
3921 res = AST_BRIDGE_COMPLETE;
3922 break;
3924 to = 0;
3928 if (config->timelimit) {
3929 time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
3930 if (time_left_ms < to)
3931 to = time_left_ms;
3933 if (time_left_ms <= 0) {
3934 if (caller_warning && config->end_sound)
3935 bridge_playfile(c0, c1, config->end_sound, 0);
3936 if (callee_warning && config->end_sound)
3937 bridge_playfile(c1, c0, config->end_sound, 0);
3938 *fo = NULL;
3939 if (who)
3940 *rc = who;
3941 res = 0;
3942 break;
3945 if (!to) {
3946 if (time_left_ms >= 5000 && config->warning_sound && config->play_warning) {
3947 int t = (time_left_ms + 500) / 1000; /* round to nearest second */
3948 if (caller_warning)
3949 bridge_playfile(c0, c1, config->warning_sound, t);
3950 if (callee_warning)
3951 bridge_playfile(c1, c0, config->warning_sound, t);
3953 if (config->warning_freq && (time_left_ms > (config->warning_freq + 5000)))
3954 nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
3955 else
3956 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3960 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3961 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3962 c0->_softhangup = 0;
3963 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3964 c1->_softhangup = 0;
3965 c0->_bridge = c1;
3966 c1->_bridge = c0;
3967 if (option_debug)
3968 ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3969 continue;
3972 /* Stop if we're a zombie or need a soft hangup */
3973 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3974 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
3975 *fo = NULL;
3976 if (who)
3977 *rc = who;
3978 res = 0;
3979 if (option_debug)
3980 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",
3981 c0->name, c1->name,
3982 ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
3983 ast_check_hangup(c0) ? "Yes" : "No",
3984 ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
3985 ast_check_hangup(c1) ? "Yes" : "No");
3986 break;
3989 /* See if the BRIDGEPEER variable needs to be updated */
3990 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER")))
3991 pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1->name);
3992 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER")))
3993 pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0->name);
3995 if (c0->tech->bridge &&
3996 (config->timelimit == 0) &&
3997 (c0->tech->bridge == c1->tech->bridge) &&
3998 !nativefailed && !c0->monitor && !c1->monitor &&
3999 !c0->audiohooks && !c1->audiohooks && !ast_test_flag(&(config->features_callee),AST_FEATURE_REDIRECT) &&
4000 !ast_test_flag(&(config->features_caller),AST_FEATURE_REDIRECT) &&
4001 !c0->masq && !c0->masqr && !c1->masq && !c1->masqr) {
4002 /* Looks like they share a bridge method and nothing else is in the way */
4003 ast_set_flag(c0, AST_FLAG_NBRIDGE);
4004 ast_set_flag(c1, AST_FLAG_NBRIDGE);
4005 if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, to)) == AST_BRIDGE_COMPLETE) {
4006 /* \todo XXX here should check that cid_num is not NULL */
4007 manager_event(EVENT_FLAG_CALL, "Unlink",
4008 "Channel1: %s\r\n"
4009 "Channel2: %s\r\n"
4010 "Uniqueid1: %s\r\n"
4011 "Uniqueid2: %s\r\n"
4012 "CallerID1: %s\r\n"
4013 "CallerID2: %s\r\n",
4014 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4015 if (option_debug)
4016 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
4018 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
4019 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
4021 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4022 continue;
4024 c0->_bridge = NULL;
4025 c1->_bridge = NULL;
4027 return res;
4028 } else {
4029 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
4030 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
4032 switch (res) {
4033 case AST_BRIDGE_RETRY:
4034 continue;
4035 default:
4036 if (option_verbose > 2)
4037 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s ended\n",
4038 c0->name, c1->name);
4039 /* fallthrough */
4040 case AST_BRIDGE_FAILED_NOWARN:
4041 nativefailed++;
4042 break;
4046 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
4047 (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
4048 !(c0->generator || c1->generator)) {
4049 if (ast_channel_make_compatible(c0, c1)) {
4050 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
4051 /* \todo XXX here should check that cid_num is not NULL */
4052 manager_event(EVENT_FLAG_CALL, "Unlink",
4053 "Channel1: %s\r\n"
4054 "Channel2: %s\r\n"
4055 "Uniqueid1: %s\r\n"
4056 "Uniqueid2: %s\r\n"
4057 "CallerID1: %s\r\n"
4058 "CallerID2: %s\r\n",
4059 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4060 return AST_BRIDGE_FAILED;
4062 o0nativeformats = c0->nativeformats;
4063 o1nativeformats = c1->nativeformats;
4065 res = ast_generic_bridge(c0, c1, config, fo, rc, nexteventts);
4066 if (res != AST_BRIDGE_RETRY)
4067 break;
4070 ast_clear_flag(c0, AST_FLAG_END_DTMF_ONLY);
4071 ast_clear_flag(c1, AST_FLAG_END_DTMF_ONLY);
4073 c0->_bridge = NULL;
4074 c1->_bridge = NULL;
4076 /* \todo XXX here should check that cid_num is not NULL */
4077 manager_event(EVENT_FLAG_CALL, "Unlink",
4078 "Channel1: %s\r\n"
4079 "Channel2: %s\r\n"
4080 "Uniqueid1: %s\r\n"
4081 "Uniqueid2: %s\r\n"
4082 "CallerID1: %s\r\n"
4083 "CallerID2: %s\r\n",
4084 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4085 if (option_debug)
4086 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
4088 return res;
4091 /*! \brief Sets an option on a channel */
4092 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
4094 int res;
4096 if (chan->tech->setoption) {
4097 res = chan->tech->setoption(chan, option, data, datalen);
4098 if (res < 0)
4099 return res;
4100 } else {
4101 errno = ENOSYS;
4102 return -1;
4104 if (block) {
4105 /* XXX Implement blocking -- just wait for our option frame reply, discarding
4106 intermediate packets. XXX */
4107 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
4108 return -1;
4110 return 0;
4113 struct tonepair_def {
4114 int freq1;
4115 int freq2;
4116 int duration;
4117 int vol;
4120 struct tonepair_state {
4121 int fac1;
4122 int fac2;
4123 int v1_1;
4124 int v2_1;
4125 int v3_1;
4126 int v1_2;
4127 int v2_2;
4128 int v3_2;
4129 int origwfmt;
4130 int pos;
4131 int duration;
4132 int modulate;
4133 struct ast_frame f;
4134 unsigned char offset[AST_FRIENDLY_OFFSET];
4135 short data[4000];
4138 static void tonepair_release(struct ast_channel *chan, void *params)
4140 struct tonepair_state *ts = params;
4142 if (chan)
4143 ast_set_write_format(chan, ts->origwfmt);
4144 free(ts);
4147 static void *tonepair_alloc(struct ast_channel *chan, void *params)
4149 struct tonepair_state *ts;
4150 struct tonepair_def *td = params;
4152 if (!(ts = ast_calloc(1, sizeof(*ts))))
4153 return NULL;
4154 ts->origwfmt = chan->writeformat;
4155 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
4156 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
4157 tonepair_release(NULL, ts);
4158 ts = NULL;
4159 } else {
4160 ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
4161 ts->v1_1 = 0;
4162 ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4163 ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4164 ts->v2_1 = 0;
4165 ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
4166 ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4167 ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4168 ts->duration = td->duration;
4169 ts->modulate = 0;
4171 /* Let interrupts interrupt :) */
4172 ast_set_flag(chan, AST_FLAG_WRITE_INT);
4173 return ts;
4176 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
4178 struct tonepair_state *ts = data;
4179 int x;
4181 /* we need to prepare a frame with 16 * timelen samples as we're
4182 * generating SLIN audio
4184 len = samples * 2;
4186 if (len > sizeof(ts->data) / 2 - 1) {
4187 ast_log(LOG_WARNING, "Can't generate that much data!\n");
4188 return -1;
4190 memset(&ts->f, 0, sizeof(ts->f));
4191 for (x=0;x<len/2;x++) {
4192 ts->v1_1 = ts->v2_1;
4193 ts->v2_1 = ts->v3_1;
4194 ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;
4196 ts->v1_2 = ts->v2_2;
4197 ts->v2_2 = ts->v3_2;
4198 ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
4199 if (ts->modulate) {
4200 int p;
4201 p = ts->v3_2 - 32768;
4202 if (p < 0) p = -p;
4203 p = ((p * 9) / 10) + 1;
4204 ts->data[x] = (ts->v3_1 * p) >> 15;
4205 } else
4206 ts->data[x] = ts->v3_1 + ts->v3_2;
4208 ts->f.frametype = AST_FRAME_VOICE;
4209 ts->f.subclass = AST_FORMAT_SLINEAR;
4210 ts->f.datalen = len;
4211 ts->f.samples = samples;
4212 ts->f.offset = AST_FRIENDLY_OFFSET;
4213 ts->f.data = ts->data;
4214 ast_write(chan, &ts->f);
4215 ts->pos += x;
4216 if (ts->duration > 0) {
4217 if (ts->pos >= ts->duration * 8)
4218 return -1;
4220 return 0;
4223 static struct ast_generator tonepair = {
4224 alloc: tonepair_alloc,
4225 release: tonepair_release,
4226 generate: tonepair_generator,
4229 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4231 struct tonepair_def d = { 0, };
4233 d.freq1 = freq1;
4234 d.freq2 = freq2;
4235 d.duration = duration;
4236 d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
4237 if (ast_activate_generator(chan, &tonepair, &d))
4238 return -1;
4239 return 0;
4242 void ast_tonepair_stop(struct ast_channel *chan)
4244 ast_deactivate_generator(chan);
4247 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4249 int res;
4251 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
4252 return res;
4254 /* Give us some wiggle room */
4255 while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
4256 struct ast_frame *f = ast_read(chan);
4257 if (f)
4258 ast_frfree(f);
4259 else
4260 return -1;
4262 return 0;
4265 ast_group_t ast_get_group(const char *s)
4267 char *piece;
4268 char *c;
4269 int start=0, finish=0, x;
4270 ast_group_t group = 0;
4272 if (ast_strlen_zero(s))
4273 return 0;
4275 c = ast_strdupa(s);
4277 while ((piece = strsep(&c, ","))) {
4278 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
4279 /* Range */
4280 } else if (sscanf(piece, "%d", &start)) {
4281 /* Just one */
4282 finish = start;
4283 } else {
4284 ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
4285 continue;
4287 for (x = start; x <= finish; x++) {
4288 if ((x > 63) || (x < 0)) {
4289 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
4290 } else
4291 group |= ((ast_group_t) 1 << x);
4294 return group;
4297 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
4298 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
4299 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
4301 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
4302 void (*stop_ptr)(struct ast_channel *),
4303 void (*cleanup_ptr)(struct ast_channel *))
4305 ast_moh_start_ptr = start_ptr;
4306 ast_moh_stop_ptr = stop_ptr;
4307 ast_moh_cleanup_ptr = cleanup_ptr;
4310 void ast_uninstall_music_functions(void)
4312 ast_moh_start_ptr = NULL;
4313 ast_moh_stop_ptr = NULL;
4314 ast_moh_cleanup_ptr = NULL;
4317 /*! \brief Turn on music on hold on a given channel */
4318 int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
4320 if (ast_moh_start_ptr)
4321 return ast_moh_start_ptr(chan, mclass, interpclass);
4323 if (option_verbose > 2) {
4324 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n",
4325 mclass ? mclass : (interpclass ? interpclass : "default"));
4328 return 0;
4331 /*! \brief Turn off music on hold on a given channel */
4332 void ast_moh_stop(struct ast_channel *chan)
4334 if (ast_moh_stop_ptr)
4335 ast_moh_stop_ptr(chan);
4338 void ast_moh_cleanup(struct ast_channel *chan)
4340 if (ast_moh_cleanup_ptr)
4341 ast_moh_cleanup_ptr(chan);
4344 void ast_channels_init(void)
4346 ast_cli_register_multiple(cli_channel, sizeof(cli_channel) / sizeof(struct ast_cli_entry));
4349 /*! \brief Print call group and pickup group ---*/
4350 char *ast_print_group(char *buf, int buflen, ast_group_t group)
4352 unsigned int i;
4353 int first=1;
4354 char num[3];
4356 buf[0] = '\0';
4358 if (!group) /* Return empty string if no group */
4359 return buf;
4361 for (i = 0; i <= 63; i++) { /* Max group is 63 */
4362 if (group & ((ast_group_t) 1 << i)) {
4363 if (!first) {
4364 strncat(buf, ", ", buflen);
4365 } else {
4366 first=0;
4368 snprintf(num, sizeof(num), "%u", i);
4369 strncat(buf, num, buflen);
4372 return buf;
4375 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
4377 struct ast_variable *cur;
4379 for (cur = vars; cur; cur = cur->next)
4380 pbx_builtin_setvar_helper(chan, cur->name, cur->value);
4383 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
4385 /* just store the data pointer in the channel structure */
4386 return data;
4389 static void silence_generator_release(struct ast_channel *chan, void *data)
4391 /* nothing to do */
4394 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
4396 short buf[samples];
4397 struct ast_frame frame = {
4398 .frametype = AST_FRAME_VOICE,
4399 .subclass = AST_FORMAT_SLINEAR,
4400 .data = buf,
4401 .samples = samples,
4402 .datalen = sizeof(buf),
4404 memset(buf, 0, sizeof(buf));
4405 if (ast_write(chan, &frame))
4406 return -1;
4407 return 0;
4410 static struct ast_generator silence_generator = {
4411 .alloc = silence_generator_alloc,
4412 .release = silence_generator_release,
4413 .generate = silence_generator_generate,
4416 struct ast_silence_generator {
4417 int old_write_format;
4420 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
4422 struct ast_silence_generator *state;
4424 if (!(state = ast_calloc(1, sizeof(*state)))) {
4425 return NULL;
4428 state->old_write_format = chan->writeformat;
4430 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
4431 ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
4432 free(state);
4433 return NULL;
4436 ast_activate_generator(chan, &silence_generator, state);
4438 if (option_debug)
4439 ast_log(LOG_DEBUG, "Started silence generator on '%s'\n", chan->name);
4441 return state;
4444 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
4446 if (!state)
4447 return;
4449 ast_deactivate_generator(chan);
4451 if (option_debug)
4452 ast_log(LOG_DEBUG, "Stopped silence generator on '%s'\n", chan->name);
4454 if (ast_set_write_format(chan, state->old_write_format) < 0)
4455 ast_log(LOG_ERROR, "Could not return write format to its original state\n");
4457 free(state);
4461 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
4462 const char *channelreloadreason2txt(enum channelreloadreason reason)
4464 switch (reason) {
4465 case CHANNEL_MODULE_LOAD:
4466 return "LOAD (Channel module load)";
4468 case CHANNEL_MODULE_RELOAD:
4469 return "RELOAD (Channel module reload)";
4471 case CHANNEL_CLI_RELOAD:
4472 return "CLIRELOAD (Channel module reload by CLI command)";
4474 default:
4475 return "MANAGERRELOAD (Channel module reload by manager)";
4479 #ifdef DEBUG_CHANNEL_LOCKS
4481 /*! \brief Unlock AST channel (and print debugging output)
4482 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
4484 int ast_channel_unlock(struct ast_channel *chan)
4486 int res = 0;
4487 if (option_debug > 2)
4488 ast_log(LOG_DEBUG, "::::==== Unlocking AST channel %s\n", chan->name);
4490 if (!chan) {
4491 if (option_debug)
4492 ast_log(LOG_DEBUG, "::::==== Unlocking non-existing channel \n");
4493 return 0;
4496 res = ast_mutex_unlock(&chan->lock);
4498 if (option_debug > 2) {
4499 #ifdef DEBUG_THREADS
4500 int count = 0;
4501 if ((count = chan->lock.reentrancy))
4502 ast_log(LOG_DEBUG, ":::=== Still have %d locks (recursive)\n", count);
4503 #endif
4504 if (!res)
4505 if (option_debug)
4506 ast_log(LOG_DEBUG, "::::==== Channel %s was unlocked\n", chan->name);
4507 if (res == EINVAL) {
4508 if (option_debug)
4509 ast_log(LOG_DEBUG, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan->name);
4512 if (res == EPERM) {
4513 /* We had no lock, so okay any way*/
4514 if (option_debug > 3)
4515 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked at all \n", chan->name);
4516 res = 0;
4518 return res;
4521 /*! \brief Lock AST channel (and print debugging output)
4522 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4523 int ast_channel_lock(struct ast_channel *chan)
4525 int res;
4527 if (option_debug > 3)
4528 ast_log(LOG_DEBUG, "====:::: Locking AST channel %s\n", chan->name);
4530 res = ast_mutex_lock(&chan->lock);
4532 if (option_debug > 3) {
4533 #ifdef DEBUG_THREADS
4534 int count = 0;
4535 if ((count = chan->lock.reentrancy))
4536 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4537 #endif
4538 if (!res)
4539 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4540 if (res == EDEADLK) {
4541 /* We had no lock, so okey any way */
4542 if (option_debug > 3)
4543 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan->name);
4545 if (res == EINVAL) {
4546 if (option_debug > 3)
4547 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4550 return res;
4553 /*! \brief Lock AST channel (and print debugging output)
4554 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
4555 int ast_channel_trylock(struct ast_channel *chan)
4557 int res;
4559 if (option_debug > 2)
4560 ast_log(LOG_DEBUG, "====:::: Trying to lock AST channel %s\n", chan->name);
4562 res = ast_mutex_trylock(&chan->lock);
4564 if (option_debug > 2) {
4565 #ifdef DEBUG_THREADS
4566 int count = 0;
4567 if ((count = chan->lock.reentrancy))
4568 ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
4569 #endif
4570 if (!res)
4571 ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
4572 if (res == EBUSY) {
4573 /* We failed to lock */
4574 if (option_debug > 2)
4575 ast_log(LOG_DEBUG, "::::==== Channel %s failed to lock. Not waiting around...\n", chan->name);
4577 if (res == EDEADLK) {
4578 /* We had no lock, so okey any way*/
4579 if (option_debug > 2)
4580 ast_log(LOG_DEBUG, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan->name);
4582 if (res == EINVAL && option_debug > 2)
4583 ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
4585 return res;
4588 #endif
4591 * Wrappers for various ast_say_*() functions that call the full version
4592 * of the same functions.
4593 * The proper place would be say.c, but that file is optional and one
4594 * must be able to build asterisk even without it (using a loadable 'say'
4595 * implementation that only supplies the 'full' version of the functions.
4598 int ast_say_number(struct ast_channel *chan, int num,
4599 const char *ints, const char *language, const char *options)
4601 return ast_say_number_full(chan, num, ints, language, options, -1, -1);
4604 int ast_say_enumeration(struct ast_channel *chan, int num,
4605 const char *ints, const char *language, const char *options)
4607 return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
4610 int ast_say_digits(struct ast_channel *chan, int num,
4611 const char *ints, const char *lang)
4613 return ast_say_digits_full(chan, num, ints, lang, -1, -1);
4616 int ast_say_digit_str(struct ast_channel *chan, const char *str,
4617 const char *ints, const char *lang)
4619 return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
4622 int ast_say_character_str(struct ast_channel *chan, const char *str,
4623 const char *ints, const char *lang)
4625 return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
4628 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
4629 const char *ints, const char *lang)
4631 return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
4634 int ast_say_digits_full(struct ast_channel *chan, int num,
4635 const char *ints, const char *lang, int audiofd, int ctrlfd)
4637 char buf[256];
4639 snprintf(buf, sizeof(buf), "%d", num);
4640 return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);