Merged revisions 140053 via svnmerge from
[asterisk-bristuff.git] / main / channel.c
blob77a7908025cf0c52e9acfa6b17799f0fe5052954
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 "asterisk/_private.h"
32 #include <sys/time.h>
33 #include <signal.h>
34 #include <math.h>
36 #include "asterisk/paths.h" /* use ast_config_AST_SYSTEM_NAME */
38 #include "asterisk/pbx.h"
39 #include "asterisk/frame.h"
40 #include "asterisk/sched.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/musiconhold.h"
43 #include "asterisk/say.h"
44 #include "asterisk/file.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/translate.h"
47 #include "asterisk/manager.h"
48 #include "asterisk/chanvars.h"
49 #include "asterisk/linkedlists.h"
50 #include "asterisk/indications.h"
51 #include "asterisk/monitor.h"
52 #include "asterisk/causes.h"
53 #include "asterisk/callerid.h"
54 #include "asterisk/utils.h"
55 #include "asterisk/lock.h"
56 #include "asterisk/app.h"
57 #include "asterisk/transcap.h"
58 #include "asterisk/devicestate.h"
59 #include "asterisk/sha1.h"
60 #include "asterisk/threadstorage.h"
61 #include "asterisk/slinfactory.h"
62 #include "asterisk/audiohook.h"
63 #include "asterisk/timing.h"
65 #ifdef HAVE_EPOLL
66 #include <sys/epoll.h>
67 #endif
69 struct ast_epoll_data {
70 struct ast_channel *chan;
71 int which;
74 /* uncomment if you have problems with 'monitoring' synchronized files */
75 #if 0
76 #define MONITOR_CONSTANT_DELAY
77 #define MONITOR_DELAY 150 * 8 /*!< 150 ms of MONITORING DELAY */
78 #endif
80 /*! \brief Prevent new channel allocation if shutting down. */
81 static int shutting_down;
83 static int uniqueint;
85 unsigned long global_fin, global_fout;
87 AST_THREADSTORAGE(state2str_threadbuf);
88 #define STATE2STR_BUFSIZE 32
90 /*! Default amount of time to use when emulating a digit as a begin and end
91 * 100ms */
92 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
94 /*! Minimum allowed digit length - 80ms */
95 #define AST_MIN_DTMF_DURATION 80
97 /*! Minimum amount of time between the end of the last digit and the beginning
98 * of a new one - 45ms */
99 #define AST_MIN_DTMF_GAP 45
101 /*! \brief List of channel drivers */
102 struct chanlist {
103 const struct ast_channel_tech *tech;
104 AST_LIST_ENTRY(chanlist) list;
107 #ifdef CHANNEL_TRACE
108 /*! \brief Structure to hold channel context backtrace data */
109 struct ast_chan_trace_data {
110 int enabled;
111 AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
114 /*! \brief Structure to save contexts where an ast_chan has been into */
115 struct ast_chan_trace {
116 char context[AST_MAX_CONTEXT];
117 char exten[AST_MAX_EXTENSION];
118 int priority;
119 AST_LIST_ENTRY(ast_chan_trace) entry;
121 #endif
123 /*! \brief the list of registered channel types */
124 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
126 /*! \brief the list of channels we have. Note that the lock for this list is used for
127 both the channels list and the backends list. */
128 static AST_RWLIST_HEAD_STATIC(channels, ast_channel);
130 /*! \brief map AST_CAUSE's to readable string representations
132 * \ref causes.h
134 const struct ast_cause {
135 int cause;
136 const char *name;
137 const char *desc;
138 } causes[] = {
139 { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
140 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
141 { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
142 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
143 { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
144 { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
145 { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
146 { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
147 { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
148 { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
149 { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
150 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
151 { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
152 { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
153 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
154 { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
155 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
156 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
157 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
158 { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
159 { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
160 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
161 { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
162 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
163 { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
164 { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
165 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
166 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
167 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
168 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
169 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
170 { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
171 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
172 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
173 { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
174 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
175 { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
176 { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
177 { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
178 { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
179 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
180 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
181 { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
182 { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
185 struct ast_variable *ast_channeltype_list(void)
187 struct chanlist *cl;
188 struct ast_variable *var=NULL, *prev = NULL;
189 AST_LIST_TRAVERSE(&backends, cl, list) {
190 if (prev) {
191 if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
192 prev = prev->next;
193 } else {
194 var = ast_variable_new(cl->tech->type, cl->tech->description, "");
195 prev = var;
198 return var;
201 /*! \brief Show channel types - CLI command */
202 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
204 #define FORMAT "%-10.10s %-40.40s %-12.12s %-12.12s %-12.12s\n"
205 struct chanlist *cl;
206 int count_chan = 0;
208 switch (cmd) {
209 case CLI_INIT:
210 e->command = "core show channeltypes";
211 e->usage =
212 "Usage: core show channeltypes\n"
213 " Lists available channel types registered in your\n"
214 " Asterisk server.\n";
215 return NULL;
216 case CLI_GENERATE:
217 return NULL;
220 if (a->argc != 3)
221 return CLI_SHOWUSAGE;
223 ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
224 ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
226 AST_RWLIST_RDLOCK(&channels);
228 AST_LIST_TRAVERSE(&backends, cl, list) {
229 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
230 (cl->tech->devicestate) ? "yes" : "no",
231 (cl->tech->indicate) ? "yes" : "no",
232 (cl->tech->transfer) ? "yes" : "no");
233 count_chan++;
236 AST_RWLIST_UNLOCK(&channels);
238 ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
240 return CLI_SUCCESS;
242 #undef FORMAT
245 static char *complete_channeltypes(struct ast_cli_args *a)
247 struct chanlist *cl;
248 int which = 0;
249 int wordlen;
250 char *ret = NULL;
252 if (a->pos != 3)
253 return NULL;
255 wordlen = strlen(a->word);
257 AST_LIST_TRAVERSE(&backends, cl, list) {
258 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
259 ret = ast_strdup(cl->tech->type);
260 break;
264 return ret;
267 /*! \brief Show details about a channel driver - CLI command */
268 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
270 struct chanlist *cl = NULL;
272 switch (cmd) {
273 case CLI_INIT:
274 e->command = "core show channeltype";
275 e->usage =
276 "Usage: core show channeltype <name>\n"
277 " Show details about the specified channel type, <name>.\n";
278 return NULL;
279 case CLI_GENERATE:
280 return complete_channeltypes(a);
283 if (a->argc != 4)
284 return CLI_SHOWUSAGE;
286 AST_RWLIST_RDLOCK(&channels);
288 AST_LIST_TRAVERSE(&backends, cl, list) {
289 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
290 break;
294 if (!cl) {
295 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
296 AST_RWLIST_UNLOCK(&channels);
297 return CLI_FAILURE;
300 ast_cli(a->fd,
301 "-- Info about channel driver: %s --\n"
302 " Device State: %s\n"
303 " Indication: %s\n"
304 " Transfer : %s\n"
305 " Capabilities: %d\n"
306 " Digit Begin: %s\n"
307 " Digit End: %s\n"
308 " Send HTML : %s\n"
309 " Image Support: %s\n"
310 " Text Support: %s\n",
311 cl->tech->type,
312 (cl->tech->devicestate) ? "yes" : "no",
313 (cl->tech->indicate) ? "yes" : "no",
314 (cl->tech->transfer) ? "yes" : "no",
315 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
316 (cl->tech->send_digit_begin) ? "yes" : "no",
317 (cl->tech->send_digit_end) ? "yes" : "no",
318 (cl->tech->send_html) ? "yes" : "no",
319 (cl->tech->send_image) ? "yes" : "no",
320 (cl->tech->send_text) ? "yes" : "no"
324 AST_RWLIST_UNLOCK(&channels);
325 return CLI_SUCCESS;
328 static struct ast_cli_entry cli_channel[] = {
329 AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
330 AST_CLI_DEFINE(handle_cli_core_show_channeltype, "Give more details on that channel type")
333 #ifdef CHANNEL_TRACE
334 /*! \brief Destructor for the channel trace datastore */
335 static void ast_chan_trace_destroy_cb(void *data)
337 struct ast_chan_trace *trace;
338 struct ast_chan_trace_data *traced = data;
339 while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
340 ast_free(trace);
342 ast_free(traced);
345 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
346 const struct ast_datastore_info ast_chan_trace_datastore_info = {
347 .type = "ChanTrace",
348 .destroy = ast_chan_trace_destroy_cb
351 /*! \brief Put the channel backtrace in a string */
352 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
354 int total = 0;
355 struct ast_chan_trace *trace;
356 struct ast_chan_trace_data *traced;
357 struct ast_datastore *store;
359 ast_channel_lock(chan);
360 store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
361 if (!store) {
362 ast_channel_unlock(chan);
363 return total;
365 traced = store->data;
366 (*buf)->used = 0;
367 (*buf)->str[0] = '\0';
368 AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
369 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
370 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
371 total = -1;
372 break;
374 total++;
376 ast_channel_unlock(chan);
377 return total;
380 /* !\brief Whether or not context tracing is enabled */
381 int ast_channel_trace_is_enabled(struct ast_channel *chan)
383 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
384 if (!store)
385 return 0;
386 return ((struct ast_chan_trace_data *)store->data)->enabled;
389 /*! \brief Update the context backtrace data if tracing is enabled */
390 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
392 struct ast_chan_trace *trace;
393 if (!traced->enabled)
394 return 0;
395 /* If the last saved context does not match the current one
396 OR we have not saved any context so far, then save the current context */
397 if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) ||
398 (AST_LIST_EMPTY(&traced->trace))) {
399 /* Just do some debug logging */
400 if (AST_LIST_EMPTY(&traced->trace))
401 ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
402 else
403 ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
404 /* alloc or bail out */
405 trace = ast_malloc(sizeof(*trace));
406 if (!trace)
407 return -1;
408 /* save the current location and store it in the trace list */
409 ast_copy_string(trace->context, chan->context, sizeof(trace->context));
410 ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
411 trace->priority = chan->priority;
412 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
414 return 0;
417 /*! \brief Update the context backtrace if tracing is enabled */
418 int ast_channel_trace_update(struct ast_channel *chan)
420 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
421 if (!store)
422 return 0;
423 return ast_channel_trace_data_update(chan, store->data);
426 /*! \brief Enable context tracing in the channel */
427 int ast_channel_trace_enable(struct ast_channel *chan)
429 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
430 struct ast_chan_trace_data *traced;
431 if (!store) {
432 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
433 if (!store)
434 return -1;
435 traced = ast_calloc(1, sizeof(*traced));
436 if (!traced) {
437 ast_datastore_free(store);
438 return -1;
440 store->data = traced;
441 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
442 ast_channel_datastore_add(chan, store);
444 ((struct ast_chan_trace_data *)store->data)->enabled = 1;
445 ast_channel_trace_data_update(chan, store->data);
446 return 0;
449 /*! \brief Disable context tracing in the channel */
450 int ast_channel_trace_disable(struct ast_channel *chan)
452 struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
453 if (!store)
454 return 0;
455 ((struct ast_chan_trace_data *)store->data)->enabled = 0;
456 return 0;
458 #endif /* CHANNEL_TRACE */
460 /*! \brief Checks to see if a channel is needing hang up */
461 int ast_check_hangup(struct ast_channel *chan)
463 if (chan->_softhangup) /* yes if soft hangup flag set */
464 return 1;
465 if (!chan->tech_pvt) /* yes if no technology private data */
466 return 1;
467 if (ast_tvzero(chan->whentohangup)) /* no if no hangup scheduled */
468 return 0;
469 if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0) /* no if hangup time has not come yet. */
470 return 0;
471 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
472 return 1;
475 static int ast_check_hangup_locked(struct ast_channel *chan)
477 int res;
478 ast_channel_lock(chan);
479 res = ast_check_hangup(chan);
480 ast_channel_unlock(chan);
481 return res;
484 /*! \brief Initiate system shutdown */
485 void ast_begin_shutdown(int hangup)
487 struct ast_channel *c;
488 shutting_down = 1;
489 if (hangup) {
490 AST_RWLIST_RDLOCK(&channels);
491 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
492 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
494 AST_RWLIST_UNLOCK(&channels);
498 /*! \brief returns number of active/allocated channels */
499 int ast_active_channels(void)
501 struct ast_channel *c;
502 int cnt = 0;
503 AST_RWLIST_RDLOCK(&channels);
504 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
505 cnt++;
506 AST_RWLIST_UNLOCK(&channels);
507 return cnt;
510 /*! \brief Cancel a shutdown in progress */
511 void ast_cancel_shutdown(void)
513 shutting_down = 0;
516 /*! \brief Returns non-zero if Asterisk is being shut down */
517 int ast_shutting_down(void)
519 return shutting_down;
522 /*! \brief Set when to hangup channel */
523 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
525 chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
526 ast_queue_frame(chan, &ast_null_frame);
527 return;
530 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
532 struct timeval when = { offset, };
533 ast_channel_setwhentohangup_tv(chan, when);
536 /*! \brief Compare a offset with when to hangup channel */
537 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
539 struct timeval whentohangup;
541 if (ast_tvzero(chan->whentohangup))
542 return ast_tvzero(offset) ? 0 : -1;
544 if (ast_tvzero(offset))
545 return 1;
547 whentohangup = ast_tvadd(offset, ast_tvnow());
549 return ast_tvdiff_ms(whentohangup, chan->whentohangup);
552 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
554 struct timeval when = { offset, };
555 return ast_channel_cmpwhentohangup_tv(chan, when);
558 /*! \brief Register a new telephony channel in Asterisk */
559 int ast_channel_register(const struct ast_channel_tech *tech)
561 struct chanlist *chan;
563 AST_RWLIST_WRLOCK(&channels);
565 AST_LIST_TRAVERSE(&backends, chan, list) {
566 if (!strcasecmp(tech->type, chan->tech->type)) {
567 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
568 AST_RWLIST_UNLOCK(&channels);
569 return -1;
573 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
574 AST_RWLIST_UNLOCK(&channels);
575 return -1;
577 chan->tech = tech;
578 AST_LIST_INSERT_HEAD(&backends, chan, list);
580 ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
582 ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
584 AST_RWLIST_UNLOCK(&channels);
585 return 0;
588 /*! \brief Unregister channel driver */
589 void ast_channel_unregister(const struct ast_channel_tech *tech)
591 struct chanlist *chan;
593 ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
595 AST_RWLIST_WRLOCK(&channels);
597 AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
598 if (chan->tech == tech) {
599 AST_LIST_REMOVE_CURRENT(list);
600 ast_free(chan);
601 ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
602 break;
605 AST_LIST_TRAVERSE_SAFE_END;
607 AST_RWLIST_UNLOCK(&channels);
610 /*! \brief Get handle to channel driver based on name */
611 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
613 struct chanlist *chanls;
614 const struct ast_channel_tech *ret = NULL;
616 AST_RWLIST_RDLOCK(&channels);
618 AST_LIST_TRAVERSE(&backends, chanls, list) {
619 if (!strcasecmp(name, chanls->tech->type)) {
620 ret = chanls->tech;
621 break;
625 AST_RWLIST_UNLOCK(&channels);
627 return ret;
630 /*! \brief Gives the string form of a given hangup cause */
631 const char *ast_cause2str(int cause)
633 int x;
635 for (x = 0; x < ARRAY_LEN(causes); x++) {
636 if (causes[x].cause == cause)
637 return causes[x].desc;
640 return "Unknown";
643 /*! \brief Convert a symbolic hangup cause to number */
644 int ast_str2cause(const char *name)
646 int x;
648 for (x = 0; x < ARRAY_LEN(causes); x++)
649 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
650 return causes[x].cause;
652 return -1;
655 /*! \brief Gives the string form of a given channel state.
656 \note This function is not reentrant.
658 const char *ast_state2str(enum ast_channel_state state)
660 char *buf;
662 switch (state) {
663 case AST_STATE_DOWN:
664 return "Down";
665 case AST_STATE_RESERVED:
666 return "Rsrvd";
667 case AST_STATE_OFFHOOK:
668 return "OffHook";
669 case AST_STATE_DIALING:
670 return "Dialing";
671 case AST_STATE_RING:
672 return "Ring";
673 case AST_STATE_RINGING:
674 return "Ringing";
675 case AST_STATE_UP:
676 return "Up";
677 case AST_STATE_BUSY:
678 return "Busy";
679 case AST_STATE_DIALING_OFFHOOK:
680 return "Dialing Offhook";
681 case AST_STATE_PRERING:
682 return "Pre-ring";
683 default:
684 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
685 return "Unknown";
686 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
687 return buf;
691 /*! \brief Gives the string form of a given transfer capability */
692 char *ast_transfercapability2str(int transfercapability)
694 switch (transfercapability) {
695 case AST_TRANS_CAP_SPEECH:
696 return "SPEECH";
697 case AST_TRANS_CAP_DIGITAL:
698 return "DIGITAL";
699 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
700 return "RESTRICTED_DIGITAL";
701 case AST_TRANS_CAP_3_1K_AUDIO:
702 return "3K1AUDIO";
703 case AST_TRANS_CAP_DIGITAL_W_TONES:
704 return "DIGITAL_W_TONES";
705 case AST_TRANS_CAP_VIDEO:
706 return "VIDEO";
707 default:
708 return "UNKNOWN";
712 /*! \brief Pick the best audio codec */
713 int ast_best_codec(int fmts)
715 /* This just our opinion, expressed in code. We are asked to choose
716 the best codec to use, given no information */
717 int x;
718 static const int prefs[] =
720 /*! Okay, ulaw is used by all telephony equipment, so start with it */
721 AST_FORMAT_ULAW,
722 /*! Unless of course, you're a silly European, so then prefer ALAW */
723 AST_FORMAT_ALAW,
724 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
725 AST_FORMAT_G722,
726 /*! Okay, well, signed linear is easy to translate into other stuff */
727 AST_FORMAT_SLINEAR16,
728 AST_FORMAT_SLINEAR,
729 /*! G.726 is standard ADPCM, in RFC3551 packing order */
730 AST_FORMAT_G726,
731 /*! G.726 is standard ADPCM, in AAL2 packing order */
732 AST_FORMAT_G726_AAL2,
733 /*! ADPCM has great sound quality and is still pretty easy to translate */
734 AST_FORMAT_ADPCM,
735 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
736 translate and sounds pretty good */
737 AST_FORMAT_GSM,
738 /*! iLBC is not too bad */
739 AST_FORMAT_ILBC,
740 /*! Speex is free, but computationally more expensive than GSM */
741 AST_FORMAT_SPEEX,
742 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
743 to use it */
744 AST_FORMAT_LPC10,
745 /*! G.729a is faster than 723 and slightly less expensive */
746 AST_FORMAT_G729A,
747 /*! Down to G.723.1 which is proprietary but at least designed for voice */
748 AST_FORMAT_G723_1,
751 /* Strip out video */
752 fmts &= AST_FORMAT_AUDIO_MASK;
754 /* Find the first preferred codec in the format given */
755 for (x = 0; x < ARRAY_LEN(prefs); x++) {
756 if (fmts & prefs[x])
757 return prefs[x];
760 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
762 return 0;
765 static const struct ast_channel_tech null_tech = {
766 .type = "NULL",
767 .description = "Null channel (should not see this)",
770 /*! \brief Create a new channel structure */
771 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, ...)
773 struct ast_channel *tmp;
774 int x;
775 int flags;
776 struct varshead *headp;
777 va_list ap1, ap2;
779 /* If shutting down, don't allocate any new channels */
780 if (shutting_down) {
781 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
782 return NULL;
785 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
786 return NULL;
788 if (!(tmp->sched = sched_context_create())) {
789 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
790 ast_free(tmp);
791 return NULL;
794 if ((ast_string_field_init(tmp, 128))) {
795 sched_context_destroy(tmp->sched);
796 ast_free(tmp);
797 return NULL;
800 #ifdef HAVE_EPOLL
801 tmp->epfd = epoll_create(25);
802 #endif
804 for (x = 0; x < AST_MAX_FDS; x++) {
805 tmp->fds[x] = -1;
806 #ifdef HAVE_EPOLL
807 tmp->epfd_data[x] = NULL;
808 #endif
811 tmp->timingfd = ast_timer_open();
812 if (tmp->timingfd > -1) {
813 needqueue = 0;
816 if (needqueue) {
817 if (pipe(tmp->alertpipe)) {
818 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
819 alertpipe_failed:
820 if (tmp->timingfd > -1) {
821 ast_timer_close(tmp->timingfd);
824 sched_context_destroy(tmp->sched);
825 ast_string_field_free_memory(tmp);
826 ast_free(tmp);
827 return NULL;
828 } else {
829 flags = fcntl(tmp->alertpipe[0], F_GETFL);
830 if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
831 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
832 close(tmp->alertpipe[0]);
833 close(tmp->alertpipe[1]);
834 goto alertpipe_failed;
836 flags = fcntl(tmp->alertpipe[1], F_GETFL);
837 if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
838 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
839 close(tmp->alertpipe[0]);
840 close(tmp->alertpipe[1]);
841 goto alertpipe_failed;
844 } else /* Make sure we've got it done right if they don't */
845 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
847 /* Always watch the alertpipe */
848 ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
849 /* And timing pipe */
850 ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
851 ast_string_field_set(tmp, name, "**Unknown**");
853 /* Initial state */
854 tmp->_state = state;
856 tmp->streamid = -1;
858 tmp->fin = global_fin;
859 tmp->fout = global_fout;
861 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
862 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL),
863 ast_atomic_fetchadd_int(&uniqueint, 1));
864 } else {
865 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
866 (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
869 tmp->cid.cid_name = ast_strdup(cid_name);
870 tmp->cid.cid_num = ast_strdup(cid_num);
872 if (!ast_strlen_zero(name_fmt)) {
873 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
874 * And they all use slightly different formats for their name string.
875 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
876 * This means, that the stringfields must have a routine that takes the va_lists directly, and
877 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
878 * This new function was written so this can be accomplished.
880 va_start(ap1, name_fmt);
881 va_start(ap2, name_fmt);
882 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
883 va_end(ap1);
884 va_end(ap2);
887 /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
889 /* These 4 variables need to be set up for the cdr_init() to work right */
890 if (amaflag)
891 tmp->amaflags = amaflag;
892 else
893 tmp->amaflags = ast_default_amaflags;
895 if (!ast_strlen_zero(acctcode))
896 ast_string_field_set(tmp, accountcode, acctcode);
897 else
898 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
900 if (!ast_strlen_zero(context))
901 ast_copy_string(tmp->context, context, sizeof(tmp->context));
902 else
903 strcpy(tmp->context, "default");
905 if (!ast_strlen_zero(exten))
906 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
907 else
908 strcpy(tmp->exten, "s");
910 tmp->priority = 1;
912 tmp->cdr = ast_cdr_alloc();
913 ast_cdr_init(tmp->cdr, tmp);
914 ast_cdr_start(tmp->cdr);
916 headp = &tmp->varshead;
917 AST_LIST_HEAD_INIT_NOLOCK(headp);
919 ast_mutex_init(&tmp->lock_dont_use);
921 AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
923 ast_string_field_set(tmp, language, defaultlanguage);
925 tmp->tech = &null_tech;
927 AST_RWLIST_WRLOCK(&channels);
928 AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
929 AST_RWLIST_UNLOCK(&channels);
931 /*\!note
932 * and now, since the channel structure is built, and has its name, let's
933 * call the manager event generator with this Newchannel event. This is the
934 * proper and correct place to make this call, but you sure do have to pass
935 * a lot of data into this func to do it here!
937 if (!ast_strlen_zero(name_fmt)) {
938 manager_event(EVENT_FLAG_CALL, "Newchannel",
939 "Channel: %s\r\n"
940 "ChannelState: %d\r\n"
941 "ChannelStateDesc: %s\r\n"
942 "CallerIDNum: %s\r\n"
943 "CallerIDName: %s\r\n"
944 "AccountCode: %s\r\n"
945 "Uniqueid: %s\r\n",
946 tmp->name,
947 state,
948 ast_state2str(state),
949 S_OR(cid_num, ""),
950 S_OR(cid_name, ""),
951 tmp->accountcode,
952 tmp->uniqueid);
955 return tmp;
958 /*! \brief Queue an outgoing media frame */
959 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
961 struct ast_frame *f;
962 struct ast_frame *cur;
963 int blah = 1;
964 int qlen = 0;
966 /* Build us a copy and free the original one */
967 if (!(f = ast_frdup(fin))) {
968 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
969 return -1;
971 ast_channel_lock(chan);
973 /* See if the last frame on the queue is a hangup, if so don't queue anything */
974 if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
975 ast_frfree(f);
976 ast_channel_unlock(chan);
977 return 0;
980 /* Count how many frames exist on the queue */
981 AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
982 qlen++;
985 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
986 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
987 if (fin->frametype != AST_FRAME_VOICE) {
988 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
989 ast_assert(fin->frametype == AST_FRAME_VOICE);
990 } else {
991 ast_debug(1, "Dropping voice to exceptionally long queue on %s\n", chan->name);
992 ast_frfree(f);
993 ast_channel_unlock(chan);
994 return 0;
997 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
998 if (chan->alertpipe[1] > -1) {
999 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
1000 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
1001 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
1002 } else if (chan->timingfd > -1) {
1003 ast_timer_enable_continuous(chan->timingfd);
1004 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1005 pthread_kill(chan->blocker, SIGURG);
1007 ast_channel_unlock(chan);
1008 return 0;
1011 /*! \brief Queue a hangup frame for channel */
1012 int ast_queue_hangup(struct ast_channel *chan)
1014 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
1015 /* Yeah, let's not change a lock-critical value without locking */
1016 if (!ast_channel_trylock(chan)) {
1017 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1018 ast_channel_unlock(chan);
1020 return ast_queue_frame(chan, &f);
1023 /*! \brief Queue a hangup frame for channel */
1024 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1026 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
1028 if (cause >= 0)
1029 f.data.uint32 = cause;
1031 /* Yeah, let's not change a lock-critical value without locking */
1032 if (!ast_channel_trylock(chan)) {
1033 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1034 if (cause < 0)
1035 f.data.uint32 = chan->hangupcause;
1037 ast_channel_unlock(chan);
1040 return ast_queue_frame(chan, &f);
1043 /*! \brief Queue a control frame */
1044 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1046 struct ast_frame f = { AST_FRAME_CONTROL, };
1048 f.subclass = control;
1050 return ast_queue_frame(chan, &f);
1053 /*! \brief Queue a control frame with payload */
1054 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1055 const void *data, size_t datalen)
1057 struct ast_frame f = { AST_FRAME_CONTROL, };
1059 f.subclass = control;
1060 f.data.ptr = (void *) data;
1061 f.datalen = datalen;
1063 return ast_queue_frame(chan, &f);
1066 /*! \brief Set defer DTMF flag on channel */
1067 int ast_channel_defer_dtmf(struct ast_channel *chan)
1069 int pre = 0;
1071 if (chan) {
1072 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1073 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1075 return pre;
1078 /*! \brief Unset defer DTMF flag on channel */
1079 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1081 if (chan)
1082 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1086 * \brief Helper function to find channels.
1088 * It supports these modes:
1090 * prev != NULL : get channel next in list after prev
1091 * name != NULL : get channel with matching name
1092 * name != NULL && namelen != 0 : get channel whose name starts with prefix
1093 * exten != NULL : get channel whose exten or macroexten matches
1094 * context != NULL && exten != NULL : get channel whose context or macrocontext
1096 * It returns with the channel's lock held. If getting the individual lock fails,
1097 * unlock and retry quickly up to 10 times, then give up.
1099 * \note XXX Note that this code has cost O(N) because of the need to verify
1100 * that the object is still on the global list.
1102 * \note XXX also note that accessing fields (e.g. c->name in ast_log())
1103 * can only be done with the lock held or someone could delete the
1104 * object while we work on it. This causes some ugliness in the code.
1105 * Note that removing the first ast_log() may be harmful, as it would
1106 * shorten the retry period and possibly cause failures.
1107 * We should definitely go for a better scheme that is deadlock-free.
1109 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
1110 const char *name, const int namelen,
1111 const char *context, const char *exten)
1113 const char *msg = prev ? "deadlock" : "initial deadlock";
1114 int retries;
1115 struct ast_channel *c;
1116 const struct ast_channel *_prev = prev;
1118 for (retries = 0; retries < 200; retries++) {
1119 int done;
1120 /* Reset prev on each retry. See note below for the reason. */
1121 prev = _prev;
1122 AST_RWLIST_RDLOCK(&channels);
1123 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
1124 if (prev) { /* look for last item, first, before any evaluation */
1125 if (c != prev) /* not this one */
1126 continue;
1127 /* found, prepare to return c->next */
1128 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
1129 /*!\note
1130 * We're done searching through the list for the previous item.
1131 * Any item after this point, we want to evaluate for a match.
1132 * If we didn't set prev to NULL here, then we would only
1133 * return matches for the first matching item (since the above
1134 * "if (c != prev)" would not permit any other potential
1135 * matches to reach the additional matching logic, below).
1136 * Instead, it would just iterate until it once again found the
1137 * original match, then iterate down to the end of the list and
1138 * quit.
1140 prev = NULL;
1142 if (name) { /* want match by name */
1143 if ((!namelen && strcasecmp(c->name, name) && strcmp(c->uniqueid, name)) ||
1144 (namelen && strncasecmp(c->name, name, namelen)))
1145 continue; /* name match failed */
1146 } else if (exten) {
1147 if (context && strcasecmp(c->context, context) &&
1148 strcasecmp(c->macrocontext, context))
1149 continue; /* context match failed */
1150 if (strcasecmp(c->exten, exten) &&
1151 strcasecmp(c->macroexten, exten))
1152 continue; /* exten match failed */
1154 /* if we get here, c points to the desired record */
1155 break;
1157 /* exit if chan not found or mutex acquired successfully */
1158 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1159 done = c == NULL || ast_channel_trylock(c) == 0;
1160 if (!done) {
1161 ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
1162 if (retries == 199) {
1163 /* We are about to fail due to a deadlock, so report this
1164 * while we still have the list lock.
1166 ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
1167 /* As we have deadlocked, we will skip this channel and
1168 * see if there is another match.
1169 * NOTE: No point doing this for a full-name match,
1170 * as there can be no more matches.
1172 if (!(name && !namelen)) {
1173 prev = c;
1174 retries = -1;
1178 AST_RWLIST_UNLOCK(&channels);
1179 if (done)
1180 return c;
1181 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1182 * starting from the beginning of the list we can restore our saved pointer to the previous
1183 * channel and start from there.
1185 prev = _prev;
1186 usleep(1); /* give other threads a chance before retrying */
1189 return NULL;
1192 /*! \brief Browse channels in use */
1193 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1195 return channel_find_locked(prev, NULL, 0, NULL, NULL);
1198 /*! \brief Get channel by name and lock it */
1199 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1201 return channel_find_locked(NULL, name, 0, NULL, NULL);
1204 /*! \brief Get channel by name prefix and lock it */
1205 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1207 return channel_find_locked(NULL, name, namelen, NULL, NULL);
1210 /*! \brief Get next channel by name prefix and lock it */
1211 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1212 const int namelen)
1214 return channel_find_locked(chan, name, namelen, NULL, NULL);
1217 /*! \brief Get channel by exten (and optionally context) and lock it */
1218 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1220 return channel_find_locked(NULL, NULL, 0, context, exten);
1223 /*! \brief Get next channel by exten (and optionally context) and lock it */
1224 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1225 const char *context)
1227 return channel_find_locked(chan, NULL, 0, context, exten);
1230 /*! \brief Wait, look for hangups and condition arg */
1231 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1233 struct ast_frame *f;
1235 while (ms > 0) {
1236 if (cond && ((*cond)(data) == 0))
1237 return 0;
1238 ms = ast_waitfor(chan, ms);
1239 if (ms < 0)
1240 return -1;
1241 if (ms > 0) {
1242 f = ast_read(chan);
1243 if (!f)
1244 return -1;
1245 ast_frfree(f);
1248 return 0;
1251 /*! \brief Wait, look for hangups */
1252 int ast_safe_sleep(struct ast_channel *chan, int ms)
1254 return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1257 static void free_cid(struct ast_callerid *cid)
1259 if (cid->cid_dnid)
1260 ast_free(cid->cid_dnid);
1261 if (cid->cid_num)
1262 ast_free(cid->cid_num);
1263 if (cid->cid_name)
1264 ast_free(cid->cid_name);
1265 if (cid->cid_ani)
1266 ast_free(cid->cid_ani);
1267 if (cid->cid_rdnis)
1268 ast_free(cid->cid_rdnis);
1269 cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1272 /*! \brief Free a channel structure */
1273 void ast_channel_free(struct ast_channel *chan)
1275 int fd;
1276 #ifdef HAVE_EPOLL
1277 int i;
1278 #endif
1279 struct ast_var_t *vardata;
1280 struct ast_frame *f;
1281 struct varshead *headp;
1282 struct ast_datastore *datastore = NULL;
1283 char name[AST_CHANNEL_NAME], *dashptr;
1285 headp=&chan->varshead;
1287 AST_RWLIST_WRLOCK(&channels);
1288 if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1289 AST_RWLIST_UNLOCK(&channels);
1290 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1292 /* Lock and unlock the channel just to be sure nobody has it locked still
1293 due to a reference retrieved from the channel list. */
1294 ast_channel_lock(chan);
1295 ast_channel_unlock(chan);
1297 /* Get rid of each of the data stores on the channel */
1298 while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1299 /* Free the data store */
1300 ast_datastore_free(datastore);
1302 /* Lock and unlock the channel just to be sure nobody has it locked still
1303 due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1304 ast_channel_lock(chan);
1305 ast_channel_unlock(chan);
1307 if (chan->tech_pvt) {
1308 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1309 ast_free(chan->tech_pvt);
1312 if (chan->sched)
1313 sched_context_destroy(chan->sched);
1315 ast_copy_string(name, chan->name, sizeof(name));
1316 if ((dashptr = strrchr(name, '-'))) {
1317 *dashptr = '\0';
1320 /* Stop monitoring */
1321 if (chan->monitor)
1322 chan->monitor->stop( chan, 0 );
1324 /* If there is native format music-on-hold state, free it */
1325 if (chan->music_state)
1326 ast_moh_cleanup(chan);
1328 /* Free translators */
1329 if (chan->readtrans)
1330 ast_translator_free_path(chan->readtrans);
1331 if (chan->writetrans)
1332 ast_translator_free_path(chan->writetrans);
1333 if (chan->pbx)
1334 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1335 free_cid(&chan->cid);
1336 /* Close pipes if appropriate */
1337 if ((fd = chan->alertpipe[0]) > -1)
1338 close(fd);
1339 if ((fd = chan->alertpipe[1]) > -1)
1340 close(fd);
1341 if ((fd = chan->timingfd) > -1)
1342 ast_timer_close(fd);
1343 #ifdef HAVE_EPOLL
1344 for (i = 0; i < AST_MAX_FDS; i++) {
1345 if (chan->epfd_data[i])
1346 free(chan->epfd_data[i]);
1348 close(chan->epfd);
1349 #endif
1350 while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1351 ast_frfree(f);
1353 /* loop over the variables list, freeing all data and deleting list items */
1354 /* no need to lock the list, as the channel is already locked */
1356 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1357 ast_var_delete(vardata);
1359 ast_app_group_discard(chan);
1361 /* Destroy the jitterbuffer */
1362 ast_jb_destroy(chan);
1364 ast_mutex_destroy(&chan->lock_dont_use);
1366 ast_string_field_free_memory(chan);
1367 ast_free(chan);
1368 AST_RWLIST_UNLOCK(&channels);
1370 ast_devstate_changed_literal(AST_DEVICE_NOT_INUSE, name);
1373 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1375 return ast_datastore_alloc(info, uid);
1378 int ast_channel_datastore_free(struct ast_datastore *datastore)
1380 return ast_datastore_free(datastore);
1383 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1385 struct ast_datastore *datastore = NULL, *datastore2;
1387 AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1388 if (datastore->inheritance > 0) {
1389 datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
1390 if (datastore2) {
1391 datastore2->data = datastore->info->duplicate(datastore->data);
1392 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1393 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1397 return 0;
1400 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1402 int res = 0;
1404 AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1406 return res;
1409 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1411 return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1414 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1416 struct ast_datastore *datastore = NULL;
1418 if (info == NULL)
1419 return NULL;
1421 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1422 if (datastore->info != info) {
1423 continue;
1426 if (uid == NULL) {
1427 /* matched by type only */
1428 break;
1431 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
1432 /* Matched by type AND uid */
1433 break;
1436 AST_LIST_TRAVERSE_SAFE_END;
1438 return datastore;
1441 /*! Set the file descriptor on the channel */
1442 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
1444 #ifdef HAVE_EPOLL
1445 struct epoll_event ev;
1446 struct ast_epoll_data *aed = NULL;
1448 if (chan->fds[which] > -1) {
1449 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
1450 aed = chan->epfd_data[which];
1453 /* If this new fd is valid, add it to the epoll */
1454 if (fd > -1) {
1455 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
1456 return;
1458 chan->epfd_data[which] = aed;
1459 aed->chan = chan;
1460 aed->which = which;
1462 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1463 ev.data.ptr = aed;
1464 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
1465 } else if (aed) {
1466 /* We don't have to keep around this epoll data structure now */
1467 free(aed);
1468 chan->epfd_data[which] = NULL;
1470 #endif
1471 chan->fds[which] = fd;
1472 return;
1475 /*! Add a channel to an optimized waitfor */
1476 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
1478 #ifdef HAVE_EPOLL
1479 struct epoll_event ev;
1480 int i = 0;
1482 if (chan0->epfd == -1)
1483 return;
1485 /* Iterate through the file descriptors on chan1, adding them to chan0 */
1486 for (i = 0; i < AST_MAX_FDS; i++) {
1487 if (chan1->fds[i] == -1)
1488 continue;
1489 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1490 ev.data.ptr = chan1->epfd_data[i];
1491 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
1494 #endif
1495 return;
1498 /*! Delete a channel from an optimized waitfor */
1499 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
1501 #ifdef HAVE_EPOLL
1502 struct epoll_event ev;
1503 int i = 0;
1505 if (chan0->epfd == -1)
1506 return;
1508 for (i = 0; i < AST_MAX_FDS; i++) {
1509 if (chan1->fds[i] == -1)
1510 continue;
1511 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
1514 #endif
1515 return;
1518 /*! \brief Softly hangup a channel, don't lock */
1519 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1521 ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1522 /* Inform channel driver that we need to be hung up, if it cares */
1523 chan->_softhangup |= cause;
1524 ast_queue_frame(chan, &ast_null_frame);
1525 /* Interrupt any poll call or such */
1526 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1527 pthread_kill(chan->blocker, SIGURG);
1528 return 0;
1531 /*! \brief Softly hangup a channel, lock */
1532 int ast_softhangup(struct ast_channel *chan, int cause)
1534 int res;
1536 ast_channel_lock(chan);
1537 res = ast_softhangup_nolock(chan, cause);
1538 ast_channel_unlock(chan);
1540 return res;
1543 static void free_translation(struct ast_channel *clonechan)
1545 if (clonechan->writetrans)
1546 ast_translator_free_path(clonechan->writetrans);
1547 if (clonechan->readtrans)
1548 ast_translator_free_path(clonechan->readtrans);
1549 clonechan->writetrans = NULL;
1550 clonechan->readtrans = NULL;
1551 clonechan->rawwriteformat = clonechan->nativeformats;
1552 clonechan->rawreadformat = clonechan->nativeformats;
1555 /*! \brief Hangup a channel */
1556 int ast_hangup(struct ast_channel *chan)
1558 int res = 0;
1560 /* Don't actually hang up a channel that will masquerade as someone else, or
1561 if someone is going to masquerade as us */
1562 ast_channel_lock(chan);
1564 if (chan->audiohooks) {
1565 ast_audiohook_detach_list(chan->audiohooks);
1566 chan->audiohooks = NULL;
1569 ast_autoservice_stop(chan);
1571 if (chan->masq) {
1572 if (ast_do_masquerade(chan))
1573 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1576 if (chan->masq) {
1577 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1578 ast_channel_unlock(chan);
1579 return 0;
1581 /* If this channel is one which will be masqueraded into something,
1582 mark it as a zombie already, so we know to free it later */
1583 if (chan->masqr) {
1584 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1585 ast_channel_unlock(chan);
1586 return 0;
1588 free_translation(chan);
1589 /* Close audio stream */
1590 if (chan->stream) {
1591 ast_closestream(chan->stream);
1592 chan->stream = NULL;
1594 /* Close video stream */
1595 if (chan->vstream) {
1596 ast_closestream(chan->vstream);
1597 chan->vstream = NULL;
1599 if (chan->sched) {
1600 sched_context_destroy(chan->sched);
1601 chan->sched = NULL;
1604 if (chan->generatordata) /* Clear any tone stuff remaining */
1605 if (chan->generator && chan->generator->release)
1606 chan->generator->release(chan, chan->generatordata);
1607 chan->generatordata = NULL;
1608 chan->generator = NULL;
1609 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1610 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1611 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1612 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1613 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
1615 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1616 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1617 if (chan->tech->hangup)
1618 res = chan->tech->hangup(chan);
1619 } else {
1620 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1623 ast_channel_unlock(chan);
1624 manager_event(EVENT_FLAG_CALL, "Hangup",
1625 "Channel: %s\r\n"
1626 "Uniqueid: %s\r\n"
1627 "CallerIDNum: %s\r\n"
1628 "CallerIDName: %s\r\n"
1629 "Cause: %d\r\n"
1630 "Cause-txt: %s\r\n",
1631 chan->name,
1632 chan->uniqueid,
1633 S_OR(chan->cid.cid_num, "<unknown>"),
1634 S_OR(chan->cid.cid_name, "<unknown>"),
1635 chan->hangupcause,
1636 ast_cause2str(chan->hangupcause)
1639 if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
1640 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
1641 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
1643 ast_cdr_end(chan->cdr);
1644 ast_cdr_detach(chan->cdr);
1647 ast_channel_free(chan);
1649 return res;
1652 #define ANSWER_WAIT_MS 500
1653 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1655 int res = 0;
1657 ast_channel_lock(chan);
1659 /* You can't answer an outbound call */
1660 if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1661 ast_channel_unlock(chan);
1662 return 0;
1665 /* Stop if we're a zombie or need a soft hangup */
1666 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1667 ast_channel_unlock(chan);
1668 return -1;
1671 switch (chan->_state) {
1672 case AST_STATE_RINGING:
1673 case AST_STATE_RING:
1674 if (chan->tech->answer)
1675 res = chan->tech->answer(chan);
1676 ast_setstate(chan, AST_STATE_UP);
1677 ast_cdr_answer(chan->cdr);
1678 if (delay)
1679 ast_safe_sleep(chan, delay);
1680 else {
1681 struct ast_frame *f;
1682 int ms = ANSWER_WAIT_MS;
1683 while (1) {
1684 /* 500 ms was the original delay here, so now
1685 * we cap our waiting at 500 ms
1687 ms = ast_waitfor(chan, ms);
1688 if (ms < 0) {
1689 ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
1690 res = -1;
1691 break;
1693 if (ms == 0) {
1694 ast_debug(2, "Didn't receive a voice frame from %s within %d ms of answering. Continuing anyway\n", chan->name, ANSWER_WAIT_MS);
1695 res = 0;
1696 break;
1698 f = ast_read(chan);
1699 if (!f || (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)) {
1700 res = -1;
1701 ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
1702 break;
1704 if (f->frametype == AST_FRAME_VOICE) {
1705 res = 0;
1706 break;
1710 break;
1711 case AST_STATE_UP:
1712 break;
1713 default:
1714 break;
1716 chan->visible_indication = 0;
1717 ast_channel_unlock(chan);
1719 return res;
1722 int ast_answer(struct ast_channel *chan)
1724 return __ast_answer(chan, 0);
1727 void ast_deactivate_generator(struct ast_channel *chan)
1729 ast_channel_lock(chan);
1730 if (chan->generatordata) {
1731 if (chan->generator && chan->generator->release)
1732 chan->generator->release(chan, chan->generatordata);
1733 chan->generatordata = NULL;
1734 chan->generator = NULL;
1735 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
1736 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1737 ast_settimeout(chan, 0, NULL, NULL);
1739 ast_channel_unlock(chan);
1742 static int generator_force(const void *data)
1744 /* Called if generator doesn't have data */
1745 void *tmp;
1746 int res;
1747 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1748 struct ast_channel *chan = (struct ast_channel *)data;
1750 ast_channel_lock(chan);
1751 tmp = chan->generatordata;
1752 chan->generatordata = NULL;
1753 if (chan->generator)
1754 generate = chan->generator->generate;
1755 ast_channel_unlock(chan);
1757 if (!tmp || !generate)
1758 return 0;
1760 res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
1762 chan->generatordata = tmp;
1764 if (res) {
1765 ast_debug(1, "Auto-deactivating generator\n");
1766 ast_deactivate_generator(chan);
1769 return 0;
1772 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1774 int res = 0;
1776 ast_channel_lock(chan);
1778 if (chan->generatordata) {
1779 if (chan->generator && chan->generator->release)
1780 chan->generator->release(chan, chan->generatordata);
1781 chan->generatordata = NULL;
1784 ast_prod(chan);
1785 if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1786 res = -1;
1789 if (!res) {
1790 ast_settimeout(chan, 50, generator_force, chan);
1791 chan->generator = gen;
1794 ast_channel_unlock(chan);
1796 return res;
1799 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1800 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1802 int winner = -1;
1803 ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1804 return winner;
1807 /*! \brief Wait for x amount of time on a file descriptor to have input. */
1808 #ifdef HAVE_EPOLL
1809 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
1810 int *exception, int *outfd, int *ms)
1811 #else
1812 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1813 int *exception, int *outfd, int *ms)
1814 #endif
1816 struct timeval start = { 0 , 0 };
1817 struct pollfd *pfds = NULL;
1818 int res;
1819 long rms;
1820 int x, y, max;
1821 int sz;
1822 struct timeval now = { 0, 0 };
1823 struct timeval whentohangup = { 0, 0 }, diff;
1824 struct ast_channel *winner = NULL;
1825 struct fdmap {
1826 int chan;
1827 int fdno;
1828 } *fdmap = NULL;
1830 if ((sz = n * AST_MAX_FDS + nfds)) {
1831 pfds = alloca(sizeof(*pfds) * sz);
1832 fdmap = alloca(sizeof(*fdmap) * sz);
1835 if (outfd)
1836 *outfd = -99999;
1837 if (exception)
1838 *exception = 0;
1840 /* Perform any pending masquerades */
1841 for (x = 0; x < n; x++) {
1842 ast_channel_lock(c[x]);
1843 if (c[x]->masq && ast_do_masquerade(c[x])) {
1844 ast_log(LOG_WARNING, "Masquerade failed\n");
1845 *ms = -1;
1846 ast_channel_unlock(c[x]);
1847 return NULL;
1849 if (!ast_tvzero(c[x]->whentohangup)) {
1850 if (ast_tvzero(whentohangup))
1851 now = ast_tvnow();
1852 diff = ast_tvsub(c[x]->whentohangup, now);
1853 if (diff.tv_sec < 0 || ast_tvzero(diff)) {
1854 /* Should already be hungup */
1855 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1856 ast_channel_unlock(c[x]);
1857 return c[x];
1859 if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
1860 whentohangup = diff;
1862 ast_channel_unlock(c[x]);
1864 /* Wait full interval */
1865 rms = *ms;
1866 if (!ast_tvzero(whentohangup)) {
1867 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000; /* timeout in milliseconds */
1868 if (*ms >= 0 && *ms < rms) /* original *ms still smaller */
1869 rms = *ms;
1872 * Build the pollfd array, putting the channels' fds first,
1873 * followed by individual fds. Order is important because
1874 * individual fd's must have priority over channel fds.
1876 max = 0;
1877 for (x = 0; x < n; x++) {
1878 for (y = 0; y < AST_MAX_FDS; y++) {
1879 fdmap[max].fdno = y; /* fd y is linked to this pfds */
1880 fdmap[max].chan = x; /* channel x is linked to this pfds */
1881 max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1883 CHECK_BLOCKING(c[x]);
1885 /* Add the individual fds */
1886 for (x = 0; x < nfds; x++) {
1887 fdmap[max].chan = -1;
1888 max += ast_add_fd(&pfds[max], fds[x]);
1891 if (*ms > 0)
1892 start = ast_tvnow();
1894 if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1895 do {
1896 int kbrms = rms;
1897 if (kbrms > 600000)
1898 kbrms = 600000;
1899 res = poll(pfds, max, kbrms);
1900 if (!res)
1901 rms -= kbrms;
1902 } while (!res && (rms > 0));
1903 } else {
1904 res = poll(pfds, max, rms);
1906 for (x = 0; x < n; x++)
1907 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1908 if (res < 0) { /* Simulate a timeout if we were interrupted */
1909 if (errno != EINTR)
1910 *ms = -1;
1911 return NULL;
1913 if (!ast_tvzero(whentohangup)) { /* if we have a timeout, check who expired */
1914 now = ast_tvnow();
1915 for (x = 0; x < n; x++) {
1916 if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
1917 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1918 if (winner == NULL)
1919 winner = c[x];
1923 if (res == 0) { /* no fd ready, reset timeout and done */
1924 *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
1925 return winner;
1928 * Then check if any channel or fd has a pending event.
1929 * Remember to check channels first and fds last, as they
1930 * must have priority on setting 'winner'
1932 for (x = 0; x < max; x++) {
1933 res = pfds[x].revents;
1934 if (res == 0)
1935 continue;
1936 if (fdmap[x].chan >= 0) { /* this is a channel */
1937 winner = c[fdmap[x].chan]; /* override previous winners */
1938 if (res & POLLPRI)
1939 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1940 else
1941 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1942 winner->fdno = fdmap[x].fdno;
1943 } else { /* this is an fd */
1944 if (outfd)
1945 *outfd = pfds[x].fd;
1946 if (exception)
1947 *exception = (res & POLLPRI) ? -1 : 0;
1948 winner = NULL;
1951 if (*ms > 0) {
1952 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1953 if (*ms < 0)
1954 *ms = 0;
1956 return winner;
1959 #ifdef HAVE_EPOLL
1960 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
1962 struct timeval start = { 0 , 0 };
1963 int res = 0;
1964 struct epoll_event ev[1];
1965 long diff, rms = *ms;
1966 struct ast_channel *winner = NULL;
1967 struct ast_epoll_data *aed = NULL;
1969 ast_channel_lock(chan);
1971 /* See if this channel needs to be masqueraded */
1972 if (chan->masq && ast_do_masquerade(chan)) {
1973 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
1974 *ms = -1;
1975 ast_channel_unlock(chan);
1976 return NULL;
1979 /* Figure out their timeout */
1980 if (!ast_tvzero(chan->whentohangup)) {
1981 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
1982 /* They should already be hungup! */
1983 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1984 ast_channel_unlock(chan);
1985 return NULL;
1987 /* If this value is smaller then the current one... make it priority */
1988 if (rms > diff)
1989 rms = diff;
1992 ast_channel_unlock(chan);
1994 /* Time to make this channel block... */
1995 CHECK_BLOCKING(chan);
1997 if (*ms > 0)
1998 start = ast_tvnow();
2000 /* We don't have to add any file descriptors... they are already added, we just have to wait! */
2001 res = epoll_wait(chan->epfd, ev, 1, rms);
2003 /* Stop blocking */
2004 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2006 /* Simulate a timeout if we were interrupted */
2007 if (res < 0) {
2008 if (errno != EINTR)
2009 *ms = -1;
2010 return NULL;
2013 /* If this channel has a timeout see if it expired */
2014 if (!ast_tvzero(chan->whentohangup)) {
2015 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
2016 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2017 winner = chan;
2021 /* No fd ready, reset timeout and be done for now */
2022 if (!res) {
2023 *ms = 0;
2024 return winner;
2027 /* See what events are pending */
2028 aed = ev[0].data.ptr;
2029 chan->fdno = aed->which;
2030 if (ev[0].events & EPOLLPRI)
2031 ast_set_flag(chan, AST_FLAG_EXCEPTION);
2032 else
2033 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2035 if (*ms > 0) {
2036 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2037 if (*ms < 0)
2038 *ms = 0;
2041 return chan;
2044 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2046 struct timeval start = { 0 , 0 };
2047 int res = 0, i;
2048 struct epoll_event ev[25] = { { 0, } };
2049 struct timeval now = { 0, 0 };
2050 long whentohangup = 0, diff = 0, rms = *ms;
2051 struct ast_channel *winner = NULL;
2053 for (i = 0; i < n; i++) {
2054 ast_channel_lock(c[i]);
2055 if (c[i]->masq && ast_do_masquerade(c[i])) {
2056 ast_log(LOG_WARNING, "Masquerade failed\n");
2057 *ms = -1;
2058 ast_channel_unlock(c[i]);
2059 return NULL;
2061 if (!ast_tvzero(c[i]->whentohangup)) {
2062 if (whentohangup == 0)
2063 now = ast_tvnow();
2064 if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
2065 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2066 ast_channel_unlock(c[i]);
2067 return c[i];
2069 if (!whentohangup || whentohangup > diff)
2070 whentohangup = diff;
2072 ast_channel_unlock(c[i]);
2073 CHECK_BLOCKING(c[i]);
2076 rms = *ms;
2077 if (whentohangup) {
2078 rms = whentohangup;
2079 if (*ms >= 0 && *ms < rms)
2080 rms = *ms;
2083 if (*ms > 0)
2084 start = ast_tvnow();
2086 res = epoll_wait(c[0]->epfd, ev, 25, rms);
2088 for (i = 0; i < n; i++)
2089 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2091 if (res < 0) {
2092 if (errno != EINTR)
2093 *ms = -1;
2094 return NULL;
2097 if (whentohangup) {
2098 now = ast_tvnow();
2099 for (i = 0; i < n; i++) {
2100 if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
2101 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2102 if (!winner)
2103 winner = c[i];
2108 if (!res) {
2109 *ms = 0;
2110 return winner;
2113 for (i = 0; i < res; i++) {
2114 struct ast_epoll_data *aed = ev[i].data.ptr;
2116 if (!ev[i].events || !aed)
2117 continue;
2119 winner = aed->chan;
2120 if (ev[i].events & EPOLLPRI)
2121 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2122 else
2123 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2124 winner->fdno = aed->which;
2127 if (*ms > 0) {
2128 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2129 if (*ms < 0)
2130 *ms = 0;
2133 return winner;
2136 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2137 int *exception, int *outfd, int *ms)
2139 /* Clear all provided values in one place. */
2140 if (outfd)
2141 *outfd = -99999;
2142 if (exception)
2143 *exception = 0;
2145 /* If no epoll file descriptor is available resort to classic nandfds */
2146 if (!n || nfds || c[0]->epfd == -1)
2147 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2148 else if (!nfds && n == 1)
2149 return ast_waitfor_nandfds_simple(c[0], ms);
2150 else
2151 return ast_waitfor_nandfds_complex(c, n, ms);
2153 #endif
2155 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2157 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2160 int ast_waitfor(struct ast_channel *c, int ms)
2162 int oldms = ms; /* -1 if no timeout */
2164 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2165 if ((ms < 0) && (oldms < 0))
2166 ms = 0;
2167 return ms;
2170 /* XXX never to be called with ms = -1 */
2171 int ast_waitfordigit(struct ast_channel *c, int ms)
2173 return ast_waitfordigit_full(c, ms, -1, -1);
2176 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
2178 int res;
2179 unsigned int real_rate = rate, max_rate;
2181 if (c->timingfd == -1) {
2182 return -1;
2185 if (!func) {
2186 rate = 0;
2187 data = NULL;
2190 if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timingfd))) {
2191 real_rate = max_rate;
2194 ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
2196 res = ast_timer_set_rate(c->timingfd, real_rate);
2198 c->timingfunc = func;
2199 c->timingdata = data;
2201 return res;
2204 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2206 /* Stop if we're a zombie or need a soft hangup */
2207 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2208 return -1;
2210 /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2211 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2213 /* Wait for a digit, no more than ms milliseconds total. */
2215 while (ms) {
2216 struct ast_channel *rchan;
2217 int outfd=-1;
2219 errno = 0;
2220 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2222 if (!rchan && outfd < 0 && ms) {
2223 if (errno == 0 || errno == EINTR)
2224 continue;
2225 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2226 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2227 return -1;
2228 } else if (outfd > -1) {
2229 /* The FD we were watching has something waiting */
2230 ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2231 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2232 return 1;
2233 } else if (rchan) {
2234 int res;
2235 struct ast_frame *f = ast_read(c);
2236 if (!f)
2237 return -1;
2239 switch (f->frametype) {
2240 case AST_FRAME_DTMF_BEGIN:
2241 break;
2242 case AST_FRAME_DTMF_END:
2243 res = f->subclass;
2244 ast_frfree(f);
2245 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2246 return res;
2247 case AST_FRAME_CONTROL:
2248 switch (f->subclass) {
2249 case AST_CONTROL_HANGUP:
2250 ast_frfree(f);
2251 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2252 return -1;
2253 case AST_CONTROL_RINGING:
2254 case AST_CONTROL_ANSWER:
2255 case AST_CONTROL_SRCUPDATE:
2256 /* Unimportant */
2257 break;
2258 default:
2259 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2260 break;
2262 break;
2263 case AST_FRAME_VOICE:
2264 /* Write audio if appropriate */
2265 if (audiofd > -1)
2266 write(audiofd, f->data.ptr, f->datalen);
2267 default:
2268 /* Ignore */
2269 break;
2271 ast_frfree(f);
2275 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2277 return 0; /* Time is up */
2280 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2282 manager_event(EVENT_FLAG_DTMF,
2283 "DTMF",
2284 "Channel: %s\r\n"
2285 "Uniqueid: %s\r\n"
2286 "Digit: %c\r\n"
2287 "Direction: %s\r\n"
2288 "Begin: %s\r\n"
2289 "End: %s\r\n",
2290 chan->name, chan->uniqueid, digit, direction, begin, end);
2293 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2295 if (chan->generatordata && !ast_internal_timing_enabled(chan)) {
2296 void *tmp = chan->generatordata;
2297 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2298 int res;
2299 int samples;
2301 if (chan->timingfunc) {
2302 ast_debug(1, "Generator got voice, switching to phase locked mode\n");
2303 ast_settimeout(chan, 0, NULL, NULL);
2306 chan->generatordata = NULL; /* reset, to let writes go through */
2308 if (f->subclass != chan->writeformat) {
2309 float factor;
2310 factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass));
2311 samples = (int) ( ((float) f->samples) * factor );
2312 } else {
2313 samples = f->samples;
2316 if (chan->generator->generate) {
2317 generate = chan->generator->generate;
2319 /* This unlock is here based on two assumptions that hold true at this point in the
2320 * code. 1) this function is only called from within __ast_read() and 2) all generators
2321 * call ast_write() in their generate callback.
2323 * The reason this is added is so that when ast_write is called, the lock that occurs
2324 * there will not recursively lock the channel. Doing this will cause intended deadlock
2325 * avoidance not to work in deeper functions
2327 ast_channel_unlock(chan);
2328 res = generate(chan, tmp, f->datalen, samples);
2329 ast_channel_lock(chan);
2330 chan->generatordata = tmp;
2331 if (res) {
2332 ast_debug(1, "Auto-deactivating generator\n");
2333 ast_deactivate_generator(chan);
2336 } else if (f->frametype == AST_FRAME_CNG) {
2337 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2338 ast_debug(1, "Generator got CNG, switching to timed mode\n");
2339 ast_settimeout(chan, 50, generator_force, chan);
2344 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2346 struct ast_frame *f = NULL; /* the return value */
2347 int blah;
2348 int prestate;
2349 int count = 0, cause = 0;
2351 /* this function is very long so make sure there is only one return
2352 * point at the end (there are only two exceptions to this).
2354 while(ast_channel_trylock(chan)) {
2355 if(count++ > 10)
2356 /*cannot goto done since the channel is not locked*/
2357 return &ast_null_frame;
2358 usleep(1);
2361 if (chan->masq) {
2362 if (ast_do_masquerade(chan))
2363 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2364 else
2365 f = &ast_null_frame;
2366 goto done;
2369 /* Stop if we're a zombie or need a soft hangup */
2370 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2371 if (chan->generator)
2372 ast_deactivate_generator(chan);
2373 goto done;
2375 prestate = chan->_state;
2377 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) &&
2378 !ast_strlen_zero(chan->dtmfq) &&
2379 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2380 /* We have DTMF that has been deferred. Return it now */
2381 chan->dtmff.subclass = chan->dtmfq[0];
2382 /* Drop first digit from the buffer */
2383 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2384 f = &chan->dtmff;
2385 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2386 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2387 chan->dtmff.frametype = AST_FRAME_DTMF_END;
2388 } else {
2389 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);
2390 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2391 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2392 chan->emulate_dtmf_digit = f->subclass;
2393 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2395 chan->dtmf_tv = ast_tvnow();
2396 goto done;
2399 /* Read and ignore anything on the alertpipe, but read only
2400 one sizeof(blah) per frame that we send from it */
2401 if (chan->alertpipe[0] > -1) {
2402 int flags = fcntl(chan->alertpipe[0], F_GETFL);
2403 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
2404 * which immediately causes a deadlock scenario. Detect and prevent this. */
2405 if ((flags & O_NONBLOCK) == 0) {
2406 ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
2407 if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2408 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
2409 f = &ast_null_frame;
2410 goto done;
2413 read(chan->alertpipe[0], &blah, sizeof(blah));
2416 if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
2417 enum ast_timing_event res;
2419 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2421 res = ast_timer_get_event(chan->timingfd);
2423 switch (res) {
2424 case AST_TIMING_EVENT_EXPIRED:
2425 ast_timer_ack(chan->timingfd, 1);
2427 if (chan->timingfunc) {
2428 /* save a copy of func/data before unlocking the channel */
2429 int (*func)(const void *) = chan->timingfunc;
2430 void *data = chan->timingdata;
2431 ast_channel_unlock(chan);
2432 func(data);
2433 } else {
2434 ast_timer_set_rate(chan->timingfd, 0);
2435 ast_channel_unlock(chan);
2438 /* cannot 'goto done' because the channel is already unlocked */
2439 return &ast_null_frame;
2441 case AST_TIMING_EVENT_CONTINUOUS:
2442 if (AST_LIST_EMPTY(&chan->readq) ||
2443 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2444 ast_timer_disable_continuous(chan->timingfd);
2446 break;
2449 } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2450 /* if the AST_GENERATOR_FD is set, call the generator with args
2451 * set to -1 so it can do whatever it needs to.
2453 void *tmp = chan->generatordata;
2454 chan->generatordata = NULL; /* reset to let ast_write get through */
2455 chan->generator->generate(chan, tmp, -1, -1);
2456 chan->generatordata = tmp;
2457 f = &ast_null_frame;
2458 goto done;
2461 /* Check for pending read queue */
2462 if (!AST_LIST_EMPTY(&chan->readq)) {
2463 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2464 /* Interpret hangup and return NULL */
2465 /* XXX why not the same for frames from the channel ? */
2466 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2467 cause = f->data.uint32;
2468 ast_frfree(f);
2469 f = NULL;
2471 } else {
2472 chan->blocker = pthread_self();
2473 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2474 if (chan->tech->exception)
2475 f = chan->tech->exception(chan);
2476 else {
2477 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2478 f = &ast_null_frame;
2480 /* Clear the exception flag */
2481 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2482 } else if (chan->tech->read)
2483 f = chan->tech->read(chan);
2484 else
2485 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2488 if (f) {
2489 /* if the channel driver returned more than one frame, stuff the excess
2490 into the readq for the next ast_read call (note that we can safely assume
2491 that the readq is empty, because otherwise we would not have called into
2492 the channel driver and f would be only a single frame)
2494 if (AST_LIST_NEXT(f, frame_list)) {
2495 AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2496 AST_LIST_NEXT(f, frame_list) = NULL;
2499 switch (f->frametype) {
2500 case AST_FRAME_CONTROL:
2501 if (f->subclass == AST_CONTROL_ANSWER) {
2502 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2503 ast_debug(1, "Ignoring answer on an inbound call!\n");
2504 ast_frfree(f);
2505 f = &ast_null_frame;
2506 } else if (prestate == AST_STATE_UP) {
2507 ast_debug(1, "Dropping duplicate answer!\n");
2508 ast_frfree(f);
2509 f = &ast_null_frame;
2510 } else {
2511 /* Answer the CDR */
2512 ast_setstate(chan, AST_STATE_UP);
2513 /* removed a call to ast_cdr_answer(chan->cdr) from here. */
2516 break;
2517 case AST_FRAME_DTMF_END:
2518 send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2519 ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2520 /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2521 * However, only let emulation be forced if the other end cares about BEGIN frames */
2522 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2523 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2524 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2525 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2526 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2527 } else
2528 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2529 ast_frfree(f);
2530 f = &ast_null_frame;
2531 } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2532 if (!ast_tvzero(chan->dtmf_tv) &&
2533 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2534 /* If it hasn't been long enough, defer this digit */
2535 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2536 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2537 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2538 } else
2539 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2540 ast_frfree(f);
2541 f = &ast_null_frame;
2542 } else {
2543 /* There was no begin, turn this into a begin and send the end later */
2544 f->frametype = AST_FRAME_DTMF_BEGIN;
2545 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2546 chan->emulate_dtmf_digit = f->subclass;
2547 chan->dtmf_tv = ast_tvnow();
2548 if (f->len) {
2549 if (f->len > AST_MIN_DTMF_DURATION)
2550 chan->emulate_dtmf_duration = f->len;
2551 else
2552 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2553 } else
2554 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2555 ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2557 if (chan->audiohooks) {
2558 struct ast_frame *old_frame = f;
2560 * \todo XXX It is possible to write a digit to the audiohook twice
2561 * if the digit was originally read while the channel was in autoservice. */
2562 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2563 if (old_frame != f)
2564 ast_frfree(old_frame);
2566 } else {
2567 struct timeval now = ast_tvnow();
2568 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2569 ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2570 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2571 if (!f->len)
2572 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2573 } else if (!f->len) {
2574 ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2575 f->len = AST_MIN_DTMF_DURATION;
2577 if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2578 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);
2579 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2580 chan->emulate_dtmf_digit = f->subclass;
2581 chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2582 ast_frfree(f);
2583 f = &ast_null_frame;
2584 } else {
2585 ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2586 if (f->len < AST_MIN_DTMF_DURATION) {
2587 f->len = AST_MIN_DTMF_DURATION;
2589 chan->dtmf_tv = now;
2591 if (chan->audiohooks) {
2592 struct ast_frame *old_frame = f;
2593 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2594 if (old_frame != f)
2595 ast_frfree(old_frame);
2598 break;
2599 case AST_FRAME_DTMF_BEGIN:
2600 send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2601 ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2602 if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
2603 (!ast_tvzero(chan->dtmf_tv) &&
2604 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2605 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2606 ast_frfree(f);
2607 f = &ast_null_frame;
2608 } else {
2609 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2610 chan->dtmf_tv = ast_tvnow();
2611 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2613 break;
2614 case AST_FRAME_NULL:
2615 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2616 * is reached , because we want to make sure we pass at least one
2617 * voice frame through before starting the next digit, to ensure a gap
2618 * between DTMF digits. */
2619 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2620 struct timeval now = ast_tvnow();
2621 if (!chan->emulate_dtmf_duration) {
2622 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2623 chan->emulate_dtmf_digit = 0;
2624 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2625 chan->emulate_dtmf_duration = 0;
2626 ast_frfree(f);
2627 f = &chan->dtmff;
2628 f->frametype = AST_FRAME_DTMF_END;
2629 f->subclass = chan->emulate_dtmf_digit;
2630 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2631 chan->dtmf_tv = now;
2632 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2633 chan->emulate_dtmf_digit = 0;
2634 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2637 break;
2638 case AST_FRAME_VOICE:
2639 /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2640 * is reached , because we want to make sure we pass at least one
2641 * voice frame through before starting the next digit, to ensure a gap
2642 * between DTMF digits. */
2643 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2644 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2645 chan->emulate_dtmf_digit = 0;
2648 if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2649 if (dropaudio)
2650 ast_read_generator_actions(chan, f);
2651 ast_frfree(f);
2652 f = &ast_null_frame;
2655 if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2656 struct timeval now = ast_tvnow();
2657 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2658 chan->emulate_dtmf_duration = 0;
2659 ast_frfree(f);
2660 f = &chan->dtmff;
2661 f->frametype = AST_FRAME_DTMF_END;
2662 f->subclass = chan->emulate_dtmf_digit;
2663 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2664 chan->dtmf_tv = now;
2665 if (chan->audiohooks) {
2666 struct ast_frame *old_frame = f;
2667 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2668 if (old_frame != f)
2669 ast_frfree(old_frame);
2671 ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2672 } else {
2673 /* Drop voice frames while we're still in the middle of the digit */
2674 ast_frfree(f);
2675 f = &ast_null_frame;
2677 } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2678 /* This frame is not one of the current native formats -- drop it on the floor */
2679 char to[200];
2680 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2681 chan->name, ast_getformatname(f->subclass), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
2682 ast_frfree(f);
2683 f = &ast_null_frame;
2684 } else if ((f->frametype == AST_FRAME_VOICE)) {
2685 /* Send frame to audiohooks if present */
2686 if (chan->audiohooks) {
2687 struct ast_frame *old_frame = f;
2688 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2689 if (old_frame != f)
2690 ast_frfree(old_frame);
2692 if (chan->monitor && chan->monitor->read_stream ) {
2693 /* XXX what does this do ? */
2694 #ifndef MONITOR_CONSTANT_DELAY
2695 int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2696 if (jump >= 0) {
2697 jump = chan->outsmpl - chan->insmpl;
2698 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2699 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2700 chan->insmpl += jump + f->samples;
2701 } else
2702 chan->insmpl+= f->samples;
2703 #else
2704 int jump = chan->outsmpl - chan->insmpl;
2705 if (jump - MONITOR_DELAY >= 0) {
2706 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2707 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2708 chan->insmpl += jump;
2709 } else
2710 chan->insmpl += f->samples;
2711 #endif
2712 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2713 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2714 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2718 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2719 f = &ast_null_frame;
2720 else
2721 /* Run generator sitting on the line if timing device not available
2722 * and synchronous generation of outgoing frames is necessary */
2723 ast_read_generator_actions(chan, f);
2725 default:
2726 /* Just pass it on! */
2727 break;
2729 } else {
2730 /* Make sure we always return NULL in the future */
2731 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2732 if (cause)
2733 chan->hangupcause = cause;
2734 if (chan->generator)
2735 ast_deactivate_generator(chan);
2736 /* We no longer End the CDR here */
2739 /* High bit prints debugging */
2740 if (chan->fin & DEBUGCHAN_FLAG)
2741 ast_frame_dump(chan->name, f, "<<");
2742 chan->fin = FRAMECOUNT_INC(chan->fin);
2744 done:
2745 if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2746 chan->generator->digit(chan, f->subclass);
2748 ast_channel_unlock(chan);
2749 return f;
2752 int ast_internal_timing_enabled(struct ast_channel *chan)
2754 int ret = ast_opt_internal_timing && chan->timingfd > -1;
2755 ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2756 return ret;
2759 struct ast_frame *ast_read(struct ast_channel *chan)
2761 return __ast_read(chan, 0);
2764 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2766 return __ast_read(chan, 1);
2769 int ast_indicate(struct ast_channel *chan, int condition)
2771 return ast_indicate_data(chan, condition, NULL, 0);
2774 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2776 int res = -1;
2778 ast_channel_lock(chan);
2779 /* Stop if we're a zombie or need a soft hangup */
2780 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2781 ast_channel_unlock(chan);
2782 return -1;
2784 if (chan->tech->indicate)
2785 res = chan->tech->indicate(chan, condition, data, datalen);
2786 ast_channel_unlock(chan);
2787 if (!chan->tech->indicate || res) {
2789 * Device does not support (that) indication, lets fake
2790 * it by doing our own tone generation. (PM2002)
2792 if (condition < 0)
2793 ast_playtones_stop(chan);
2794 else {
2795 const struct ind_tone_zone_sound *ts = NULL;
2796 switch (condition) {
2797 case AST_CONTROL_RINGING:
2798 ts = ast_get_indication_tone(chan->zone, "ring");
2799 break;
2800 case AST_CONTROL_BUSY:
2801 ts = ast_get_indication_tone(chan->zone, "busy");
2802 break;
2803 case AST_CONTROL_CONGESTION:
2804 ts = ast_get_indication_tone(chan->zone, "congestion");
2805 break;
2807 if (ts && ts->data[0]) {
2808 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2809 ast_playtones_start(chan,0,ts->data, 1);
2810 res = 0;
2811 chan->visible_indication = condition;
2812 } else if (condition == AST_CONTROL_PROGRESS) {
2813 /* ast_playtones_stop(chan); */
2814 } else if (condition == AST_CONTROL_PROCEEDING) {
2815 /* Do nothing, really */
2816 } else if (condition == AST_CONTROL_HOLD) {
2817 /* Do nothing.... */
2818 } else if (condition == AST_CONTROL_UNHOLD) {
2819 /* Do nothing.... */
2820 } else if (condition == AST_CONTROL_VIDUPDATE) {
2821 /* Do nothing.... */
2822 } else if (condition == AST_CONTROL_SRCUPDATE) {
2823 /* Do nothing... */
2824 } else {
2825 /* not handled */
2826 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2827 res = -1;
2830 } else
2831 chan->visible_indication = condition;
2833 return res;
2836 int ast_recvchar(struct ast_channel *chan, int timeout)
2838 int c;
2839 char *buf = ast_recvtext(chan, timeout);
2840 if (buf == NULL)
2841 return -1; /* error or timeout */
2842 c = *(unsigned char *)buf;
2843 ast_free(buf);
2844 return c;
2847 char *ast_recvtext(struct ast_channel *chan, int timeout)
2849 int res, done = 0;
2850 char *buf = NULL;
2852 while (!done) {
2853 struct ast_frame *f;
2854 if (ast_check_hangup(chan))
2855 break;
2856 res = ast_waitfor(chan, timeout);
2857 if (res <= 0) /* timeout or error */
2858 break;
2859 timeout = res; /* update timeout */
2860 f = ast_read(chan);
2861 if (f == NULL)
2862 break; /* no frame */
2863 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2864 done = 1; /* force a break */
2865 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
2866 buf = ast_strndup((char *) f->data.ptr, f->datalen); /* dup and break */
2867 done = 1;
2869 ast_frfree(f);
2871 return buf;
2874 int ast_sendtext(struct ast_channel *chan, const char *text)
2876 int res = 0;
2877 /* Stop if we're a zombie or need a soft hangup */
2878 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2879 return -1;
2880 CHECK_BLOCKING(chan);
2881 if (chan->tech->send_text)
2882 res = chan->tech->send_text(chan, text);
2883 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2884 return res;
2887 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2889 /* Device does not support DTMF tones, lets fake
2890 * it by doing our own generation. */
2891 static const char* dtmf_tones[] = {
2892 "941+1336", /* 0 */
2893 "697+1209", /* 1 */
2894 "697+1336", /* 2 */
2895 "697+1477", /* 3 */
2896 "770+1209", /* 4 */
2897 "770+1336", /* 5 */
2898 "770+1477", /* 6 */
2899 "852+1209", /* 7 */
2900 "852+1336", /* 8 */
2901 "852+1477", /* 9 */
2902 "697+1633", /* A */
2903 "770+1633", /* B */
2904 "852+1633", /* C */
2905 "941+1633", /* D */
2906 "941+1209", /* * */
2907 "941+1477" /* # */
2910 if (!chan->tech->send_digit_begin)
2911 return 0;
2913 if (!chan->tech->send_digit_begin(chan, digit))
2914 return 0;
2916 if (digit >= '0' && digit <='9')
2917 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2918 else if (digit >= 'A' && digit <= 'D')
2919 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2920 else if (digit == '*')
2921 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2922 else if (digit == '#')
2923 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2924 else {
2925 /* not handled */
2926 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2929 return 0;
2932 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2934 int res = -1;
2936 if (chan->tech->send_digit_end)
2937 res = chan->tech->send_digit_end(chan, digit, duration);
2939 if (res && chan->generator)
2940 ast_playtones_stop(chan);
2942 return 0;
2945 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
2947 if (chan->tech->send_digit_begin) {
2948 ast_senddigit_begin(chan, digit);
2949 ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2952 return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2955 int ast_prod(struct ast_channel *chan)
2957 struct ast_frame a = { AST_FRAME_VOICE };
2958 char nothing[128];
2960 /* Send an empty audio frame to get things moving */
2961 if (chan->_state != AST_STATE_UP) {
2962 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2963 a.subclass = chan->rawwriteformat;
2964 a.data.ptr = nothing + AST_FRIENDLY_OFFSET;
2965 a.src = "ast_prod";
2966 if (ast_write(chan, &a))
2967 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2969 return 0;
2972 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2974 int res;
2975 if (!chan->tech->write_video)
2976 return 0;
2977 res = ast_write(chan, fr);
2978 if (!res)
2979 res = 1;
2980 return res;
2983 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2985 int res = -1;
2986 struct ast_frame *f = NULL, *f2 = NULL;
2987 int count = 0;
2989 /*Deadlock avoidance*/
2990 while(ast_channel_trylock(chan)) {
2991 /*cannot goto done since the channel is not locked*/
2992 if(count++ > 10) {
2993 ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
2994 return 0;
2996 usleep(1);
2998 /* Stop if we're a zombie or need a soft hangup */
2999 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
3000 goto done;
3002 /* Handle any pending masquerades */
3003 if (chan->masq && ast_do_masquerade(chan)) {
3004 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
3005 goto done;
3007 if (chan->masqr) {
3008 res = 0; /* XXX explain, why 0 ? */
3009 goto done;
3011 if (chan->generatordata) {
3012 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
3013 ast_deactivate_generator(chan);
3014 else {
3015 if (fr->frametype == AST_FRAME_DTMF_END) {
3016 /* There is a generator running while we're in the middle of a digit.
3017 * It's probably inband DTMF, so go ahead and pass it so it can
3018 * stop the generator */
3019 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3020 ast_channel_unlock(chan);
3021 res = ast_senddigit_end(chan, fr->subclass, fr->len);
3022 ast_channel_lock(chan);
3023 CHECK_BLOCKING(chan);
3024 } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
3025 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
3026 res = (chan->tech->indicate == NULL) ? 0 :
3027 chan->tech->indicate(chan, fr->subclass, fr->data.ptr, fr->datalen);
3029 res = 0; /* XXX explain, why 0 ? */
3030 goto done;
3033 /* High bit prints debugging */
3034 if (chan->fout & DEBUGCHAN_FLAG)
3035 ast_frame_dump(chan->name, fr, ">>");
3036 CHECK_BLOCKING(chan);
3037 switch (fr->frametype) {
3038 case AST_FRAME_CONTROL:
3039 res = (chan->tech->indicate == NULL) ? 0 :
3040 chan->tech->indicate(chan, fr->subclass, fr->data.ptr, fr->datalen);
3041 break;
3042 case AST_FRAME_DTMF_BEGIN:
3043 if (chan->audiohooks) {
3044 struct ast_frame *old_frame = fr;
3045 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3046 if (old_frame != fr)
3047 f = fr;
3049 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
3050 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3051 ast_channel_unlock(chan);
3052 res = ast_senddigit_begin(chan, fr->subclass);
3053 ast_channel_lock(chan);
3054 CHECK_BLOCKING(chan);
3055 break;
3056 case AST_FRAME_DTMF_END:
3057 if (chan->audiohooks) {
3058 struct ast_frame *old_frame = fr;
3059 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3060 if (old_frame != fr)
3061 f = fr;
3063 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
3064 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3065 ast_channel_unlock(chan);
3066 res = ast_senddigit_end(chan, fr->subclass, fr->len);
3067 ast_channel_lock(chan);
3068 CHECK_BLOCKING(chan);
3069 break;
3070 case AST_FRAME_TEXT:
3071 if (fr->subclass == AST_FORMAT_T140) {
3072 res = (chan->tech->write_text == NULL) ? 0 :
3073 chan->tech->write_text(chan, fr);
3074 } else {
3075 res = (chan->tech->send_text == NULL) ? 0 :
3076 chan->tech->send_text(chan, (char *) fr->data.ptr);
3078 break;
3079 case AST_FRAME_HTML:
3080 res = (chan->tech->send_html == NULL) ? 0 :
3081 chan->tech->send_html(chan, fr->subclass, (char *) fr->data.ptr, fr->datalen);
3082 break;
3083 case AST_FRAME_VIDEO:
3084 /* XXX Handle translation of video codecs one day XXX */
3085 res = (chan->tech->write_video == NULL) ? 0 :
3086 chan->tech->write_video(chan, fr);
3087 break;
3088 case AST_FRAME_MODEM:
3089 res = (chan->tech->write == NULL) ? 0 :
3090 chan->tech->write(chan, fr);
3091 break;
3092 case AST_FRAME_VOICE:
3093 if (chan->tech->write == NULL)
3094 break; /*! \todo XXX should return 0 maybe ? */
3096 /* If audiohooks are present, write the frame out */
3097 if (chan->audiohooks) {
3098 struct ast_frame *old_frame = fr;
3099 fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3100 if (old_frame != fr)
3101 f2 = fr;
3104 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
3105 if (fr->subclass == chan->rawwriteformat)
3106 f = fr;
3107 else
3108 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
3110 if (!f) {
3111 res = 0;
3112 break;
3115 /* If Monitor is running on this channel, then we have to write frames out there too */
3116 if (chan->monitor && chan->monitor->write_stream) {
3117 /* XXX must explain this code */
3118 #ifndef MONITOR_CONSTANT_DELAY
3119 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
3120 if (jump >= 0) {
3121 jump = chan->insmpl - chan->outsmpl;
3122 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
3123 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3124 chan->outsmpl += jump + f->samples;
3125 } else
3126 chan->outsmpl += f->samples;
3127 #else
3128 int jump = chan->insmpl - chan->outsmpl;
3129 if (jump - MONITOR_DELAY >= 0) {
3130 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
3131 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3132 chan->outsmpl += jump;
3133 } else
3134 chan->outsmpl += f->samples;
3135 #endif
3136 if (chan->monitor->state == AST_MONITOR_RUNNING) {
3137 if (ast_writestream(chan->monitor->write_stream, f) < 0)
3138 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
3142 if (f)
3143 res = chan->tech->write(chan,f);
3144 else
3145 res = 0;
3146 break;
3147 case AST_FRAME_NULL:
3148 case AST_FRAME_IAX:
3149 /* Ignore these */
3150 res = 0;
3151 break;
3152 default:
3153 /* At this point, fr is the incoming frame and f is NULL. Channels do
3154 * not expect to get NULL as a frame pointer and will segfault. Hence,
3155 * we output the original frame passed in. */
3156 res = chan->tech->write(chan, fr);
3157 break;
3160 if (f && f != fr)
3161 ast_frfree(f);
3162 if (f2)
3163 ast_frfree(f2);
3164 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3165 /* Consider a write failure to force a soft hangup */
3166 if (res < 0)
3167 chan->_softhangup |= AST_SOFTHANGUP_DEV;
3168 else {
3169 chan->fout = FRAMECOUNT_INC(chan->fout);
3171 done:
3172 ast_channel_unlock(chan);
3173 return res;
3176 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
3177 struct ast_trans_pvt **trans, const int direction)
3179 int native;
3180 int res;
3181 char from[200], to[200];
3183 /* Make sure we only consider audio */
3184 fmt &= AST_FORMAT_AUDIO_MASK;
3186 native = chan->nativeformats;
3188 if (!fmt || !native) /* No audio requested */
3189 return 0; /* Let's try a call without any sounds (video, text) */
3191 /* Find a translation path from the native format to one of the desired formats */
3192 if (!direction)
3193 /* reading */
3194 res = ast_translator_best_choice(&fmt, &native);
3195 else
3196 /* writing */
3197 res = ast_translator_best_choice(&native, &fmt);
3199 if (res < 0) {
3200 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
3201 ast_getformatname_multiple(from, sizeof(from), native),
3202 ast_getformatname_multiple(to, sizeof(to), fmt));
3203 return -1;
3206 /* Now we have a good choice for both. */
3207 ast_channel_lock(chan);
3209 if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
3210 /* the channel is already in these formats, so nothing to do */
3211 ast_channel_unlock(chan);
3212 return 0;
3215 *rawformat = native;
3216 /* User perspective is fmt */
3217 *format = fmt;
3218 /* Free any read translation we have right now */
3219 if (*trans)
3220 ast_translator_free_path(*trans);
3221 /* Build a translation path from the raw format to the desired format */
3222 if (!direction)
3223 /* reading */
3224 *trans = ast_translator_build_path(*format, *rawformat);
3225 else
3226 /* writing */
3227 *trans = ast_translator_build_path(*rawformat, *format);
3228 ast_channel_unlock(chan);
3229 ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
3230 direction ? "write" : "read", ast_getformatname(fmt));
3231 return 0;
3234 int ast_set_read_format(struct ast_channel *chan, int fmt)
3236 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
3237 &chan->readtrans, 0);
3240 int ast_set_write_format(struct ast_channel *chan, int fmt)
3242 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
3243 &chan->writetrans, 1);
3246 const char *ast_channel_reason2str(int reason)
3248 switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
3250 case 0:
3251 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
3252 case AST_CONTROL_HANGUP:
3253 return "Hangup";
3254 case AST_CONTROL_RING:
3255 return "Local Ring";
3256 case AST_CONTROL_RINGING:
3257 return "Remote end Ringing";
3258 case AST_CONTROL_ANSWER:
3259 return "Remote end has Answered";
3260 case AST_CONTROL_BUSY:
3261 return "Remote end is Busy";
3262 case AST_CONTROL_CONGESTION:
3263 return "Congestion (circuits busy)";
3264 default:
3265 return "Unknown Reason!!";
3269 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)
3271 int dummy_outstate;
3272 int cause = 0;
3273 struct ast_channel *chan;
3274 int res = 0;
3275 int last_subclass = 0;
3277 if (outstate)
3278 *outstate = 0;
3279 else
3280 outstate = &dummy_outstate; /* make outstate always a valid pointer */
3282 chan = ast_request(type, format, data, &cause);
3283 if (!chan) {
3284 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
3285 /* compute error and return */
3286 if (cause == AST_CAUSE_BUSY)
3287 *outstate = AST_CONTROL_BUSY;
3288 else if (cause == AST_CAUSE_CONGESTION)
3289 *outstate = AST_CONTROL_CONGESTION;
3290 return NULL;
3293 if (oh) {
3294 if (oh->vars)
3295 ast_set_variables(chan, oh->vars);
3296 /* XXX why is this necessary, for the parent_channel perhaps ? */
3297 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
3298 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
3299 if (oh->parent_channel) {
3300 ast_channel_inherit_variables(oh->parent_channel, chan);
3301 ast_channel_datastore_inherit(oh->parent_channel, chan);
3303 if (oh->account)
3304 ast_cdr_setaccount(chan, oh->account);
3306 ast_set_callerid(chan, cid_num, cid_name, cid_num);
3308 if (ast_call(chan, data, 0)) { /* ast_call failed... */
3309 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
3310 } else {
3311 res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
3312 while (timeout && chan->_state != AST_STATE_UP) {
3313 struct ast_frame *f;
3314 res = ast_waitfor(chan, timeout);
3315 if (res <= 0) /* error, timeout, or done */
3316 break;
3317 if (timeout > -1)
3318 timeout = res;
3319 f = ast_read(chan);
3320 if (!f) {
3321 *outstate = AST_CONTROL_HANGUP;
3322 res = 0;
3323 break;
3325 if (f->frametype == AST_FRAME_CONTROL) {
3326 switch (f->subclass) {
3327 case AST_CONTROL_RINGING: /* record but keep going */
3328 *outstate = f->subclass;
3329 break;
3331 case AST_CONTROL_BUSY:
3332 case AST_CONTROL_CONGESTION:
3333 case AST_CONTROL_ANSWER:
3334 *outstate = f->subclass;
3335 timeout = 0; /* trick to force exit from the while() */
3336 break;
3338 /* Ignore these */
3339 case AST_CONTROL_PROGRESS:
3340 case AST_CONTROL_PROCEEDING:
3341 case AST_CONTROL_HOLD:
3342 case AST_CONTROL_UNHOLD:
3343 case AST_CONTROL_VIDUPDATE:
3344 case AST_CONTROL_SRCUPDATE:
3345 case -1: /* Ignore -- just stopping indications */
3346 break;
3348 default:
3349 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
3351 last_subclass = f->subclass;
3353 ast_frfree(f);
3357 /* Final fixups */
3358 if (oh) {
3359 if (!ast_strlen_zero(oh->context))
3360 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
3361 if (!ast_strlen_zero(oh->exten))
3362 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
3363 if (oh->priority)
3364 chan->priority = oh->priority;
3366 if (chan->_state == AST_STATE_UP)
3367 *outstate = AST_CONTROL_ANSWER;
3369 if (res <= 0) {
3370 if ( AST_CONTROL_RINGING == last_subclass )
3371 chan->hangupcause = AST_CAUSE_NO_ANSWER;
3372 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
3373 ast_cdr_init(chan->cdr, chan);
3374 if (chan->cdr) {
3375 char tmp[256];
3376 snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
3377 ast_cdr_setapp(chan->cdr,"Dial",tmp);
3378 ast_cdr_update(chan);
3379 ast_cdr_start(chan->cdr);
3380 ast_cdr_end(chan->cdr);
3381 /* If the cause wasn't handled properly */
3382 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
3383 ast_cdr_failed(chan->cdr);
3385 ast_hangup(chan);
3386 chan = NULL;
3388 return chan;
3391 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
3393 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
3396 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
3398 struct chanlist *chan;
3399 struct ast_channel *c;
3400 int capabilities;
3401 int fmt;
3402 int res;
3403 int foo;
3404 int videoformat = format & AST_FORMAT_VIDEO_MASK;
3405 int textformat = format & AST_FORMAT_TEXT_MASK;
3407 if (!cause)
3408 cause = &foo;
3409 *cause = AST_CAUSE_NOTDEFINED;
3411 if (AST_RWLIST_RDLOCK(&channels)) {
3412 ast_log(LOG_WARNING, "Unable to lock channel list\n");
3413 return NULL;
3416 AST_LIST_TRAVERSE(&backends, chan, list) {
3417 if (strcasecmp(type, chan->tech->type))
3418 continue;
3420 capabilities = chan->tech->capabilities;
3421 fmt = format & AST_FORMAT_AUDIO_MASK;
3422 if (fmt) {
3423 /* We have audio - is it possible to connect the various calls to each other?
3424 (Avoid this check for calls without audio, like text+video calls)
3426 res = ast_translator_best_choice(&fmt, &capabilities);
3427 if (res < 0) {
3428 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native 0x%x) to 0x%x\n", type, chan->tech->capabilities, format);
3429 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3430 AST_RWLIST_UNLOCK(&channels);
3431 return NULL;
3434 AST_RWLIST_UNLOCK(&channels);
3435 if (!chan->tech->requester)
3436 return NULL;
3438 if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, data, cause)))
3439 return NULL;
3441 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3442 return c;
3445 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
3446 *cause = AST_CAUSE_NOSUCHDRIVER;
3447 AST_RWLIST_UNLOCK(&channels);
3449 return NULL;
3452 int ast_call(struct ast_channel *chan, char *addr, int timeout)
3454 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3455 If the remote end does not answer within the timeout, then do NOT hang up, but
3456 return anyway. */
3457 int res = -1;
3458 /* Stop if we're a zombie or need a soft hangup */
3459 ast_channel_lock(chan);
3460 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3461 if (chan->cdr)
3462 ast_set_flag(chan->cdr, AST_CDR_FLAG_DIALED);
3463 if (chan->tech->call)
3464 res = chan->tech->call(chan, addr, timeout);
3465 ast_set_flag(chan, AST_FLAG_OUTGOING);
3467 ast_channel_unlock(chan);
3468 return res;
3472 \brief Transfer a call to dest, if the channel supports transfer
3474 Called by:
3475 \arg app_transfer
3476 \arg the manager interface
3478 int ast_transfer(struct ast_channel *chan, char *dest)
3480 int res = -1;
3482 /* Stop if we're a zombie or need a soft hangup */
3483 ast_channel_lock(chan);
3484 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3485 if (chan->tech->transfer) {
3486 res = chan->tech->transfer(chan, dest);
3487 if (!res)
3488 res = 1;
3489 } else
3490 res = 0;
3492 ast_channel_unlock(chan);
3493 return res;
3496 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3498 return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3501 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3503 int pos = 0; /* index in the buffer where we accumulate digits */
3504 int to = ftimeout;
3506 /* Stop if we're a zombie or need a soft hangup */
3507 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3508 return -1;
3509 if (!len)
3510 return -1;
3511 for (;;) {
3512 int d;
3513 if (c->stream) {
3514 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3515 ast_stopstream(c);
3516 usleep(1000);
3517 if (!d)
3518 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3519 } else {
3520 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3522 if (d < 0)
3523 return -1;
3524 if (d == 0) {
3525 s[pos]='\0';
3526 return 1;
3528 if (d == 1) {
3529 s[pos]='\0';
3530 return 2;
3532 if (!strchr(enders, d))
3533 s[pos++] = d;
3534 if (strchr(enders, d) || (pos >= len)) {
3535 s[pos]='\0';
3536 return 0;
3538 to = timeout;
3540 /* Never reached */
3541 return 0;
3544 int ast_channel_supports_html(struct ast_channel *chan)
3546 return (chan->tech->send_html) ? 1 : 0;
3549 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3551 if (chan->tech->send_html)
3552 return chan->tech->send_html(chan, subclass, data, datalen);
3553 return -1;
3556 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3558 return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3561 /*! \brief Set up translation from one channel to another */
3562 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
3564 int src;
3565 int dst;
3567 if (from->readformat == to->writeformat && from->writeformat == to->readformat) {
3568 /* Already compatible! Moving on ... */
3569 return 0;
3572 /* Set up translation from the 'from' channel to the 'to' channel */
3573 src = from->nativeformats;
3574 dst = to->nativeformats;
3576 /* If there's no audio in this call, don't bother with trying to find a translation path */
3577 if ((src & AST_FORMAT_AUDIO_MASK) == 0 || (dst & AST_FORMAT_AUDIO_MASK) == 0)
3578 return 0;
3580 if (ast_translator_best_choice(&dst, &src) < 0) {
3581 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", from->name, src, to->name, dst);
3582 return -1;
3585 /* if the best path is not 'pass through', then
3586 transcoding is needed; if desired, force transcode path
3587 to use SLINEAR between channels, but only if there is
3588 no direct conversion available */
3589 if ((src != dst) && ast_opt_transcode_via_slin &&
3590 (ast_translate_path_steps(dst, src) != 1))
3591 dst = AST_FORMAT_SLINEAR;
3592 if (ast_set_read_format(from, dst) < 0) {
3593 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", from->name, dst);
3594 return -1;
3596 if (ast_set_write_format(to, dst) < 0) {
3597 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", to->name, dst);
3598 return -1;
3600 return 0;
3603 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3605 /* Some callers do not check return code, and we must try to set all call legs correctly */
3606 int rc = 0;
3608 /* Set up translation from the chan to the peer */
3609 rc = ast_channel_make_compatible_helper(chan, peer);
3611 if (rc < 0)
3612 return rc;
3614 /* Set up translation from the peer to the chan */
3615 rc = ast_channel_make_compatible_helper(peer, chan);
3617 return rc;
3620 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clonechan)
3622 int res = -1;
3623 struct ast_channel *final_orig, *final_clone, *base;
3625 retrymasq:
3626 final_orig = original;
3627 final_clone = clonechan;
3629 ast_channel_lock(original);
3630 while (ast_channel_trylock(clonechan)) {
3631 ast_channel_unlock(original);
3632 usleep(1);
3633 ast_channel_lock(original);
3636 /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3637 and if so, we don't really want to masquerade it, but its proxy */
3638 if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
3639 final_orig = original->_bridge;
3641 if (clonechan->_bridge && (clonechan->_bridge != ast_bridged_channel(clonechan)) && (clonechan->_bridge->_bridge != clonechan))
3642 final_clone = clonechan->_bridge;
3644 if (final_clone->tech->get_base_channel && (base = final_clone->tech->get_base_channel(final_clone))) {
3645 final_clone = base;
3648 if ((final_orig != original) || (final_clone != clonechan)) {
3649 /* Lots and lots of deadlock avoidance. The main one we're competing with
3650 * is ast_write(), which locks channels recursively, when working with a
3651 * proxy channel. */
3652 if (ast_channel_trylock(final_orig)) {
3653 ast_channel_unlock(clonechan);
3654 ast_channel_unlock(original);
3655 goto retrymasq;
3657 if (ast_channel_trylock(final_clone)) {
3658 ast_channel_unlock(final_orig);
3659 ast_channel_unlock(clonechan);
3660 ast_channel_unlock(original);
3661 goto retrymasq;
3663 ast_channel_unlock(clonechan);
3664 ast_channel_unlock(original);
3665 original = final_orig;
3666 clonechan = final_clone;
3669 if (original == clonechan) {
3670 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3671 ast_channel_unlock(clonechan);
3672 ast_channel_unlock(original);
3673 return -1;
3676 ast_debug(1, "Planning to masquerade channel %s into the structure of %s\n",
3677 clonechan->name, original->name);
3678 if (original->masq) {
3679 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3680 original->masq->name, original->name);
3681 } else if (clonechan->masqr) {
3682 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3683 clonechan->name, clonechan->masqr->name);
3684 } else {
3685 original->masq = clonechan;
3686 clonechan->masqr = original;
3687 ast_queue_frame(original, &ast_null_frame);
3688 ast_queue_frame(clonechan, &ast_null_frame);
3689 ast_debug(1, "Done planning to masquerade channel %s into the structure of %s\n", clonechan->name, original->name);
3690 res = 0;
3693 ast_channel_unlock(clonechan);
3694 ast_channel_unlock(original);
3696 return res;
3699 void ast_change_name(struct ast_channel *chan, char *newname)
3701 manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3702 ast_string_field_set(chan, name, newname);
3705 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3707 struct ast_var_t *current, *newvar;
3708 const char *varname;
3710 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3711 int vartype = 0;
3713 varname = ast_var_full_name(current);
3714 if (!varname)
3715 continue;
3717 if (varname[0] == '_') {
3718 vartype = 1;
3719 if (varname[1] == '_')
3720 vartype = 2;
3723 switch (vartype) {
3724 case 1:
3725 newvar = ast_var_assign(&varname[1], ast_var_value(current));
3726 if (newvar) {
3727 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3728 ast_debug(1, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3730 break;
3731 case 2:
3732 newvar = ast_var_assign(varname, ast_var_value(current));
3733 if (newvar) {
3734 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3735 ast_debug(1, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3737 break;
3738 default:
3739 ast_debug(1, "Not copying variable %s.\n", ast_var_name(current));
3740 break;
3746 \brief Clone channel variables from 'clone' channel into 'original' channel
3748 All variables except those related to app_groupcount are cloned.
3749 Variables are actually _removed_ from 'clone' channel, presumably
3750 because it will subsequently be destroyed.
3752 \note Assumes locks will be in place on both channels when called.
3754 static void clone_variables(struct ast_channel *original, struct ast_channel *clonechan)
3756 struct ast_var_t *current, *newvar;
3757 /* Append variables from clone channel into original channel */
3758 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
3759 if (AST_LIST_FIRST(&clonechan->varshead))
3760 AST_LIST_APPEND_LIST(&original->varshead, &clonechan->varshead, entries);
3762 /* then, dup the varshead list into the clone */
3764 AST_LIST_TRAVERSE(&original->varshead, current, entries) {
3765 newvar = ast_var_assign(current->name, current->value);
3766 if (newvar)
3767 AST_LIST_INSERT_TAIL(&clonechan->varshead, newvar, entries);
3772 \brief Masquerade a channel
3774 \note Assumes channel will be locked when called
3776 int ast_do_masquerade(struct ast_channel *original)
3778 int x,i;
3779 int res=0;
3780 int origstate;
3781 struct ast_frame *current;
3782 const struct ast_channel_tech *t;
3783 void *t_pvt;
3784 struct ast_callerid tmpcid;
3785 struct ast_channel *clonechan = original->masq;
3786 struct ast_cdr *cdr;
3787 int rformat = original->readformat;
3788 int wformat = original->writeformat;
3789 char newn[AST_CHANNEL_NAME];
3790 char orig[AST_CHANNEL_NAME];
3791 char masqn[AST_CHANNEL_NAME];
3792 char zombn[AST_CHANNEL_NAME];
3794 ast_debug(4, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3795 clonechan->name, clonechan->_state, original->name, original->_state);
3797 manager_event(EVENT_FLAG_CALL, "Masquerade", "Clone: %s\r\nCloneState: %s\r\nOriginal: %s\r\nOriginalState: %s\r\n",
3798 clonechan->name, ast_state2str(clonechan->_state), original->name, ast_state2str(original->_state));
3800 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
3801 the clone channel into the original channel. Start by killing off the original
3802 channel's backend. I'm not sure we're going to keep this function, because
3803 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3805 /* We need the clone's lock, too */
3806 ast_channel_lock(clonechan);
3808 ast_debug(2, "Got clone lock for masquerade on '%s' at %p\n", clonechan->name, &clonechan->lock_dont_use);
3810 /* Having remembered the original read/write formats, we turn off any translation on either
3811 one */
3812 free_translation(clonechan);
3813 free_translation(original);
3816 /* Unlink the masquerade */
3817 original->masq = NULL;
3818 clonechan->masqr = NULL;
3820 /* Save the original name */
3821 ast_copy_string(orig, original->name, sizeof(orig));
3822 /* Save the new name */
3823 ast_copy_string(newn, clonechan->name, sizeof(newn));
3824 /* Create the masq name */
3825 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3827 /* Copy the name from the clone channel */
3828 ast_string_field_set(original, name, newn);
3830 /* Mangle the name of the clone channel */
3831 ast_string_field_set(clonechan, name, masqn);
3833 /* Notify any managers of the change, first the masq then the other */
3834 manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clonechan->uniqueid);
3835 manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3837 /* Swap the technologies */
3838 t = original->tech;
3839 original->tech = clonechan->tech;
3840 clonechan->tech = t;
3842 /* Swap the cdrs */
3843 cdr = original->cdr;
3844 original->cdr = clonechan->cdr;
3845 clonechan->cdr = cdr;
3847 t_pvt = original->tech_pvt;
3848 original->tech_pvt = clonechan->tech_pvt;
3849 clonechan->tech_pvt = t_pvt;
3851 /* Swap the alertpipes */
3852 for (i = 0; i < 2; i++) {
3853 x = original->alertpipe[i];
3854 original->alertpipe[i] = clonechan->alertpipe[i];
3855 clonechan->alertpipe[i] = x;
3859 * Swap the readq's. The end result should be this:
3861 * 1) All frames should be on the new (original) channel.
3862 * 2) Any frames that were already on the new channel before this
3863 * masquerade need to be at the end of the readq, after all of the
3864 * frames on the old (clone) channel.
3865 * 3) The alertpipe needs to get poked for every frame that was already
3866 * on the new channel, since we are now using the alert pipe from the
3867 * old (clone) channel.
3870 AST_LIST_HEAD_NOLOCK(, ast_frame) tmp_readq;
3871 AST_LIST_HEAD_SET_NOLOCK(&tmp_readq, NULL);
3873 AST_LIST_APPEND_LIST(&tmp_readq, &original->readq, frame_list);
3874 AST_LIST_APPEND_LIST(&original->readq, &clonechan->readq, frame_list);
3876 while ((current = AST_LIST_REMOVE_HEAD(&tmp_readq, frame_list))) {
3877 AST_LIST_INSERT_TAIL(&original->readq, current, frame_list);
3878 if (original->alertpipe[1] > -1) {
3879 int poke = 0;
3880 write(original->alertpipe[1], &poke, sizeof(poke));
3885 /* Swap the raw formats */
3886 x = original->rawreadformat;
3887 original->rawreadformat = clonechan->rawreadformat;
3888 clonechan->rawreadformat = x;
3889 x = original->rawwriteformat;
3890 original->rawwriteformat = clonechan->rawwriteformat;
3891 clonechan->rawwriteformat = x;
3893 clonechan->_softhangup = AST_SOFTHANGUP_DEV;
3895 /* And of course, so does our current state. Note we need not
3896 call ast_setstate since the event manager doesn't really consider
3897 these separate. We do this early so that the clone has the proper
3898 state of the original channel. */
3899 origstate = original->_state;
3900 original->_state = clonechan->_state;
3901 clonechan->_state = origstate;
3903 if (clonechan->tech->fixup){
3904 res = clonechan->tech->fixup(original, clonechan);
3905 if (res)
3906 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clonechan->name);
3909 /* Start by disconnecting the original's physical side */
3910 if (clonechan->tech->hangup)
3911 res = clonechan->tech->hangup(clonechan);
3912 if (res) {
3913 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
3914 ast_channel_unlock(clonechan);
3915 return -1;
3918 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3919 /* Mangle the name of the clone channel */
3920 ast_string_field_set(clonechan, name, zombn);
3921 manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clonechan->uniqueid);
3923 /* Update the type. */
3924 t_pvt = original->monitor;
3925 original->monitor = clonechan->monitor;
3926 clonechan->monitor = t_pvt;
3928 /* Keep the same language. */
3929 ast_string_field_set(original, language, clonechan->language);
3930 /* Copy the FD's other than the generator fd */
3931 for (x = 0; x < AST_MAX_FDS; x++) {
3932 if (x != AST_GENERATOR_FD)
3933 ast_channel_set_fd(original, x, clonechan->fds[x]);
3936 ast_app_group_update(clonechan, original);
3938 /* Move data stores over */
3939 if (AST_LIST_FIRST(&clonechan->datastores)) {
3940 struct ast_datastore *ds;
3941 AST_LIST_APPEND_LIST(&original->datastores, &clonechan->datastores, entry);
3942 AST_LIST_TRAVERSE(&original->datastores, ds, entry) {
3943 if (ds->info->chan_fixup)
3944 ds->info->chan_fixup(ds->data, clonechan, original);
3948 clone_variables(original, clonechan);
3949 /* Presense of ADSI capable CPE follows clone */
3950 original->adsicpe = clonechan->adsicpe;
3951 /* Bridge remains the same */
3952 /* CDR fields remain the same */
3953 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3954 /* Application and data remain the same */
3955 /* Clone exception becomes real one, as with fdno */
3956 ast_copy_flags(original, clonechan, AST_FLAG_EXCEPTION);
3957 original->fdno = clonechan->fdno;
3958 /* Schedule context remains the same */
3959 /* Stream stuff stays the same */
3960 /* Keep the original state. The fixup code will need to work with it most likely */
3962 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3963 out. */
3964 tmpcid = original->cid;
3965 original->cid = clonechan->cid;
3966 clonechan->cid = tmpcid;
3968 /* Restore original timing file descriptor */
3969 ast_channel_set_fd(original, AST_TIMING_FD, original->timingfd);
3971 /* Our native formats are different now */
3972 original->nativeformats = clonechan->nativeformats;
3974 /* Context, extension, priority, app data, jump table, remain the same */
3975 /* pvt switches. pbx stays the same, as does next */
3977 /* Set the write format */
3978 ast_set_write_format(original, wformat);
3980 /* Set the read format */
3981 ast_set_read_format(original, rformat);
3983 /* Copy the music class */
3984 ast_string_field_set(original, musicclass, clonechan->musicclass);
3986 ast_debug(1, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3988 /* Okay. Last thing is to let the channel driver know about all this mess, so he
3989 can fix up everything as best as possible */
3990 if (original->tech->fixup) {
3991 res = original->tech->fixup(clonechan, original);
3992 if (res) {
3993 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3994 original->tech->type, original->name);
3995 ast_channel_unlock(clonechan);
3996 return -1;
3998 } else
3999 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
4000 original->tech->type, original->name);
4002 /* If an indication is currently playing maintain it on the channel that is taking the place of original */
4003 if (original->visible_indication)
4004 ast_indicate(original, original->visible_indication);
4006 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
4007 a zombie so nothing tries to touch it. If it's already been marked as a
4008 zombie, then free it now (since it already is considered invalid). */
4009 if (ast_test_flag(clonechan, AST_FLAG_ZOMBIE)) {
4010 ast_debug(1, "Destroying channel clone '%s'\n", clonechan->name);
4011 ast_channel_unlock(clonechan);
4012 manager_event(EVENT_FLAG_CALL, "Hangup",
4013 "Channel: %s\r\n"
4014 "Uniqueid: %s\r\n"
4015 "Cause: %d\r\n"
4016 "Cause-txt: %s\r\n",
4017 clonechan->name,
4018 clonechan->uniqueid,
4019 clonechan->hangupcause,
4020 ast_cause2str(clonechan->hangupcause)
4022 ast_channel_free(clonechan);
4023 } else {
4024 ast_debug(1, "Released clone lock on '%s'\n", clonechan->name);
4025 ast_set_flag(clonechan, AST_FLAG_ZOMBIE);
4026 ast_queue_frame(clonechan, &ast_null_frame);
4027 ast_channel_unlock(clonechan);
4030 /* Signal any blocker */
4031 if (ast_test_flag(original, AST_FLAG_BLOCKING))
4032 pthread_kill(original->blocker, SIGURG);
4033 ast_debug(1, "Done Masquerading %s (%d)\n", original->name, original->_state);
4034 return 0;
4037 void ast_set_callerid(struct ast_channel *chan, const char *cid_num, const char *cid_name, const char *cid_ani)
4039 ast_channel_lock(chan);
4041 if (cid_num) {
4042 if (chan->cid.cid_num)
4043 ast_free(chan->cid.cid_num);
4044 chan->cid.cid_num = ast_strdup(cid_num);
4046 if (cid_name) {
4047 if (chan->cid.cid_name)
4048 ast_free(chan->cid.cid_name);
4049 chan->cid.cid_name = ast_strdup(cid_name);
4051 if (cid_ani) {
4052 if (chan->cid.cid_ani)
4053 ast_free(chan->cid.cid_ani);
4054 chan->cid.cid_ani = ast_strdup(cid_ani);
4056 manager_event(EVENT_FLAG_CALL, "NewCallerid",
4057 "Channel: %s\r\n"
4058 "CallerIDNum: %s\r\n"
4059 "CallerIDName: %s\r\n"
4060 "Uniqueid: %s\r\n"
4061 "CID-CallingPres: %d (%s)\r\n",
4062 chan->name,
4063 S_OR(chan->cid.cid_num, ""),
4064 S_OR(chan->cid.cid_name, ""),
4065 chan->uniqueid,
4066 chan->cid.cid_pres,
4067 ast_describe_caller_presentation(chan->cid.cid_pres)
4070 ast_channel_unlock(chan);
4073 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
4075 int oldstate = chan->_state;
4076 char name[AST_CHANNEL_NAME], *dashptr;
4078 if (oldstate == state)
4079 return 0;
4081 ast_copy_string(name, chan->name, sizeof(name));
4082 if ((dashptr = strrchr(name, '-'))) {
4083 *dashptr = '\0';
4086 chan->_state = state;
4087 ast_devstate_changed_literal(ast_state_chan2dev(state), name);
4088 /* setstate used to conditionally report Newchannel; this is no more */
4089 manager_event(EVENT_FLAG_CALL,
4090 "Newstate",
4091 "Channel: %s\r\n"
4092 "ChannelState: %d\r\n"
4093 "ChannelStateDesc: %s\r\n"
4094 "CallerIDNum: %s\r\n"
4095 "CallerIDName: %s\r\n"
4096 "Uniqueid: %s\r\n",
4097 chan->name, chan->_state, ast_state2str(chan->_state),
4098 S_OR(chan->cid.cid_num, ""),
4099 S_OR(chan->cid.cid_name, ""),
4100 chan->uniqueid);
4102 return 0;
4105 /*! \brief Find bridged channel */
4106 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
4108 struct ast_channel *bridged;
4109 bridged = chan->_bridge;
4110 if (bridged && bridged->tech->bridged_channel)
4111 bridged = bridged->tech->bridged_channel(chan, bridged);
4112 return bridged;
4115 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
4117 int min = 0, sec = 0, check;
4119 check = ast_autoservice_start(peer);
4120 if (check)
4121 return;
4123 if (remain > 0) {
4124 if (remain / 60 > 1) {
4125 min = remain / 60;
4126 sec = remain % 60;
4127 } else {
4128 sec = remain;
4132 if (!strcmp(sound,"timeleft")) { /* Queue support */
4133 ast_stream_and_wait(chan, "vm-youhave", "");
4134 if (min) {
4135 ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
4136 ast_stream_and_wait(chan, "queue-minutes", "");
4138 if (sec) {
4139 ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
4140 ast_stream_and_wait(chan, "queue-seconds", "");
4142 } else {
4143 ast_stream_and_wait(chan, sound, "");
4146 ast_autoservice_stop(peer);
4149 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
4150 struct ast_bridge_config *config, struct ast_frame **fo,
4151 struct ast_channel **rc, struct timeval bridge_end)
4153 /* Copy voice back and forth between the two channels. */
4154 struct ast_channel *cs[3];
4155 struct ast_frame *f;
4156 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
4157 int o0nativeformats;
4158 int o1nativeformats;
4159 int watch_c0_dtmf;
4160 int watch_c1_dtmf;
4161 void *pvt0, *pvt1;
4162 /* Indicates whether a frame was queued into a jitterbuffer */
4163 int frame_put_in_jb = 0;
4164 int jb_in_use;
4165 int to;
4167 cs[0] = c0;
4168 cs[1] = c1;
4169 pvt0 = c0->tech_pvt;
4170 pvt1 = c1->tech_pvt;
4171 o0nativeformats = c0->nativeformats;
4172 o1nativeformats = c1->nativeformats;
4173 watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
4174 watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
4176 /* Check the need of a jitterbuffer for each channel */
4177 jb_in_use = ast_jb_do_usecheck(c0, c1);
4178 if (jb_in_use)
4179 ast_jb_empty_and_reset(c0, c1);
4181 ast_poll_channel_add(c0, c1);
4183 for (;;) {
4184 struct ast_channel *who, *other;
4186 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
4187 (o0nativeformats != c0->nativeformats) ||
4188 (o1nativeformats != c1->nativeformats)) {
4189 /* Check for Masquerade, codec changes, etc */
4190 res = AST_BRIDGE_RETRY;
4191 break;
4193 if (bridge_end.tv_sec) {
4194 to = ast_tvdiff_ms(bridge_end, ast_tvnow());
4195 if (to <= 0) {
4196 if (config->timelimit)
4197 res = AST_BRIDGE_RETRY;
4198 else
4199 res = AST_BRIDGE_COMPLETE;
4200 break;
4202 } else
4203 to = -1;
4204 /* Calculate the appropriate max sleep interval - in general, this is the time,
4205 left to the closest jb delivery moment */
4206 if (jb_in_use)
4207 to = ast_jb_get_when_to_wakeup(c0, c1, to);
4208 who = ast_waitfor_n(cs, 2, &to);
4209 if (!who) {
4210 /* No frame received within the specified timeout - check if we have to deliver now */
4211 if (jb_in_use)
4212 ast_jb_get_and_deliver(c0, c1);
4213 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
4214 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4215 c0->_softhangup = 0;
4216 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4217 c1->_softhangup = 0;
4218 c0->_bridge = c1;
4219 c1->_bridge = c0;
4221 continue;
4223 f = ast_read(who);
4224 if (!f) {
4225 *fo = NULL;
4226 *rc = who;
4227 ast_debug(1, "Didn't get a frame from channel: %s\n",who->name);
4228 break;
4231 other = (who == c0) ? c1 : c0; /* the 'other' channel */
4232 /* Try add the frame info the who's bridged channel jitterbuff */
4233 if (jb_in_use)
4234 frame_put_in_jb = !ast_jb_put(other, f);
4236 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
4237 int bridge_exit = 0;
4239 switch (f->subclass) {
4240 case AST_CONTROL_HOLD:
4241 case AST_CONTROL_UNHOLD:
4242 case AST_CONTROL_VIDUPDATE:
4243 case AST_CONTROL_SRCUPDATE:
4244 ast_indicate_data(other, f->subclass, f->data.ptr, f->datalen);
4245 if (jb_in_use) {
4246 ast_jb_empty_and_reset(c0, c1);
4248 break;
4249 default:
4250 *fo = f;
4251 *rc = who;
4252 bridge_exit = 1;
4253 ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
4254 break;
4256 if (bridge_exit)
4257 break;
4259 if ((f->frametype == AST_FRAME_VOICE) ||
4260 (f->frametype == AST_FRAME_DTMF_BEGIN) ||
4261 (f->frametype == AST_FRAME_DTMF) ||
4262 (f->frametype == AST_FRAME_VIDEO) ||
4263 (f->frametype == AST_FRAME_IMAGE) ||
4264 (f->frametype == AST_FRAME_HTML) ||
4265 (f->frametype == AST_FRAME_MODEM) ||
4266 (f->frametype == AST_FRAME_TEXT)) {
4267 /* monitored dtmf causes exit from bridge */
4268 int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
4270 if (monitored_source &&
4271 (f->frametype == AST_FRAME_DTMF_END ||
4272 f->frametype == AST_FRAME_DTMF_BEGIN)) {
4273 *fo = f;
4274 *rc = who;
4275 ast_debug(1, "Got DTMF %s on channel (%s)\n",
4276 f->frametype == AST_FRAME_DTMF_END ? "end" : "begin",
4277 who->name);
4278 break;
4280 /* Write immediately frames, not passed through jb */
4281 if (!frame_put_in_jb)
4282 ast_write(other, f);
4284 /* Check if we have to deliver now */
4285 if (jb_in_use)
4286 ast_jb_get_and_deliver(c0, c1);
4288 /* XXX do we want to pass on also frames not matched above ? */
4289 ast_frfree(f);
4291 #ifndef HAVE_EPOLL
4292 /* Swap who gets priority */
4293 cs[2] = cs[0];
4294 cs[0] = cs[1];
4295 cs[1] = cs[2];
4296 #endif
4299 ast_poll_channel_del(c0, c1);
4301 return res;
4304 /*! \brief Bridge two channels together (early) */
4305 int ast_channel_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
4307 /* Make sure we can early bridge, if not error out */
4308 if (!c0->tech->early_bridge || (c1 && (!c1->tech->early_bridge || c0->tech->early_bridge != c1->tech->early_bridge)))
4309 return -1;
4311 return c0->tech->early_bridge(c0, c1);
4314 /*! \brief Send manager event for bridge link and unlink events.
4315 * \param onoff Link/Unlinked
4316 * \param type 1 for core, 2 for native
4317 * \param c0 first channel in bridge
4318 * \param c1 second channel in bridge
4320 static void manager_bridge_event(int onoff, int type, struct ast_channel *c0, struct ast_channel *c1)
4322 manager_event(EVENT_FLAG_CALL, "Bridge",
4323 "Bridgestate: %s\r\n"
4324 "Bridgetype: %s\r\n"
4325 "Channel1: %s\r\n"
4326 "Channel2: %s\r\n"
4327 "Uniqueid1: %s\r\n"
4328 "Uniqueid2: %s\r\n"
4329 "CallerID1: %s\r\n"
4330 "CallerID2: %s\r\n",
4331 onoff ? "Link" : "Unlink",
4332 type == 1 ? "core" : "native",
4333 c0->name, c1->name, c0->uniqueid, c1->uniqueid,
4334 S_OR(c0->cid.cid_num, ""),
4335 S_OR(c1->cid.cid_num, ""));
4338 /*! \brief Bridge two channels together */
4339 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
4340 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
4342 struct ast_channel *who = NULL;
4343 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
4344 int nativefailed=0;
4345 int firstpass;
4346 int o0nativeformats;
4347 int o1nativeformats;
4348 long time_left_ms=0;
4349 struct timeval nexteventts = { 0, };
4350 char caller_warning = 0;
4351 char callee_warning = 0;
4353 if (c0->_bridge) {
4354 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
4355 c0->name, c0->_bridge->name);
4356 return -1;
4358 if (c1->_bridge) {
4359 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
4360 c1->name, c1->_bridge->name);
4361 return -1;
4364 /* Stop if we're a zombie or need a soft hangup */
4365 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
4366 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
4367 return -1;
4369 *fo = NULL;
4370 firstpass = config->firstpass;
4371 config->firstpass = 0;
4373 if (ast_tvzero(config->start_time))
4374 config->start_time = ast_tvnow();
4375 time_left_ms = config->timelimit;
4377 caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
4378 callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
4380 if (config->start_sound && firstpass) {
4381 if (caller_warning)
4382 bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
4383 if (callee_warning)
4384 bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
4387 /* Keep track of bridge */
4388 c0->_bridge = c1;
4389 c1->_bridge = c0;
4392 o0nativeformats = c0->nativeformats;
4393 o1nativeformats = c1->nativeformats;
4395 if (config->feature_timer) {
4396 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->feature_timer, 1000));
4397 } else if (config->timelimit) {
4398 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
4399 if (caller_warning || callee_warning)
4400 nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
4403 if (!c0->tech->send_digit_begin)
4404 ast_set_flag(c1, AST_FLAG_END_DTMF_ONLY);
4405 if (!c1->tech->send_digit_begin)
4406 ast_set_flag(c0, AST_FLAG_END_DTMF_ONLY);
4407 manager_bridge_event(1, 1, c0, c1);
4409 /* Before we enter in and bridge these two together tell them both the source of audio has changed */
4410 ast_indicate(c0, AST_CONTROL_SRCUPDATE);
4411 ast_indicate(c1, AST_CONTROL_SRCUPDATE);
4413 for (/* ever */;;) {
4414 struct timeval now = { 0, };
4415 int to;
4416 const char *bridge_play_sound = NULL;
4418 to = -1;
4420 if (!ast_tvzero(nexteventts)) {
4421 now = ast_tvnow();
4422 to = ast_tvdiff_ms(nexteventts, now);
4423 if (to <= 0) {
4424 if (!config->timelimit) {
4425 res = AST_BRIDGE_COMPLETE;
4426 break;
4428 to = 0;
4432 if (config->timelimit) {
4433 time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
4434 if (time_left_ms < to)
4435 to = time_left_ms;
4437 if (time_left_ms <= 0) {
4438 if (caller_warning && config->end_sound)
4439 bridge_playfile(c0, c1, config->end_sound, 0);
4440 if (callee_warning && config->end_sound)
4441 bridge_playfile(c1, c0, config->end_sound, 0);
4442 *fo = NULL;
4443 if (who)
4444 *rc = who;
4445 res = 0;
4446 break;
4449 if (!to) {
4450 if (time_left_ms >= 5000 && config->warning_sound && config->play_warning) {
4451 int t = (time_left_ms + 500) / 1000; /* round to nearest second */
4452 if (caller_warning)
4453 bridge_playfile(c0, c1, config->warning_sound, t);
4454 if (callee_warning)
4455 bridge_playfile(c1, c0, config->warning_sound, t);
4457 if (config->warning_freq && (time_left_ms > (config->warning_freq + 5000)))
4458 nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
4459 else
4460 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
4464 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
4465 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4466 c0->_softhangup = 0;
4467 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4468 c1->_softhangup = 0;
4469 c0->_bridge = c1;
4470 c1->_bridge = c0;
4471 ast_debug(1, "Unbridge signal received. Ending native bridge.\n");
4472 continue;
4475 /* Stop if we're a zombie or need a soft hangup */
4476 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
4477 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
4478 *fo = NULL;
4479 if (who)
4480 *rc = who;
4481 res = 0;
4482 ast_debug(1, "Bridge stops because we're zombie or need a soft hangup: c0=%s, c1=%s, flags: %s,%s,%s,%s\n",
4483 c0->name, c1->name,
4484 ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
4485 ast_check_hangup(c0) ? "Yes" : "No",
4486 ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
4487 ast_check_hangup(c1) ? "Yes" : "No");
4488 break;
4491 /* See if the BRIDGEPEER variable needs to be updated */
4492 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER")))
4493 pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1->name);
4494 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER")))
4495 pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0->name);
4496 if (c0->tech->get_pvt_uniqueid)
4497 pbx_builtin_setvar_helper(c1, "BRIDGEPVTCALLID", c0->tech->get_pvt_uniqueid(c0));
4498 if (c1->tech->get_pvt_uniqueid)
4499 pbx_builtin_setvar_helper(c0, "BRIDGEPVTCALLID", c1->tech->get_pvt_uniqueid(c1));
4501 /* See if we need to play an audio file to any side of the bridge */
4502 if ((bridge_play_sound = pbx_builtin_getvar_helper(c0, "BRIDGE_PLAY_SOUND"))) {
4503 bridge_playfile(c0, c1, bridge_play_sound, 0);
4504 pbx_builtin_setvar_helper(c0, "BRIDGE_PLAY_SOUND", NULL);
4506 if ((bridge_play_sound = pbx_builtin_getvar_helper(c1, "BRIDGE_PLAY_SOUND"))) {
4507 bridge_playfile(c1, c0, bridge_play_sound, 0);
4508 pbx_builtin_setvar_helper(c1, "BRIDGE_PLAY_SOUND", NULL);
4511 if (c0->tech->bridge &&
4512 (c0->tech->bridge == c1->tech->bridge) &&
4513 !nativefailed && !c0->monitor && !c1->monitor &&
4514 !c0->audiohooks && !c1->audiohooks &&
4515 !c0->masq && !c0->masqr && !c1->masq && !c1->masqr) {
4516 /* Looks like they share a bridge method and nothing else is in the way */
4517 ast_set_flag(c0, AST_FLAG_NBRIDGE);
4518 ast_set_flag(c1, AST_FLAG_NBRIDGE);
4519 if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, to)) == AST_BRIDGE_COMPLETE) {
4520 /* \todo XXX here should check that cid_num is not NULL */
4521 manager_event(EVENT_FLAG_CALL, "Unlink",
4522 "Channel1: %s\r\n"
4523 "Channel2: %s\r\n"
4524 "Uniqueid1: %s\r\n"
4525 "Uniqueid2: %s\r\n"
4526 "CallerID1: %s\r\n"
4527 "CallerID2: %s\r\n",
4528 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4529 ast_debug(1, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
4531 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
4532 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
4534 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
4535 continue;
4537 c0->_bridge = NULL;
4538 c1->_bridge = NULL;
4540 return res;
4541 } else {
4542 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
4543 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
4545 switch (res) {
4546 case AST_BRIDGE_RETRY:
4547 continue;
4548 default:
4549 ast_verb(3, "Native bridging %s and %s ended\n", c0->name, c1->name);
4550 /* fallthrough */
4551 case AST_BRIDGE_FAILED_NOWARN:
4552 nativefailed++;
4553 break;
4557 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
4558 (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
4559 !(c0->generator || c1->generator)) {
4560 if (ast_channel_make_compatible(c0, c1)) {
4561 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
4562 manager_bridge_event(0, 1, c0, c1);
4563 return AST_BRIDGE_FAILED;
4565 o0nativeformats = c0->nativeformats;
4566 o1nativeformats = c1->nativeformats;
4569 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER")))
4570 pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1->name);
4571 if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER")))
4572 pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0->name);
4574 res = ast_generic_bridge(c0, c1, config, fo, rc, nexteventts);
4575 if (res != AST_BRIDGE_RETRY)
4576 break;
4579 ast_clear_flag(c0, AST_FLAG_END_DTMF_ONLY);
4580 ast_clear_flag(c1, AST_FLAG_END_DTMF_ONLY);
4582 /* Now that we have broken the bridge the source will change yet again */
4583 ast_indicate(c0, AST_CONTROL_SRCUPDATE);
4584 ast_indicate(c1, AST_CONTROL_SRCUPDATE);
4586 c0->_bridge = NULL;
4587 c1->_bridge = NULL;
4589 /* \todo XXX here should check that cid_num is not NULL */
4590 manager_event(EVENT_FLAG_CALL, "Unlink",
4591 "Channel1: %s\r\n"
4592 "Channel2: %s\r\n"
4593 "Uniqueid1: %s\r\n"
4594 "Uniqueid2: %s\r\n"
4595 "CallerID1: %s\r\n"
4596 "CallerID2: %s\r\n",
4597 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
4598 ast_debug(1, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
4600 return res;
4603 /*! \brief Sets an option on a channel */
4604 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
4606 if (!chan->tech->setoption) {
4607 errno = ENOSYS;
4608 return -1;
4611 if (block)
4612 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
4614 return chan->tech->setoption(chan, option, data, datalen);
4617 int ast_channel_queryoption(struct ast_channel *chan, int option, void *data, int *datalen, int block)
4619 if (!chan->tech->queryoption) {
4620 errno = ENOSYS;
4621 return -1;
4624 if (block)
4625 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
4627 return chan->tech->queryoption(chan, option, data, datalen);
4630 struct tonepair_def {
4631 int freq1;
4632 int freq2;
4633 int duration;
4634 int vol;
4637 struct tonepair_state {
4638 int fac1;
4639 int fac2;
4640 int v1_1;
4641 int v2_1;
4642 int v3_1;
4643 int v1_2;
4644 int v2_2;
4645 int v3_2;
4646 int origwfmt;
4647 int pos;
4648 int duration;
4649 int modulate;
4650 struct ast_frame f;
4651 unsigned char offset[AST_FRIENDLY_OFFSET];
4652 short data[4000];
4655 static void tonepair_release(struct ast_channel *chan, void *params)
4657 struct tonepair_state *ts = params;
4659 if (chan)
4660 ast_set_write_format(chan, ts->origwfmt);
4661 ast_free(ts);
4664 static void *tonepair_alloc(struct ast_channel *chan, void *params)
4666 struct tonepair_state *ts;
4667 struct tonepair_def *td = params;
4669 if (!(ts = ast_calloc(1, sizeof(*ts))))
4670 return NULL;
4671 ts->origwfmt = chan->writeformat;
4672 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
4673 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
4674 tonepair_release(NULL, ts);
4675 ts = NULL;
4676 } else {
4677 ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
4678 ts->v1_1 = 0;
4679 ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4680 ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
4681 ts->v2_1 = 0;
4682 ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
4683 ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4684 ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
4685 ts->duration = td->duration;
4686 ts->modulate = 0;
4688 /* Let interrupts interrupt :) */
4689 ast_set_flag(chan, AST_FLAG_WRITE_INT);
4690 return ts;
4693 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
4695 struct tonepair_state *ts = data;
4696 int x;
4698 /* we need to prepare a frame with 16 * timelen samples as we're
4699 * generating SLIN audio
4701 len = samples * 2;
4703 if (len > sizeof(ts->data) / 2 - 1) {
4704 ast_log(LOG_WARNING, "Can't generate that much data!\n");
4705 return -1;
4707 memset(&ts->f, 0, sizeof(ts->f));
4708 for (x=0;x<len/2;x++) {
4709 ts->v1_1 = ts->v2_1;
4710 ts->v2_1 = ts->v3_1;
4711 ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;
4713 ts->v1_2 = ts->v2_2;
4714 ts->v2_2 = ts->v3_2;
4715 ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
4716 if (ts->modulate) {
4717 int p;
4718 p = ts->v3_2 - 32768;
4719 if (p < 0) p = -p;
4720 p = ((p * 9) / 10) + 1;
4721 ts->data[x] = (ts->v3_1 * p) >> 15;
4722 } else
4723 ts->data[x] = ts->v3_1 + ts->v3_2;
4725 ts->f.frametype = AST_FRAME_VOICE;
4726 ts->f.subclass = AST_FORMAT_SLINEAR;
4727 ts->f.datalen = len;
4728 ts->f.samples = samples;
4729 ts->f.offset = AST_FRIENDLY_OFFSET;
4730 ts->f.data.ptr = ts->data;
4731 ast_write(chan, &ts->f);
4732 ts->pos += x;
4733 if (ts->duration > 0) {
4734 if (ts->pos >= ts->duration * 8)
4735 return -1;
4737 return 0;
4740 static struct ast_generator tonepair = {
4741 alloc: tonepair_alloc,
4742 release: tonepair_release,
4743 generate: tonepair_generator,
4746 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4748 struct tonepair_def d = { 0, };
4750 d.freq1 = freq1;
4751 d.freq2 = freq2;
4752 d.duration = duration;
4753 d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
4754 if (ast_activate_generator(chan, &tonepair, &d))
4755 return -1;
4756 return 0;
4759 void ast_tonepair_stop(struct ast_channel *chan)
4761 ast_deactivate_generator(chan);
4764 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
4766 int res;
4768 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
4769 return res;
4771 /* Give us some wiggle room */
4772 while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
4773 struct ast_frame *f = ast_read(chan);
4774 if (f)
4775 ast_frfree(f);
4776 else
4777 return -1;
4779 return 0;
4782 ast_group_t ast_get_group(const char *s)
4784 char *piece;
4785 char *c;
4786 int start=0, finish=0, x;
4787 ast_group_t group = 0;
4789 if (ast_strlen_zero(s))
4790 return 0;
4792 c = ast_strdupa(s);
4794 while ((piece = strsep(&c, ","))) {
4795 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
4796 /* Range */
4797 } else if (sscanf(piece, "%d", &start)) {
4798 /* Just one */
4799 finish = start;
4800 } else {
4801 ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
4802 continue;
4804 for (x = start; x <= finish; x++) {
4805 if ((x > 63) || (x < 0)) {
4806 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
4807 } else
4808 group |= ((ast_group_t) 1 << x);
4811 return group;
4814 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
4815 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
4816 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
4818 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
4819 void (*stop_ptr)(struct ast_channel *),
4820 void (*cleanup_ptr)(struct ast_channel *))
4822 ast_moh_start_ptr = start_ptr;
4823 ast_moh_stop_ptr = stop_ptr;
4824 ast_moh_cleanup_ptr = cleanup_ptr;
4827 void ast_uninstall_music_functions(void)
4829 ast_moh_start_ptr = NULL;
4830 ast_moh_stop_ptr = NULL;
4831 ast_moh_cleanup_ptr = NULL;
4834 /*! \brief Turn on music on hold on a given channel */
4835 int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
4837 if (ast_moh_start_ptr)
4838 return ast_moh_start_ptr(chan, mclass, interpclass);
4840 ast_verb(3, "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : (interpclass ? interpclass : "default"));
4842 return 0;
4845 /*! \brief Turn off music on hold on a given channel */
4846 void ast_moh_stop(struct ast_channel *chan)
4848 if (ast_moh_stop_ptr)
4849 ast_moh_stop_ptr(chan);
4852 void ast_moh_cleanup(struct ast_channel *chan)
4854 if (ast_moh_cleanup_ptr)
4855 ast_moh_cleanup_ptr(chan);
4858 void ast_channels_init(void)
4860 ast_cli_register_multiple(cli_channel, ARRAY_LEN(cli_channel));
4863 /*! \brief Print call group and pickup group ---*/
4864 char *ast_print_group(char *buf, int buflen, ast_group_t group)
4866 unsigned int i;
4867 int first = 1;
4868 char num[3];
4870 buf[0] = '\0';
4872 if (!group) /* Return empty string if no group */
4873 return buf;
4875 for (i = 0; i <= 63; i++) { /* Max group is 63 */
4876 if (group & ((ast_group_t) 1 << i)) {
4877 if (!first) {
4878 strncat(buf, ", ", buflen - strlen(buf) - 1);
4879 } else {
4880 first = 0;
4882 snprintf(num, sizeof(num), "%u", i);
4883 strncat(buf, num, buflen - strlen(buf) - 1);
4886 return buf;
4889 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
4891 struct ast_variable *cur;
4893 for (cur = vars; cur; cur = cur->next)
4894 pbx_builtin_setvar_helper(chan, cur->name, cur->value);
4897 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
4899 /* just store the data pointer in the channel structure */
4900 return data;
4903 static void silence_generator_release(struct ast_channel *chan, void *data)
4905 /* nothing to do */
4908 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
4910 short buf[samples];
4911 struct ast_frame frame = {
4912 .frametype = AST_FRAME_VOICE,
4913 .subclass = AST_FORMAT_SLINEAR,
4914 .data.ptr = buf,
4915 .samples = samples,
4916 .datalen = sizeof(buf),
4919 memset(buf, 0, sizeof(buf));
4921 if (ast_write(chan, &frame))
4922 return -1;
4924 return 0;
4927 static struct ast_generator silence_generator = {
4928 .alloc = silence_generator_alloc,
4929 .release = silence_generator_release,
4930 .generate = silence_generator_generate,
4933 struct ast_silence_generator {
4934 int old_write_format;
4937 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
4939 struct ast_silence_generator *state;
4941 if (!(state = ast_calloc(1, sizeof(*state)))) {
4942 return NULL;
4945 state->old_write_format = chan->writeformat;
4947 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
4948 ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
4949 ast_free(state);
4950 return NULL;
4953 ast_activate_generator(chan, &silence_generator, state);
4955 ast_debug(1, "Started silence generator on '%s'\n", chan->name);
4957 return state;
4960 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
4962 if (!state)
4963 return;
4965 ast_deactivate_generator(chan);
4967 ast_debug(1, "Stopped silence generator on '%s'\n", chan->name);
4969 if (ast_set_write_format(chan, state->old_write_format) < 0)
4970 ast_log(LOG_ERROR, "Could not return write format to its original state\n");
4972 ast_free(state);
4976 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
4977 const char *channelreloadreason2txt(enum channelreloadreason reason)
4979 switch (reason) {
4980 case CHANNEL_MODULE_LOAD:
4981 return "LOAD (Channel module load)";
4983 case CHANNEL_MODULE_RELOAD:
4984 return "RELOAD (Channel module reload)";
4986 case CHANNEL_CLI_RELOAD:
4987 return "CLIRELOAD (Channel module reload by CLI command)";
4989 default:
4990 return "MANAGERRELOAD (Channel module reload by manager)";
4994 #ifdef DEBUG_CHANNEL_LOCKS
4996 /*! \brief Unlock AST channel (and print debugging output)
4997 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
4999 int __ast_channel_unlock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
5001 int res = 0;
5002 ast_debug(3, "::::==== Unlocking AST channel %s\n", chan->name);
5004 if (!chan) {
5005 ast_debug(1, "::::==== Unlocking non-existing channel \n");
5006 return 0;
5008 #ifdef DEBUG_THREADS
5009 res = __ast_pthread_mutex_unlock(filename, lineno, func, "(channel lock)", &chan->lock_dont_use);
5010 #else
5011 res = ast_mutex_unlock(&chan->lock_dont_use);
5012 #endif
5014 if (option_debug > 2) {
5015 #ifdef DEBUG_THREADS
5016 int count = 0;
5017 if ((count = chan->lock_dont_use.track.reentrancy))
5018 ast_debug(3, ":::=== Still have %d locks (recursive)\n", count);
5019 #endif
5020 if (!res)
5021 ast_debug(3, "::::==== Channel %s was unlocked\n", chan->name);
5022 if (res == EINVAL) {
5023 ast_debug(3, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan->name);
5026 if (res == EPERM) {
5027 /* We had no lock, so okay any way*/
5028 ast_debug(4, "::::==== Channel %s was not locked at all \n", chan->name);
5029 res = 0;
5031 return res;
5034 /*! \brief Lock AST channel (and print debugging output)
5035 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
5036 int __ast_channel_lock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
5038 int res;
5040 ast_debug(4, "====:::: Locking AST channel %s\n", chan->name);
5042 #ifdef DEBUG_THREADS
5043 res = __ast_pthread_mutex_lock(filename, lineno, func, "(channel lock)", &chan->lock_dont_use);
5044 #else
5045 res = ast_mutex_lock(&chan->lock_dont_use);
5046 #endif
5048 if (option_debug > 3) {
5049 #ifdef DEBUG_THREADS
5050 int count = 0;
5051 if ((count = chan->lock_dont_use.track.reentrancy))
5052 ast_debug(4, ":::=== Now have %d locks (recursive)\n", count);
5053 #endif
5054 if (!res)
5055 ast_debug(4, "::::==== Channel %s was locked\n", chan->name);
5056 if (res == EDEADLK) {
5057 /* We had no lock, so okey any way */
5058 ast_debug(4, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan->name);
5060 if (res == EINVAL) {
5061 ast_debug(4, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
5064 return res;
5067 /*! \brief Lock AST channel (and print debugging output)
5068 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
5069 int __ast_channel_trylock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
5071 int res;
5073 ast_debug(3, "====:::: Trying to lock AST channel %s\n", chan->name);
5074 #ifdef DEBUG_THREADS
5075 res = __ast_pthread_mutex_trylock(filename, lineno, func, "(channel lock)", &chan->lock_dont_use);
5076 #else
5077 res = ast_mutex_trylock(&chan->lock_dont_use);
5078 #endif
5080 if (option_debug > 2) {
5081 #ifdef DEBUG_THREADS
5082 int count = 0;
5083 if ((count = chan->lock_dont_use.track.reentrancy))
5084 ast_debug(3, ":::=== Now have %d locks (recursive)\n", count);
5085 #endif
5086 if (!res)
5087 ast_debug(3, "::::==== Channel %s was locked\n", chan->name);
5088 if (res == EBUSY) {
5089 /* We failed to lock */
5090 ast_debug(3, "::::==== Channel %s failed to lock. Not waiting around...\n", chan->name);
5092 if (res == EDEADLK) {
5093 /* We had no lock, so okey any way*/
5094 ast_debug(3, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan->name);
5096 if (res == EINVAL)
5097 ast_debug(3, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
5099 return res;
5102 #endif
5105 * Wrappers for various ast_say_*() functions that call the full version
5106 * of the same functions.
5107 * The proper place would be say.c, but that file is optional and one
5108 * must be able to build asterisk even without it (using a loadable 'say'
5109 * implementation that only supplies the 'full' version of the functions.
5112 int ast_say_number(struct ast_channel *chan, int num,
5113 const char *ints, const char *language, const char *options)
5115 return ast_say_number_full(chan, num, ints, language, options, -1, -1);
5118 int ast_say_enumeration(struct ast_channel *chan, int num,
5119 const char *ints, const char *language, const char *options)
5121 return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
5124 int ast_say_digits(struct ast_channel *chan, int num,
5125 const char *ints, const char *lang)
5127 return ast_say_digits_full(chan, num, ints, lang, -1, -1);
5130 int ast_say_digit_str(struct ast_channel *chan, const char *str,
5131 const char *ints, const char *lang)
5133 return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
5136 int ast_say_character_str(struct ast_channel *chan, const char *str,
5137 const char *ints, const char *lang)
5139 return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
5142 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
5143 const char *ints, const char *lang)
5145 return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
5148 int ast_say_digits_full(struct ast_channel *chan, int num,
5149 const char *ints, const char *lang, int audiofd, int ctrlfd)
5151 char buf[256];
5153 snprintf(buf, sizeof(buf), "%d", num);
5155 return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);