Merged revisions 179461 via svnmerge from
[asterisk/asterisk.git] / main / channel.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
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.
13  *
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.
17  */
18
19 /*! \file
20  *
21  * \brief Channel Management
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include "asterisk/_private.h"
31
32 #include <sys/time.h>
33 #include <signal.h>
34 #include <math.h>
35
36 #include "asterisk/paths.h"     /* use ast_config_AST_SYSTEM_NAME */
37
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"
64
65 #ifdef HAVE_EPOLL
66 #include <sys/epoll.h>
67 #endif
68
69 struct ast_epoll_data {
70         struct ast_channel *chan;
71         int which;
72 };
73
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
79
80 /*! \brief Prevent new channel allocation if shutting down. */
81 static int shutting_down;
82
83 static int uniqueint;
84
85 unsigned long global_fin, global_fout;
86
87 AST_THREADSTORAGE(state2str_threadbuf);
88 #define STATE2STR_BUFSIZE   32
89
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
93
94 /*! Minimum allowed digit length - 80ms */
95 #define AST_MIN_DTMF_DURATION 80
96
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
100
101 /*! \brief List of channel drivers */
102 struct chanlist {
103         const struct ast_channel_tech *tech;
104         AST_LIST_ENTRY(chanlist) list;
105 };
106
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;
112 };
113
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;
120 };
121 #endif
122
123 /*! \brief the list of registered channel types */
124 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
125
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);
129
130 /*! \brief map AST_CAUSE's to readable string representations 
131  *
132  * \ref causes.h
133 */
134 static const struct {
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" },
183 };
184
185 struct ast_variable *ast_channeltype_list(void)
186 {
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;
196                 }
197         }
198         return var;
199 }
200
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)
203 {
204 #define FORMAT  "%-10.10s  %-40.40s %-12.12s %-12.12s %-12.12s\n"
205         struct chanlist *cl;
206         int count_chan = 0;
207
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;
218         }
219
220         if (a->argc != 3)
221                 return CLI_SHOWUSAGE;
222
223         ast_cli(a->fd, FORMAT, "Type", "Description",       "Devicestate", "Indications", "Transfer");
224         ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
225
226         AST_RWLIST_RDLOCK(&channels);
227
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++;
234         }
235
236         AST_RWLIST_UNLOCK(&channels);
237
238         ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
239
240         return CLI_SUCCESS;
241
242 #undef FORMAT
243 }
244
245 static char *complete_channeltypes(struct ast_cli_args *a)
246 {
247         struct chanlist *cl;
248         int which = 0;
249         int wordlen;
250         char *ret = NULL;
251
252         if (a->pos != 3)
253                 return NULL;
254
255         wordlen = strlen(a->word);
256
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;
261                 }
262         }
263         
264         return ret;
265 }
266
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)
269 {
270         struct chanlist *cl = NULL;
271
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);
281         }
282
283         if (a->argc != 4)
284                 return CLI_SHOWUSAGE;
285         
286         AST_RWLIST_RDLOCK(&channels);
287
288         AST_LIST_TRAVERSE(&backends, cl, list) {
289                 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
290                         break;
291         }
292
293
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;
298         }
299
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"
321                 
322         );
323
324         AST_RWLIST_UNLOCK(&channels);
325         return CLI_SUCCESS;
326 }
327
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")
331 };
332
333 #ifdef CHANNEL_TRACE
334 /*! \brief Destructor for the channel trace datastore */
335 static void ast_chan_trace_destroy_cb(void *data)
336 {
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);
341         }
342         ast_free(traced);
343 }
344
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
349 };
350
351 /*! \brief Put the channel backtrace in a string */
352 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
353 {
354         int total = 0;
355         struct ast_chan_trace *trace;
356         struct ast_chan_trace_data *traced;
357         struct ast_datastore *store;
358
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;
364         }
365         traced = store->data;
366         ast_str_reset(*buf);
367         AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
368                 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
369                         ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
370                         total = -1;
371                         break;
372                 }
373                 total++;
374         }
375         ast_channel_unlock(chan);
376         return total;
377 }
378
379 /* !\brief Whether or not context tracing is enabled */
380 int ast_channel_trace_is_enabled(struct ast_channel *chan)
381 {
382         struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
383         if (!store)
384                 return 0;
385         return ((struct ast_chan_trace_data *)store->data)->enabled;
386 }
387
388 /*! \brief Update the context backtrace data if tracing is enabled */
389 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
390 {
391         struct ast_chan_trace *trace;
392         if (!traced->enabled)
393                 return 0;
394         /* If the last saved context does not match the current one
395            OR we have not saved any context so far, then save the current context */
396         if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) || 
397             (AST_LIST_EMPTY(&traced->trace))) {
398                 /* Just do some debug logging */
399                 if (AST_LIST_EMPTY(&traced->trace))
400                         ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
401                 else
402                         ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
403                 /* alloc or bail out */
404                 trace = ast_malloc(sizeof(*trace));
405                 if (!trace) 
406                         return -1;
407                 /* save the current location and store it in the trace list */
408                 ast_copy_string(trace->context, chan->context, sizeof(trace->context));
409                 ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
410                 trace->priority = chan->priority;
411                 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
412         }
413         return 0;
414 }
415
416 /*! \brief Update the context backtrace if tracing is enabled */
417 int ast_channel_trace_update(struct ast_channel *chan)
418 {
419         struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
420         if (!store)
421                 return 0;
422         return ast_channel_trace_data_update(chan, store->data);
423 }
424
425 /*! \brief Enable context tracing in the channel */
426 int ast_channel_trace_enable(struct ast_channel *chan)
427 {
428         struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
429         struct ast_chan_trace_data *traced;
430         if (!store) {
431                 store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
432                 if (!store) 
433                         return -1;
434                 traced = ast_calloc(1, sizeof(*traced));
435                 if (!traced) {
436                         ast_datastore_free(store);
437                         return -1;
438                 }       
439                 store->data = traced;
440                 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
441                 ast_channel_datastore_add(chan, store);
442         }       
443         ((struct ast_chan_trace_data *)store->data)->enabled = 1;
444         ast_channel_trace_data_update(chan, store->data);
445         return 0;
446 }
447
448 /*! \brief Disable context tracing in the channel */
449 int ast_channel_trace_disable(struct ast_channel *chan)
450 {
451         struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
452         if (!store)
453                 return 0;
454         ((struct ast_chan_trace_data *)store->data)->enabled = 0;
455         return 0;
456 }
457 #endif /* CHANNEL_TRACE */
458
459 /*! \brief Checks to see if a channel is needing hang up */
460 int ast_check_hangup(struct ast_channel *chan)
461 {
462         if (chan->_softhangup)          /* yes if soft hangup flag set */
463                 return 1;
464         if (ast_tvzero(chan->whentohangup))     /* no if no hangup scheduled */
465                 return 0;
466         if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0)         /* no if hangup time has not come yet. */
467                 return 0;
468         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;    /* record event */
469         return 1;
470 }
471
472 static int ast_check_hangup_locked(struct ast_channel *chan)
473 {
474         int res;
475         ast_channel_lock(chan);
476         res = ast_check_hangup(chan);
477         ast_channel_unlock(chan);
478         return res;
479 }
480
481 /*! \brief Initiate system shutdown */
482 void ast_begin_shutdown(int hangup)
483 {
484         struct ast_channel *c;
485         shutting_down = 1;
486         if (hangup) {
487                 AST_RWLIST_RDLOCK(&channels);
488                 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
489                         ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
490                 }
491                 AST_RWLIST_UNLOCK(&channels);
492         }
493 }
494
495 /*! \brief returns number of active/allocated channels */
496 int ast_active_channels(void)
497 {
498         struct ast_channel *c;
499         int cnt = 0;
500         AST_RWLIST_RDLOCK(&channels);
501         AST_RWLIST_TRAVERSE(&channels, c, chan_list)
502                 cnt++;
503         AST_RWLIST_UNLOCK(&channels);
504         return cnt;
505 }
506
507 /*! \brief Cancel a shutdown in progress */
508 void ast_cancel_shutdown(void)
509 {
510         shutting_down = 0;
511 }
512
513 /*! \brief Returns non-zero if Asterisk is being shut down */
514 int ast_shutting_down(void)
515 {
516         return shutting_down;
517 }
518
519 /*! \brief Set when to hangup channel */
520 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
521 {
522         chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
523         ast_queue_frame(chan, &ast_null_frame);
524         return;
525 }
526
527 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
528 {
529         struct timeval when = { offset, };
530         ast_channel_setwhentohangup_tv(chan, when);
531 }
532
533 /*! \brief Compare a offset with when to hangup channel */
534 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
535 {
536         struct timeval whentohangup;
537
538         if (ast_tvzero(chan->whentohangup))
539                 return ast_tvzero(offset) ? 0 : -1;
540
541         if (ast_tvzero(offset))
542                 return 1;
543
544         whentohangup = ast_tvadd(offset, ast_tvnow());
545
546         return ast_tvdiff_ms(whentohangup, chan->whentohangup);
547 }
548
549 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
550 {
551         struct timeval when = { offset, };
552         return ast_channel_cmpwhentohangup_tv(chan, when);
553 }
554
555 /*! \brief Register a new telephony channel in Asterisk */
556 int ast_channel_register(const struct ast_channel_tech *tech)
557 {
558         struct chanlist *chan;
559
560         AST_RWLIST_WRLOCK(&channels);
561
562         AST_LIST_TRAVERSE(&backends, chan, list) {
563                 if (!strcasecmp(tech->type, chan->tech->type)) {
564                         ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
565                         AST_RWLIST_UNLOCK(&channels);
566                         return -1;
567                 }
568         }
569         
570         if (!(chan = ast_calloc(1, sizeof(*chan)))) {
571                 AST_RWLIST_UNLOCK(&channels);
572                 return -1;
573         }
574         chan->tech = tech;
575         AST_LIST_INSERT_HEAD(&backends, chan, list);
576
577         ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
578
579         ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
580
581         AST_RWLIST_UNLOCK(&channels);
582         return 0;
583 }
584
585 /*! \brief Unregister channel driver */
586 void ast_channel_unregister(const struct ast_channel_tech *tech)
587 {
588         struct chanlist *chan;
589
590         ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
591
592         AST_RWLIST_WRLOCK(&channels);
593
594         AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
595                 if (chan->tech == tech) {
596                         AST_LIST_REMOVE_CURRENT(list);
597                         ast_free(chan);
598                         ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
599                         break;  
600                 }
601         }
602         AST_LIST_TRAVERSE_SAFE_END;
603
604         AST_RWLIST_UNLOCK(&channels);
605 }
606
607 /*! \brief Get handle to channel driver based on name */
608 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
609 {
610         struct chanlist *chanls;
611         const struct ast_channel_tech *ret = NULL;
612
613         AST_RWLIST_RDLOCK(&channels);
614
615         AST_LIST_TRAVERSE(&backends, chanls, list) {
616                 if (!strcasecmp(name, chanls->tech->type)) {
617                         ret = chanls->tech;
618                         break;
619                 }
620         }
621
622         AST_RWLIST_UNLOCK(&channels);
623         
624         return ret;
625 }
626
627 /*! \brief Gives the string form of a given hangup cause */
628 const char *ast_cause2str(int cause)
629 {
630         int x;
631
632         for (x = 0; x < ARRAY_LEN(causes); x++) {
633                 if (causes[x].cause == cause)
634                         return causes[x].desc;
635         }
636
637         return "Unknown";
638 }
639
640 /*! \brief Convert a symbolic hangup cause to number */
641 int ast_str2cause(const char *name)
642 {
643         int x;
644
645         for (x = 0; x < ARRAY_LEN(causes); x++)
646                 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
647                         return causes[x].cause;
648
649         return -1;
650 }
651
652 /*! \brief Gives the string form of a given channel state.
653         \note This function is not reentrant.
654  */
655 const char *ast_state2str(enum ast_channel_state state)
656 {
657         char *buf;
658
659         switch (state) {
660         case AST_STATE_DOWN:
661                 return "Down";
662         case AST_STATE_RESERVED:
663                 return "Rsrvd";
664         case AST_STATE_OFFHOOK:
665                 return "OffHook";
666         case AST_STATE_DIALING:
667                 return "Dialing";
668         case AST_STATE_RING:
669                 return "Ring";
670         case AST_STATE_RINGING:
671                 return "Ringing";
672         case AST_STATE_UP:
673                 return "Up";
674         case AST_STATE_BUSY:
675                 return "Busy";
676         case AST_STATE_DIALING_OFFHOOK:
677                 return "Dialing Offhook";
678         case AST_STATE_PRERING:
679                 return "Pre-ring";
680         default:
681                 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
682                         return "Unknown";
683                 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
684                 return buf;
685         }
686 }
687
688 /*! \brief Gives the string form of a given transfer capability */
689 char *ast_transfercapability2str(int transfercapability)
690 {
691         switch (transfercapability) {
692         case AST_TRANS_CAP_SPEECH:
693                 return "SPEECH";
694         case AST_TRANS_CAP_DIGITAL:
695                 return "DIGITAL";
696         case AST_TRANS_CAP_RESTRICTED_DIGITAL:
697                 return "RESTRICTED_DIGITAL";
698         case AST_TRANS_CAP_3_1K_AUDIO:
699                 return "3K1AUDIO";
700         case AST_TRANS_CAP_DIGITAL_W_TONES:
701                 return "DIGITAL_W_TONES";
702         case AST_TRANS_CAP_VIDEO:
703                 return "VIDEO";
704         default:
705                 return "UNKNOWN";
706         }
707 }
708
709 /*! \brief Pick the best audio codec */
710 int ast_best_codec(int fmts)
711 {
712         /* This just our opinion, expressed in code.  We are asked to choose
713            the best codec to use, given no information */
714         int x;
715         static const int prefs[] =
716         {
717                 /*! Okay, ulaw is used by all telephony equipment, so start with it */
718                 AST_FORMAT_ULAW,
719                 /*! Unless of course, you're a silly European, so then prefer ALAW */
720                 AST_FORMAT_ALAW,
721                 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
722                 AST_FORMAT_G722,
723                 /*! Okay, well, signed linear is easy to translate into other stuff */
724                 AST_FORMAT_SLINEAR16,
725                 AST_FORMAT_SLINEAR,
726                 /*! G.726 is standard ADPCM, in RFC3551 packing order */
727                 AST_FORMAT_G726,
728                 /*! G.726 is standard ADPCM, in AAL2 packing order */
729                 AST_FORMAT_G726_AAL2,
730                 /*! ADPCM has great sound quality and is still pretty easy to translate */
731                 AST_FORMAT_ADPCM,
732                 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
733                     translate and sounds pretty good */
734                 AST_FORMAT_GSM,
735                 /*! iLBC is not too bad */
736                 AST_FORMAT_ILBC,
737                 /*! Speex is free, but computationally more expensive than GSM */
738                 AST_FORMAT_SPEEX,
739                 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
740                     to use it */
741                 AST_FORMAT_LPC10,
742                 /*! G.729a is faster than 723 and slightly less expensive */
743                 AST_FORMAT_G729A,
744                 /*! Down to G.723.1 which is proprietary but at least designed for voice */
745                 AST_FORMAT_G723_1,
746         };
747
748         /* Strip out video */
749         fmts &= AST_FORMAT_AUDIO_MASK;
750         
751         /* Find the first preferred codec in the format given */
752         for (x = 0; x < ARRAY_LEN(prefs); x++) {
753                 if (fmts & prefs[x])
754                         return prefs[x];
755         }
756
757         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
758
759         return 0;
760 }
761
762 static const struct ast_channel_tech null_tech = {
763         .type = "NULL",
764         .description = "Null channel (should not see this)",
765 };
766
767 /*! \brief Create a new channel structure */
768 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, ...)
769 {
770         struct ast_channel *tmp;
771         int x;
772         int flags;
773         struct varshead *headp;
774         va_list ap1, ap2;
775
776         /* If shutting down, don't allocate any new channels */
777         if (shutting_down) {
778                 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
779                 return NULL;
780         }
781
782         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
783                 return NULL;
784
785         if (!(tmp->sched = sched_context_create())) {
786                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
787                 ast_free(tmp);
788                 return NULL;
789         }
790         
791         if ((ast_string_field_init(tmp, 128))) {
792                 sched_context_destroy(tmp->sched);
793                 ast_free(tmp);
794                 return NULL;
795         }
796
797 #ifdef HAVE_EPOLL
798         tmp->epfd = epoll_create(25);
799 #endif
800
801         for (x = 0; x < AST_MAX_FDS; x++) {
802                 tmp->fds[x] = -1;
803 #ifdef HAVE_EPOLL
804                 tmp->epfd_data[x] = NULL;
805 #endif
806         }
807
808         tmp->timingfd = ast_timer_open();
809         if (tmp->timingfd > -1) {
810                 needqueue = 0;
811         }
812
813         if (needqueue) {
814                 if (pipe(tmp->alertpipe)) {
815                         ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
816 alertpipe_failed:
817                         if (tmp->timingfd > -1) {
818                                 ast_timer_close(tmp->timingfd);
819                         }
820
821                         sched_context_destroy(tmp->sched);
822                         ast_string_field_free_memory(tmp);
823                         ast_free(tmp);
824                         return NULL;
825                 } else {
826                         flags = fcntl(tmp->alertpipe[0], F_GETFL);
827                         if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
828                                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
829                                 close(tmp->alertpipe[0]);
830                                 close(tmp->alertpipe[1]);
831                                 goto alertpipe_failed;
832                         }
833                         flags = fcntl(tmp->alertpipe[1], F_GETFL);
834                         if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
835                                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
836                                 close(tmp->alertpipe[0]);
837                                 close(tmp->alertpipe[1]);
838                                 goto alertpipe_failed;
839                         }
840                 }
841         } else  /* Make sure we've got it done right if they don't */
842                 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
843
844         /* Always watch the alertpipe */
845         ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
846         /* And timing pipe */
847         ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
848         ast_string_field_set(tmp, name, "**Unknown**");
849
850         /* Initial state */
851         tmp->_state = state;
852
853         tmp->streamid = -1;
854         
855         tmp->fin = global_fin;
856         tmp->fout = global_fout;
857
858         if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
859                 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), 
860                                        ast_atomic_fetchadd_int(&uniqueint, 1));
861         } else {
862                 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, 
863                                        (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
864         }
865
866         tmp->cid.cid_name = ast_strdup(cid_name);
867         tmp->cid.cid_num = ast_strdup(cid_num);
868         
869         if (!ast_strlen_zero(name_fmt)) {
870                 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
871                  * And they all use slightly different formats for their name string.
872                  * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
873                  * This means, that the stringfields must have a routine that takes the va_lists directly, and 
874                  * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
875                  * This new function was written so this can be accomplished.
876                  */
877                 va_start(ap1, name_fmt);
878                 va_start(ap2, name_fmt);
879                 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
880                 va_end(ap1);
881                 va_end(ap2);
882         }
883
884         /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
885
886         /* These 4 variables need to be set up for the cdr_init() to work right */
887         if (amaflag)
888                 tmp->amaflags = amaflag;
889         else
890                 tmp->amaflags = ast_default_amaflags;
891         
892         if (!ast_strlen_zero(acctcode))
893                 ast_string_field_set(tmp, accountcode, acctcode);
894         else
895                 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
896                 
897         if (!ast_strlen_zero(context))
898                 ast_copy_string(tmp->context, context, sizeof(tmp->context));
899         else
900                 strcpy(tmp->context, "default");
901
902         if (!ast_strlen_zero(exten))
903                 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
904         else
905                 strcpy(tmp->exten, "s");
906
907         tmp->priority = 1;
908                 
909         tmp->cdr = ast_cdr_alloc();
910         ast_cdr_init(tmp->cdr, tmp);
911         ast_cdr_start(tmp->cdr);
912         
913         headp = &tmp->varshead;
914         AST_LIST_HEAD_INIT_NOLOCK(headp);
915         
916         ast_mutex_init(&tmp->lock_dont_use);
917         
918         AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
919         
920         ast_string_field_set(tmp, language, defaultlanguage);
921
922         tmp->tech = &null_tech;
923
924         AST_RWLIST_WRLOCK(&channels);
925         AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
926         AST_RWLIST_UNLOCK(&channels);
927
928         /*\!note
929          * and now, since the channel structure is built, and has its name, let's
930          * call the manager event generator with this Newchannel event. This is the
931          * proper and correct place to make this call, but you sure do have to pass
932          * a lot of data into this func to do it here!
933          */
934         if (!ast_strlen_zero(name_fmt)) {
935                 manager_event(EVENT_FLAG_CALL, "Newchannel",
936                         "Channel: %s\r\n"
937                         "ChannelState: %d\r\n"
938                         "ChannelStateDesc: %s\r\n"
939                         "CallerIDNum: %s\r\n"
940                         "CallerIDName: %s\r\n"
941                         "AccountCode: %s\r\n"
942                         "Exten: %s\r\n"
943                         "Context: %s\r\n"
944                         "Uniqueid: %s\r\n",
945                         tmp->name, 
946                         state, 
947                         ast_state2str(state),
948                         S_OR(cid_num, ""),
949                         S_OR(cid_name, ""),
950                         tmp->accountcode,
951                         S_OR(exten, ""),
952                         S_OR(context, ""),
953                         tmp->uniqueid);
954         }
955
956         return tmp;
957 }
958
959 /*! \brief Queue an outgoing media frame */
960 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head)
961 {
962         struct ast_frame *f;
963         struct ast_frame *cur;
964         int blah = 1;
965         int qlen = 0;
966
967         /* Build us a copy and free the original one */
968         if (!(f = ast_frdup(fin))) {
969                 return -1;
970         }
971
972         ast_channel_lock(chan);
973
974         /* See if the last frame on the queue is a hangup, if so don't queue anything */
975         if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
976                 ast_frfree(f);
977                 ast_channel_unlock(chan);
978                 return 0;
979         }
980
981         /* Count how many frames exist on the queue */
982         AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
983                 qlen++;
984         }
985
986         /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
987         if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen  > 128)) {
988                 if (fin->frametype != AST_FRAME_VOICE) {
989                         ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
990                         ast_assert(fin->frametype == AST_FRAME_VOICE);
991                 } else {
992                         ast_debug(1, "Dropping voice to exceptionally long queue on %s\n", chan->name);
993                         ast_frfree(f);
994                         ast_channel_unlock(chan);
995                         return 0;
996                 }
997         }
998
999         if (head) {
1000                 AST_LIST_INSERT_HEAD(&chan->readq, f, frame_list);
1001         } else {
1002                 AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
1003         }
1004
1005         if (chan->alertpipe[1] > -1) {
1006                 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah)) {
1007                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
1008                                 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
1009                 }
1010         } else if (chan->timingfd > -1) {
1011                 ast_timer_enable_continuous(chan->timingfd);
1012         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1013                 pthread_kill(chan->blocker, SIGURG);
1014         }
1015
1016         ast_channel_unlock(chan);
1017
1018         return 0;
1019 }
1020
1021 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1022 {
1023         return __ast_queue_frame(chan, fin, 0);
1024 }
1025
1026 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1027 {
1028         return __ast_queue_frame(chan, fin, 1);
1029 }
1030
1031 /*! \brief Queue a hangup frame for channel */
1032 int ast_queue_hangup(struct ast_channel *chan)
1033 {
1034         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
1035         /* Yeah, let's not change a lock-critical value without locking */
1036         if (!ast_channel_trylock(chan)) {
1037                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1038                 ast_channel_unlock(chan);
1039         }
1040         return ast_queue_frame(chan, &f);
1041 }
1042
1043 /*! \brief Queue a hangup frame for channel */
1044 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1045 {
1046         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
1047
1048         if (cause >= 0)
1049                 f.data.uint32 = cause;
1050
1051         /* Yeah, let's not change a lock-critical value without locking */
1052         if (!ast_channel_trylock(chan)) {
1053                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1054                 if (cause < 0)
1055                         f.data.uint32 = chan->hangupcause;
1056
1057                 ast_channel_unlock(chan);
1058         }
1059
1060         return ast_queue_frame(chan, &f);
1061 }
1062
1063 /*! \brief Queue a control frame */
1064 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1065 {
1066         struct ast_frame f = { AST_FRAME_CONTROL, };
1067
1068         f.subclass = control;
1069
1070         return ast_queue_frame(chan, &f);
1071 }
1072
1073 /*! \brief Queue a control frame with payload */
1074 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1075                            const void *data, size_t datalen)
1076 {
1077         struct ast_frame f = { AST_FRAME_CONTROL, };
1078
1079         f.subclass = control;
1080         f.data.ptr = (void *) data;
1081         f.datalen = datalen;
1082
1083         return ast_queue_frame(chan, &f);
1084 }
1085
1086 /*! \brief Set defer DTMF flag on channel */
1087 int ast_channel_defer_dtmf(struct ast_channel *chan)
1088 {
1089         int pre = 0;
1090
1091         if (chan) {
1092                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1093                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1094         }
1095         return pre;
1096 }
1097
1098 /*! \brief Unset defer DTMF flag on channel */
1099 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1100 {
1101         if (chan)
1102                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1103 }
1104
1105 /*!
1106  * \brief Helper function to find channels.
1107  *
1108  * It supports these modes:
1109  *
1110  * prev != NULL : get channel next in list after prev
1111  * name != NULL : get channel with matching name
1112  * name != NULL && namelen != 0 : get channel whose name starts with prefix
1113  * exten != NULL : get channel whose exten or macroexten matches
1114  * context != NULL && exten != NULL : get channel whose context or macrocontext
1115  *
1116  * It returns with the channel's lock held. If getting the individual lock fails,
1117  * unlock and retry quickly up to 10 times, then give up.
1118  *
1119  * \note XXX Note that this code has cost O(N) because of the need to verify
1120  * that the object is still on the global list.
1121  *
1122  * \note XXX also note that accessing fields (e.g. c->name in ast_log())
1123  * can only be done with the lock held or someone could delete the
1124  * object while we work on it. This causes some ugliness in the code.
1125  * Note that removing the first ast_log() may be harmful, as it would
1126  * shorten the retry period and possibly cause failures.
1127  * We should definitely go for a better scheme that is deadlock-free.
1128  */
1129 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
1130                                                const char *name, const int namelen,
1131                                                const char *context, const char *exten)
1132 {
1133         const char *msg = prev ? "deadlock" : "initial deadlock";
1134         int retries;
1135         struct ast_channel *c;
1136         const struct ast_channel *_prev = prev;
1137
1138         for (retries = 0; retries < 200; retries++) {
1139                 int done;
1140                 /* Reset prev on each retry.  See note below for the reason. */
1141                 prev = _prev;
1142                 AST_RWLIST_RDLOCK(&channels);
1143                 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
1144                         if (prev) {     /* look for last item, first, before any evaluation */
1145                                 if (c != prev)  /* not this one */
1146                                         continue;
1147                                 /* found, prepare to return c->next */
1148                                 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
1149                                 /*!\note
1150                                  * We're done searching through the list for the previous item.
1151                                  * Any item after this point, we want to evaluate for a match.
1152                                  * If we didn't set prev to NULL here, then we would only
1153                                  * return matches for the first matching item (since the above
1154                                  * "if (c != prev)" would not permit any other potential
1155                                  * matches to reach the additional matching logic, below).
1156                                  * Instead, it would just iterate until it once again found the
1157                                  * original match, then iterate down to the end of the list and
1158                                  * quit.
1159                                  */
1160                                 prev = NULL;
1161                         }
1162                         if (name) { /* want match by name */
1163                                 if ((!namelen && strcasecmp(c->name, name) && strcmp(c->uniqueid, name)) ||
1164                                     (namelen && strncasecmp(c->name, name, namelen)))
1165                                         continue;       /* name match failed */
1166                         } else if (exten) {
1167                                 if (context && strcasecmp(c->context, context) &&
1168                                     strcasecmp(c->macrocontext, context))
1169                                         continue;       /* context match failed */
1170                                 if (strcasecmp(c->exten, exten) &&
1171                                     strcasecmp(c->macroexten, exten))
1172                                         continue;       /* exten match failed */
1173                         }
1174                         /* if we get here, c points to the desired record */
1175                         break;
1176                 }
1177                 /* exit if chan not found or mutex acquired successfully */
1178                 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1179                 done = c == NULL || ast_channel_trylock(c) == 0;
1180                 if (!done) {
1181                         ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
1182                         if (retries == 199) {
1183                                 /* We are about to fail due to a deadlock, so report this
1184                                  * while we still have the list lock.
1185                                  */
1186                                 ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
1187                                 /* As we have deadlocked, we will skip this channel and
1188                                  * see if there is another match.
1189                                  * NOTE: No point doing this for a full-name match,
1190                                  * as there can be no more matches.
1191                                  */
1192                                 if (!(name && !namelen)) {
1193                                         prev = c;
1194                                         retries = -1;
1195                                 }
1196                         }
1197                 }
1198                 AST_RWLIST_UNLOCK(&channels);
1199                 if (done)
1200                         return c;
1201                 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1202                  * starting from the beginning of the list we can restore our saved pointer to the previous
1203                  * channel and start from there.
1204                  */
1205                 prev = _prev;
1206                 usleep(1);      /* give other threads a chance before retrying */
1207         }
1208
1209         return NULL;
1210 }
1211
1212 /*! \brief Browse channels in use */
1213 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1214 {
1215         return channel_find_locked(prev, NULL, 0, NULL, NULL);
1216 }
1217
1218 /*! \brief Get channel by name and lock it */
1219 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1220 {
1221         return channel_find_locked(NULL, name, 0, NULL, NULL);
1222 }
1223
1224 /*! \brief Get channel by name prefix and lock it */
1225 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1226 {
1227         return channel_find_locked(NULL, name, namelen, NULL, NULL);
1228 }
1229
1230 /*! \brief Get next channel by name prefix and lock it */
1231 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1232                                                            const int namelen)
1233 {
1234         return channel_find_locked(chan, name, namelen, NULL, NULL);
1235 }
1236
1237 /*! \brief Get channel by exten (and optionally context) and lock it */
1238 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1239 {
1240         return channel_find_locked(NULL, NULL, 0, context, exten);
1241 }
1242
1243 /*! \brief Get next channel by exten (and optionally context) and lock it */
1244 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1245                                                      const char *context)
1246 {
1247         return channel_find_locked(chan, NULL, 0, context, exten);
1248 }
1249
1250 /*! \brief Search for a channel based on the passed channel matching callback (first match) and return it, locked */
1251 struct ast_channel *ast_channel_search_locked(int (*is_match)(struct ast_channel *, void *), void *data)
1252 {
1253         struct ast_channel *c = NULL;
1254
1255         AST_RWLIST_RDLOCK(&channels);
1256         AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
1257                 ast_channel_lock(c);
1258                 if (is_match(c, data)) {
1259                         break;
1260                 }
1261                 ast_channel_unlock(c);
1262         }
1263         AST_RWLIST_UNLOCK(&channels);
1264
1265         return c;
1266 }
1267
1268 /*! \brief Wait, look for hangups and condition arg */
1269 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1270 {
1271         struct ast_frame *f;
1272
1273         while (ms > 0) {
1274                 if (cond && ((*cond)(data) == 0))
1275                         return 0;
1276                 ms = ast_waitfor(chan, ms);
1277                 if (ms < 0)
1278                         return -1;
1279                 if (ms > 0) {
1280                         f = ast_read(chan);
1281                         if (!f)
1282                                 return -1;
1283                         ast_frfree(f);
1284                 }
1285         }
1286         return 0;
1287 }
1288
1289 /*! \brief Wait, look for hangups */
1290 int ast_safe_sleep(struct ast_channel *chan, int ms)
1291 {
1292         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1293 }
1294
1295 static void free_cid(struct ast_callerid *cid)
1296 {
1297         if (cid->cid_dnid)
1298                 ast_free(cid->cid_dnid);
1299         if (cid->cid_num)
1300                 ast_free(cid->cid_num); 
1301         if (cid->cid_name)
1302                 ast_free(cid->cid_name);        
1303         if (cid->cid_ani)
1304                 ast_free(cid->cid_ani);
1305         if (cid->cid_rdnis)
1306                 ast_free(cid->cid_rdnis);
1307         cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1308 }
1309
1310 /*! \brief Free a channel structure */
1311 void ast_channel_free(struct ast_channel *chan)
1312 {
1313         int fd;
1314 #ifdef HAVE_EPOLL
1315         int i;
1316 #endif
1317         struct ast_var_t *vardata;
1318         struct ast_frame *f;
1319         struct varshead *headp;
1320         struct ast_datastore *datastore = NULL;
1321         char name[AST_CHANNEL_NAME], *dashptr;
1322         
1323         headp=&chan->varshead;
1324         
1325         AST_RWLIST_WRLOCK(&channels);
1326         if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1327                 AST_RWLIST_UNLOCK(&channels);
1328                 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1329         }
1330         /* Lock and unlock the channel just to be sure nobody has it locked still
1331            due to a reference retrieved from the channel list. */
1332         ast_channel_lock(chan);
1333         ast_channel_unlock(chan);
1334
1335         /* Get rid of each of the data stores on the channel */
1336         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1337                 /* Free the data store */
1338                 ast_datastore_free(datastore);
1339
1340         /* Lock and unlock the channel just to be sure nobody has it locked still
1341            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1342         ast_channel_lock(chan);
1343         ast_channel_unlock(chan);
1344
1345         if (chan->tech_pvt) {
1346                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1347                 ast_free(chan->tech_pvt);
1348         }
1349
1350         if (chan->sched)
1351                 sched_context_destroy(chan->sched);
1352
1353         ast_copy_string(name, chan->name, sizeof(name));
1354         if ((dashptr = strrchr(name, '-'))) {
1355                 *dashptr = '\0';
1356         }
1357
1358         /* Stop monitoring */
1359         if (chan->monitor)
1360                 chan->monitor->stop( chan, 0 );
1361
1362         /* If there is native format music-on-hold state, free it */
1363         if (chan->music_state)
1364                 ast_moh_cleanup(chan);
1365
1366         /* Free translators */
1367         if (chan->readtrans)
1368                 ast_translator_free_path(chan->readtrans);
1369         if (chan->writetrans)
1370                 ast_translator_free_path(chan->writetrans);
1371         if (chan->pbx)
1372                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1373         free_cid(&chan->cid);
1374         /* Close pipes if appropriate */
1375         if ((fd = chan->alertpipe[0]) > -1)
1376                 close(fd);
1377         if ((fd = chan->alertpipe[1]) > -1)
1378                 close(fd);
1379         if ((fd = chan->timingfd) > -1)
1380                 ast_timer_close(fd);
1381 #ifdef HAVE_EPOLL
1382         for (i = 0; i < AST_MAX_FDS; i++) {
1383                 if (chan->epfd_data[i])
1384                         free(chan->epfd_data[i]);
1385         }
1386         close(chan->epfd);
1387 #endif
1388         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1389                 ast_frfree(f);
1390         
1391         /* loop over the variables list, freeing all data and deleting list items */
1392         /* no need to lock the list, as the channel is already locked */
1393         
1394         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1395                 ast_var_delete(vardata);
1396
1397         ast_app_group_discard(chan);
1398
1399         /* Destroy the jitterbuffer */
1400         ast_jb_destroy(chan);
1401
1402         if (chan->cdr) {
1403                 ast_cdr_discard(chan->cdr);
1404                 chan->cdr = NULL;
1405         }
1406
1407         if (chan->zone) {
1408                 chan->zone = ast_tone_zone_unref(chan->zone);
1409         }
1410
1411         ast_mutex_destroy(&chan->lock_dont_use);
1412
1413         ast_string_field_free_memory(chan);
1414         ast_free(chan);
1415         AST_RWLIST_UNLOCK(&channels);
1416
1417         /* Queue an unknown state, because, while we know that this particular
1418          * instance is dead, we don't know the state of all other possible
1419          * instances. */
1420         ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, name);
1421 }
1422
1423 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1424 {
1425         return ast_datastore_alloc(info, uid);
1426 }
1427
1428 int ast_channel_datastore_free(struct ast_datastore *datastore)
1429 {
1430         return ast_datastore_free(datastore);
1431 }
1432
1433 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1434 {
1435         struct ast_datastore *datastore = NULL, *datastore2;
1436
1437         AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1438                 if (datastore->inheritance > 0) {
1439                         datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
1440                         if (datastore2) {
1441                                 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
1442                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1443                                 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1444                         }
1445                 }
1446         }
1447         return 0;
1448 }
1449
1450 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1451 {
1452         int res = 0;
1453
1454         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1455
1456         return res;
1457 }
1458
1459 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1460 {
1461         return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1462 }
1463
1464 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1465 {
1466         struct ast_datastore *datastore = NULL;
1467         
1468         if (info == NULL)
1469                 return NULL;
1470
1471         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1472                 if (datastore->info != info) {
1473                         continue;
1474                 }
1475
1476                 if (uid == NULL) {
1477                         /* matched by type only */
1478                         break;
1479                 }
1480
1481                 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
1482                         /* Matched by type AND uid */
1483                         break;
1484                 }
1485         }
1486         AST_LIST_TRAVERSE_SAFE_END;
1487
1488         return datastore;
1489 }
1490
1491 /*! Set the file descriptor on the channel */
1492 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
1493 {
1494 #ifdef HAVE_EPOLL
1495         struct epoll_event ev;
1496         struct ast_epoll_data *aed = NULL;
1497
1498         if (chan->fds[which] > -1) {
1499                 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
1500                 aed = chan->epfd_data[which];
1501         }
1502
1503         /* If this new fd is valid, add it to the epoll */
1504         if (fd > -1) {
1505                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
1506                         return;
1507                 
1508                 chan->epfd_data[which] = aed;
1509                 aed->chan = chan;
1510                 aed->which = which;
1511                 
1512                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1513                 ev.data.ptr = aed;
1514                 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
1515         } else if (aed) {
1516                 /* We don't have to keep around this epoll data structure now */
1517                 free(aed);
1518                 chan->epfd_data[which] = NULL;
1519         }
1520 #endif
1521         chan->fds[which] = fd;
1522         return;
1523 }
1524
1525 /*! Add a channel to an optimized waitfor */
1526 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
1527 {
1528 #ifdef HAVE_EPOLL
1529         struct epoll_event ev;
1530         int i = 0;
1531
1532         if (chan0->epfd == -1)
1533                 return;
1534
1535         /* Iterate through the file descriptors on chan1, adding them to chan0 */
1536         for (i = 0; i < AST_MAX_FDS; i++) {
1537                 if (chan1->fds[i] == -1)
1538                         continue;
1539                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1540                 ev.data.ptr = chan1->epfd_data[i];
1541                 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
1542         }
1543
1544 #endif
1545         return;
1546 }
1547
1548 /*! Delete a channel from an optimized waitfor */
1549 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
1550 {
1551 #ifdef HAVE_EPOLL
1552         struct epoll_event ev;
1553         int i = 0;
1554
1555         if (chan0->epfd == -1)
1556                 return;
1557
1558         for (i = 0; i < AST_MAX_FDS; i++) {
1559                 if (chan1->fds[i] == -1)
1560                         continue;
1561                 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
1562         }
1563
1564 #endif
1565         return;
1566 }
1567
1568 /*! \brief Softly hangup a channel, don't lock */
1569 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1570 {
1571         ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1572         /* Inform channel driver that we need to be hung up, if it cares */
1573         chan->_softhangup |= cause;
1574         ast_queue_frame(chan, &ast_null_frame);
1575         /* Interrupt any poll call or such */
1576         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1577                 pthread_kill(chan->blocker, SIGURG);
1578         return 0;
1579 }
1580
1581 /*! \brief Softly hangup a channel, lock */
1582 int ast_softhangup(struct ast_channel *chan, int cause)
1583 {
1584         int res;
1585
1586         ast_channel_lock(chan);
1587         res = ast_softhangup_nolock(chan, cause);
1588         ast_channel_unlock(chan);
1589
1590         return res;
1591 }
1592
1593 static void free_translation(struct ast_channel *clonechan)
1594 {
1595         if (clonechan->writetrans)
1596                 ast_translator_free_path(clonechan->writetrans);
1597         if (clonechan->readtrans)
1598                 ast_translator_free_path(clonechan->readtrans);
1599         clonechan->writetrans = NULL;
1600         clonechan->readtrans = NULL;
1601         clonechan->rawwriteformat = clonechan->nativeformats;
1602         clonechan->rawreadformat = clonechan->nativeformats;
1603 }
1604
1605 /*! \brief Hangup a channel */
1606 int ast_hangup(struct ast_channel *chan)
1607 {
1608         int res = 0;
1609
1610         /* Don't actually hang up a channel that will masquerade as someone else, or
1611            if someone is going to masquerade as us */
1612         ast_channel_lock(chan);
1613
1614         if (chan->audiohooks) {
1615                 ast_audiohook_detach_list(chan->audiohooks);
1616                 chan->audiohooks = NULL;
1617         }
1618
1619         ast_autoservice_stop(chan);
1620
1621         if (chan->masq) {
1622                 if (ast_do_masquerade(chan))
1623                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1624         }
1625
1626         if (chan->masq) {
1627                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1628                 ast_channel_unlock(chan);
1629                 return 0;
1630         }
1631         /* If this channel is one which will be masqueraded into something,
1632            mark it as a zombie already, so we know to free it later */
1633         if (chan->masqr) {
1634                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1635                 ast_channel_unlock(chan);
1636                 return 0;
1637         }
1638         free_translation(chan);
1639         /* Close audio stream */
1640         if (chan->stream) {
1641                 ast_closestream(chan->stream);
1642                 chan->stream = NULL;
1643         }
1644         /* Close video stream */
1645         if (chan->vstream) {
1646                 ast_closestream(chan->vstream);
1647                 chan->vstream = NULL;
1648         }
1649         if (chan->sched) {
1650                 sched_context_destroy(chan->sched);
1651                 chan->sched = NULL;
1652         }
1653         
1654         if (chan->generatordata)        /* Clear any tone stuff remaining */
1655                 if (chan->generator && chan->generator->release)
1656                         chan->generator->release(chan, chan->generatordata);
1657         chan->generatordata = NULL;
1658         chan->generator = NULL;
1659         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1660                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1661                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1662                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1663                 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
1664         }
1665         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1666                 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1667                 if (chan->tech->hangup)
1668                         res = chan->tech->hangup(chan);
1669         } else {
1670                 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1671         }
1672                         
1673         ast_channel_unlock(chan);
1674         manager_event(EVENT_FLAG_CALL, "Hangup",
1675                         "Channel: %s\r\n"
1676                         "Uniqueid: %s\r\n"
1677                         "CallerIDNum: %s\r\n"
1678                         "CallerIDName: %s\r\n"
1679                         "Cause: %d\r\n"
1680                         "Cause-txt: %s\r\n",
1681                         chan->name,
1682                         chan->uniqueid,
1683                         S_OR(chan->cid.cid_num, "<unknown>"),
1684                         S_OR(chan->cid.cid_name, "<unknown>"),
1685                         chan->hangupcause,
1686                         ast_cause2str(chan->hangupcause)
1687                         );
1688
1689         if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) && 
1690                 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) && 
1691             (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
1692                         
1693                 ast_cdr_end(chan->cdr);
1694                 ast_cdr_detach(chan->cdr);
1695                 chan->cdr = NULL;
1696         }
1697         
1698         ast_channel_free(chan);
1699
1700         return res;
1701 }
1702
1703 #define ANSWER_WAIT_MS 500
1704 int __ast_answer(struct ast_channel *chan, unsigned int delay,  int cdr_answer)
1705 {
1706         int res = 0;
1707
1708         ast_channel_lock(chan);
1709
1710         /* You can't answer an outbound call */
1711         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1712                 ast_channel_unlock(chan);
1713                 return 0;
1714         }
1715
1716         /* Stop if we're a zombie or need a soft hangup */
1717         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1718                 ast_channel_unlock(chan);
1719                 return -1;
1720         }
1721
1722         ast_channel_unlock(chan);
1723
1724         switch (chan->_state) {
1725         case AST_STATE_RINGING:
1726         case AST_STATE_RING:
1727                 ast_channel_lock(chan);
1728                 if (chan->tech->answer) {
1729                         res = chan->tech->answer(chan);
1730                 }
1731                 ast_setstate(chan, AST_STATE_UP);
1732                 if (cdr_answer) {
1733                         ast_cdr_answer(chan->cdr);
1734                 }
1735                 ast_channel_unlock(chan);
1736                 if (delay) {
1737                         ast_safe_sleep(chan, delay);
1738                 } else {
1739                         struct ast_frame *f;
1740                         int ms = ANSWER_WAIT_MS;
1741                         while (1) {
1742                                 /* 500 ms was the original delay here, so now
1743                                  * we cap our waiting at 500 ms
1744                                  */
1745                                 ms = ast_waitfor(chan, ms);
1746                                 if (ms < 0) {
1747                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
1748                                         res = -1;
1749                                         break;
1750                                 }
1751                                 if (ms == 0) {
1752                                         ast_debug(2, "Didn't receive a voice frame from %s within %d ms of answering. Continuing anyway\n", chan->name, ANSWER_WAIT_MS);
1753                                         res = 0;
1754                                         break;
1755                                 }
1756                                 f = ast_read(chan);
1757                                 if (!f || (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)) {
1758                                         res = -1;
1759                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
1760                                         break;
1761                                 }
1762                                 if (f->frametype == AST_FRAME_VOICE) {
1763                                         res = 0;
1764                                         break;
1765                                 }
1766                         }
1767                 }
1768                 break;
1769         case AST_STATE_UP:
1770                 /* Calling ast_cdr_answer when it it has previously been called
1771                  * is essentially a no-op, so it is safe.
1772                  */
1773                 if (cdr_answer) {
1774                         ast_cdr_answer(chan->cdr);
1775                 }
1776                 break;
1777         default:
1778                 break;
1779         }
1780
1781         ast_indicate(chan, -1);
1782         chan->visible_indication = 0;
1783
1784         return res;
1785 }
1786
1787 int ast_answer(struct ast_channel *chan)
1788 {
1789         return __ast_answer(chan, 0, 1);
1790 }
1791
1792 void ast_deactivate_generator(struct ast_channel *chan)
1793 {
1794         ast_channel_lock(chan);
1795         if (chan->generatordata) {
1796                 if (chan->generator && chan->generator->release)
1797                         chan->generator->release(chan, chan->generatordata);
1798                 chan->generatordata = NULL;
1799                 chan->generator = NULL;
1800                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
1801                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1802                 ast_settimeout(chan, 0, NULL, NULL);
1803         }
1804         ast_channel_unlock(chan);
1805 }
1806
1807 static int generator_force(const void *data)
1808 {
1809         /* Called if generator doesn't have data */
1810         void *tmp;
1811         int res;
1812         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1813         struct ast_channel *chan = (struct ast_channel *)data;
1814
1815         ast_channel_lock(chan);
1816         tmp = chan->generatordata;
1817         chan->generatordata = NULL;
1818         if (chan->generator)
1819                 generate = chan->generator->generate;
1820         ast_channel_unlock(chan);
1821
1822         if (!tmp || !generate)
1823                 return 0;
1824
1825         res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
1826
1827         chan->generatordata = tmp;
1828
1829         if (res) {
1830                 ast_debug(1, "Auto-deactivating generator\n");
1831                 ast_deactivate_generator(chan);
1832         }
1833
1834         return 0;
1835 }
1836
1837 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1838 {
1839         int res = 0;
1840
1841         ast_channel_lock(chan);
1842
1843         if (chan->generatordata) {
1844                 if (chan->generator && chan->generator->release)
1845                         chan->generator->release(chan, chan->generatordata);
1846                 chan->generatordata = NULL;
1847         }
1848
1849         ast_prod(chan);
1850         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1851                 res = -1;
1852         }
1853         
1854         if (!res) {
1855                 ast_settimeout(chan, 50, generator_force, chan);
1856                 chan->generator = gen;
1857         }
1858
1859         ast_channel_unlock(chan);
1860
1861         return res;
1862 }
1863
1864 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1865 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1866 {
1867         int winner = -1;
1868         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1869         return winner;
1870 }
1871
1872 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1873 #ifdef HAVE_EPOLL
1874 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
1875                                         int *exception, int *outfd, int *ms)
1876 #else
1877 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1878                                         int *exception, int *outfd, int *ms)
1879 #endif
1880 {
1881         struct timeval start = { 0 , 0 };
1882         struct pollfd *pfds = NULL;
1883         int res;
1884         long rms;
1885         int x, y, max;
1886         int sz;
1887         struct timeval now = { 0, 0 };
1888         struct timeval whentohangup = { 0, 0 }, diff;
1889         struct ast_channel *winner = NULL;
1890         struct fdmap {
1891                 int chan;
1892                 int fdno;
1893         } *fdmap = NULL;
1894
1895         if ((sz = n * AST_MAX_FDS + nfds)) {
1896                 pfds = alloca(sizeof(*pfds) * sz);
1897                 fdmap = alloca(sizeof(*fdmap) * sz);
1898         }
1899
1900         if (outfd)
1901                 *outfd = -99999;
1902         if (exception)
1903                 *exception = 0;
1904         
1905         /* Perform any pending masquerades */
1906         for (x = 0; x < n; x++) {
1907                 ast_channel_lock(c[x]);
1908                 if (c[x]->masq && ast_do_masquerade(c[x])) {
1909                         ast_log(LOG_WARNING, "Masquerade failed\n");
1910                         *ms = -1;
1911                         ast_channel_unlock(c[x]);
1912                         return NULL;
1913                 }
1914                 if (!ast_tvzero(c[x]->whentohangup)) {
1915                         if (ast_tvzero(whentohangup))
1916                                 now = ast_tvnow();
1917                         diff = ast_tvsub(c[x]->whentohangup, now);
1918                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
1919                                 /* Should already be hungup */
1920                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1921                                 ast_channel_unlock(c[x]);
1922                                 return c[x];
1923                         }
1924                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
1925                                 whentohangup = diff;
1926                 }
1927                 ast_channel_unlock(c[x]);
1928         }
1929         /* Wait full interval */
1930         rms = *ms;
1931         if (!ast_tvzero(whentohangup)) {
1932                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
1933                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1934                         rms =  *ms;
1935         }
1936         /*
1937          * Build the pollfd array, putting the channels' fds first,
1938          * followed by individual fds. Order is important because
1939          * individual fd's must have priority over channel fds.
1940          */
1941         max = 0;
1942         for (x = 0; x < n; x++) {
1943                 for (y = 0; y < AST_MAX_FDS; y++) {
1944                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1945                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1946                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1947                 }
1948                 CHECK_BLOCKING(c[x]);
1949         }
1950         /* Add the individual fds */
1951         for (x = 0; x < nfds; x++) {
1952                 fdmap[max].chan = -1;
1953                 max += ast_add_fd(&pfds[max], fds[x]);
1954         }
1955
1956         if (*ms > 0)
1957                 start = ast_tvnow();
1958         
1959         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1960                 do {
1961                         int kbrms = rms;
1962                         if (kbrms > 600000)
1963                                 kbrms = 600000;
1964                         res = poll(pfds, max, kbrms);
1965                         if (!res)
1966                                 rms -= kbrms;
1967                 } while (!res && (rms > 0));
1968         } else {
1969                 res = poll(pfds, max, rms);
1970         }
1971         for (x = 0; x < n; x++)
1972                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1973         if (res < 0) { /* Simulate a timeout if we were interrupted */
1974                 if (errno != EINTR)
1975                         *ms = -1;
1976                 return NULL;
1977         }
1978         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
1979                 now = ast_tvnow();
1980                 for (x = 0; x < n; x++) {
1981                         if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
1982                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1983                                 if (winner == NULL)
1984                                         winner = c[x];
1985                         }
1986                 }
1987         }
1988         if (res == 0) { /* no fd ready, reset timeout and done */
1989                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1990                 return winner;
1991         }
1992         /*
1993          * Then check if any channel or fd has a pending event.
1994          * Remember to check channels first and fds last, as they
1995          * must have priority on setting 'winner'
1996          */
1997         for (x = 0; x < max; x++) {
1998                 res = pfds[x].revents;
1999                 if (res == 0)
2000                         continue;
2001                 if (fdmap[x].chan >= 0) {       /* this is a channel */
2002                         winner = c[fdmap[x].chan];      /* override previous winners */
2003                         if (res & POLLPRI)
2004                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2005                         else
2006                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2007                         winner->fdno = fdmap[x].fdno;
2008                 } else {                        /* this is an fd */
2009                         if (outfd)
2010                                 *outfd = pfds[x].fd;
2011                         if (exception)
2012                                 *exception = (res & POLLPRI) ? -1 : 0;
2013                         winner = NULL;
2014                 }
2015         }
2016         if (*ms > 0) {
2017                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2018                 if (*ms < 0)
2019                         *ms = 0;
2020         }
2021         return winner;
2022 }
2023
2024 #ifdef HAVE_EPOLL
2025 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
2026 {
2027         struct timeval start = { 0 , 0 };
2028         int res = 0;
2029         struct epoll_event ev[1];
2030         long diff, rms = *ms;
2031         struct ast_channel *winner = NULL;
2032         struct ast_epoll_data *aed = NULL;
2033
2034         ast_channel_lock(chan);
2035
2036         /* See if this channel needs to be masqueraded */
2037         if (chan->masq && ast_do_masquerade(chan)) {
2038                 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
2039                 *ms = -1;
2040                 ast_channel_unlock(chan);
2041                 return NULL;
2042         }
2043
2044         /* Figure out their timeout */
2045         if (!ast_tvzero(chan->whentohangup)) {
2046                 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
2047                         /* They should already be hungup! */
2048                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2049                         ast_channel_unlock(chan);
2050                         return NULL;
2051                 }
2052                 /* If this value is smaller then the current one... make it priority */
2053                 if (rms > diff)
2054                         rms = diff;
2055         }
2056
2057         ast_channel_unlock(chan);
2058
2059         /* Time to make this channel block... */
2060         CHECK_BLOCKING(chan);
2061
2062         if (*ms > 0)
2063                 start = ast_tvnow();
2064
2065         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
2066         res = epoll_wait(chan->epfd, ev, 1, rms);
2067
2068         /* Stop blocking */
2069         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2070
2071         /* Simulate a timeout if we were interrupted */
2072         if (res < 0) {
2073                 if (errno != EINTR)
2074                         *ms = -1;
2075                 return NULL;
2076         }
2077
2078         /* If this channel has a timeout see if it expired */
2079         if (!ast_tvzero(chan->whentohangup)) {
2080                 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
2081                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2082                         winner = chan;
2083                 }
2084         }
2085
2086         /* No fd ready, reset timeout and be done for now */
2087         if (!res) {
2088                 *ms = 0;
2089                 return winner;
2090         }
2091
2092         /* See what events are pending */
2093         aed = ev[0].data.ptr;
2094         chan->fdno = aed->which;
2095         if (ev[0].events & EPOLLPRI)
2096                 ast_set_flag(chan, AST_FLAG_EXCEPTION);
2097         else
2098                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2099
2100         if (*ms > 0) {
2101                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2102                 if (*ms < 0)
2103                         *ms = 0;
2104         }
2105
2106         return chan;
2107 }
2108
2109 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2110 {
2111         struct timeval start = { 0 , 0 };
2112         int res = 0, i;
2113         struct epoll_event ev[25] = { { 0, } };
2114         struct timeval now = { 0, 0 };
2115         long whentohangup = 0, diff = 0, rms = *ms;
2116         struct ast_channel *winner = NULL;
2117
2118         for (i = 0; i < n; i++) {
2119                 ast_channel_lock(c[i]);
2120                 if (c[i]->masq && ast_do_masquerade(c[i])) {
2121                         ast_log(LOG_WARNING, "Masquerade failed\n");
2122                         *ms = -1;
2123                         ast_channel_unlock(c[i]);
2124                         return NULL;
2125                 }
2126                 if (!ast_tvzero(c[i]->whentohangup)) {
2127                         if (whentohangup == 0)
2128                                 now = ast_tvnow();
2129                         if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
2130                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2131                                 ast_channel_unlock(c[i]);
2132                                 return c[i];
2133                         }
2134                         if (!whentohangup || whentohangup > diff)
2135                                 whentohangup = diff;
2136                 }
2137                 ast_channel_unlock(c[i]);
2138                 CHECK_BLOCKING(c[i]);
2139         }
2140
2141         rms = *ms;
2142         if (whentohangup) {
2143                 rms = whentohangup;
2144                 if (*ms >= 0 && *ms < rms)
2145                         rms = *ms;
2146         }
2147
2148         if (*ms > 0)
2149                 start = ast_tvnow();
2150
2151         res = epoll_wait(c[0]->epfd, ev, 25, rms);
2152
2153         for (i = 0; i < n; i++)
2154                 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2155
2156         if (res < 0) {
2157                 if (errno != EINTR)
2158                         *ms = -1;
2159                 return NULL;
2160         }
2161
2162         if (whentohangup) {
2163                 now = ast_tvnow();
2164                 for (i = 0; i < n; i++) {
2165                         if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
2166                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2167                                 if (!winner)
2168                                         winner = c[i];
2169                         }
2170                 }
2171         }
2172
2173         if (!res) {
2174                 *ms = 0;
2175                 return winner;
2176         }
2177
2178         for (i = 0; i < res; i++) {
2179                 struct ast_epoll_data *aed = ev[i].data.ptr;
2180
2181                 if (!ev[i].events || !aed)
2182                         continue;
2183
2184                 winner = aed->chan;
2185                 if (ev[i].events & EPOLLPRI)
2186                         ast_set_flag(winner, AST_FLAG_EXCEPTION);
2187                 else
2188                         ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2189                 winner->fdno = aed->which;
2190         }
2191
2192         if (*ms > 0) {
2193                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2194                 if (*ms < 0)
2195                         *ms = 0;
2196         }
2197
2198         return winner;
2199 }
2200
2201 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2202                                         int *exception, int *outfd, int *ms)
2203 {
2204         /* Clear all provided values in one place. */
2205         if (outfd)
2206                 *outfd = -99999;
2207         if (exception)
2208                 *exception = 0;
2209
2210         /* If no epoll file descriptor is available resort to classic nandfds */
2211         if (!n || nfds || c[0]->epfd == -1)
2212                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2213         else if (!nfds && n == 1)
2214                 return ast_waitfor_nandfds_simple(c[0], ms);
2215         else
2216                 return ast_waitfor_nandfds_complex(c, n, ms);
2217 }
2218 #endif
2219
2220 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2221 {
2222         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2223 }
2224
2225 int ast_waitfor(struct ast_channel *c, int ms)
2226 {
2227         int oldms = ms; /* -1 if no timeout */
2228
2229         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2230         if ((ms < 0) && (oldms < 0))
2231                 ms = 0;
2232         return ms;
2233 }
2234
2235 /* XXX never to be called with ms = -1 */
2236 int ast_waitfordigit(struct ast_channel *c, int ms)
2237 {
2238         return ast_waitfordigit_full(c, ms, -1, -1);
2239 }
2240
2241 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
2242 {
2243         int res;
2244         unsigned int real_rate = rate, max_rate;
2245
2246         ast_channel_lock(c);
2247
2248         if (c->timingfd == -1) {
2249                 ast_channel_unlock(c);
2250                 return -1;
2251         }
2252
2253         if (!func) {
2254                 rate = 0;
2255                 data = NULL;
2256         }
2257
2258         if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timingfd))) {
2259                 real_rate = max_rate;
2260         }
2261
2262         ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
2263
2264         res = ast_timer_set_rate(c->timingfd, real_rate);
2265
2266         c->timingfunc = func;
2267         c->timingdata = data;
2268
2269         ast_channel_unlock(c);
2270
2271         return res;
2272 }
2273
2274 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2275 {
2276         /* Stop if we're a zombie or need a soft hangup */
2277         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2278                 return -1;
2279
2280         /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2281         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2282
2283         /* Wait for a digit, no more than ms milliseconds total. */
2284         
2285         while (ms) {
2286                 struct ast_channel *rchan;
2287                 int outfd=-1;
2288
2289                 errno = 0;
2290                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2291                 
2292                 if (!rchan && outfd < 0 && ms) {
2293                         if (errno == 0 || errno == EINTR)
2294                                 continue;
2295                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2296                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2297                         return -1;
2298                 } else if (outfd > -1) {
2299                         /* The FD we were watching has something waiting */
2300                         ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2301                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2302                         return 1;
2303                 } else if (rchan) {
2304                         int res;
2305                         struct ast_frame *f = ast_read(c);
2306                         if (!f)
2307                                 return -1;
2308
2309                         switch (f->frametype) {
2310                         case AST_FRAME_DTMF_BEGIN:
2311                                 break;
2312                         case AST_FRAME_DTMF_END:
2313                                 res = f->subclass;
2314                                 ast_frfree(f);
2315                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2316                                 return res;
2317                         case AST_FRAME_CONTROL:
2318                                 switch (f->subclass) {
2319                                 case AST_CONTROL_HANGUP:
2320                                         ast_frfree(f);
2321                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2322                                         return -1;
2323                                 case AST_CONTROL_RINGING:
2324                                 case AST_CONTROL_ANSWER:
2325                                 case AST_CONTROL_SRCUPDATE:
2326                                         /* Unimportant */
2327                                         break;
2328                                 default:
2329                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2330                                         break;
2331                                 }
2332                                 break;
2333                         case AST_FRAME_VOICE:
2334                                 /* Write audio if appropriate */
2335                                 if (audiofd > -1) {
2336                                         if (write(audiofd, f->data.ptr, f->datalen) < 0) {
2337                                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
2338                                         }
2339                                 }
2340                         default:
2341                                 /* Ignore */
2342                                 break;
2343                         }
2344                         ast_frfree(f);
2345                 }
2346         }
2347
2348         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2349
2350         return 0; /* Time is up */
2351 }
2352
2353 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2354 {
2355         manager_event(EVENT_FLAG_DTMF,
2356                         "DTMF",
2357                         "Channel: %s\r\n"
2358                         "Uniqueid: %s\r\n"
2359                         "Digit: %c\r\n"
2360                         "Direction: %s\r\n"
2361                         "Begin: %s\r\n"
2362                         "End: %s\r\n",
2363                         chan->name, chan->uniqueid, digit, direction, begin, end);
2364 }
2365
2366 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2367 {
2368         if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2369                 void *tmp = chan->generatordata;
2370                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2371                 int res;
2372                 int samples;
2373
2374                 if (chan->timingfunc) {
2375                         ast_debug(1, "Generator got voice, switching to phase locked mode\n");
2376                         ast_settimeout(chan, 0, NULL, NULL);
2377                 }
2378
2379                 chan->generatordata = NULL;     /* reset, to let writes go through */
2380
2381                 if (f->subclass != chan->writeformat) {
2382                         float factor;
2383                         factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass));
2384                         samples = (int) ( ((float) f->samples) * factor );
2385                 } else {
2386                         samples = f->samples;
2387                 }
2388                 
2389                 if (chan->generator->generate) {
2390                         generate = chan->generator->generate;
2391                 }
2392                 /* This unlock is here based on two assumptions that hold true at this point in the
2393                  * code. 1) this function is only called from within __ast_read() and 2) all generators
2394                  * call ast_write() in their generate callback.
2395                  *
2396                  * The reason this is added is so that when ast_write is called, the lock that occurs 
2397                  * there will not recursively lock the channel. Doing this will cause intended deadlock 
2398                  * avoidance not to work in deeper functions
2399                  */
2400                 ast_channel_unlock(chan);
2401                 res = generate(chan, tmp, f->datalen, samples);
2402                 ast_channel_lock(chan);
2403                 chan->generatordata = tmp;
2404                 if (res) {
2405                         ast_debug(1, "Auto-deactivating generator\n");
2406                         ast_deactivate_generator(chan);
2407                 }
2408
2409         } else if (f->frametype == AST_FRAME_CNG) {
2410                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2411                         ast_debug(1, "Generator got CNG, switching to timed mode\n");
2412                         ast_settimeout(chan, 50, generator_force, chan);
2413                 }
2414         }
2415 }
2416
2417 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
2418 {
2419         struct ast_frame *fr = &chan->dtmff;
2420
2421         fr->frametype = AST_FRAME_DTMF_END;
2422         fr->subclass = f->subclass;
2423         fr->len = f->len;
2424
2425         /* The only time this function will be called is for a frame that just came
2426          * out of the channel driver.  So, we want to stick it on the tail of the
2427          * readq. */
2428
2429         ast_queue_frame(chan, fr);
2430 }
2431
2432 /*!
2433  * \brief Determine whether or not we should ignore DTMF in the readq
2434  */
2435 static inline int should_skip_dtmf(struct ast_channel *chan)
2436 {
2437         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
2438                 /* We're in the middle of emulating a digit, or DTMF has been
2439                  * explicitly deferred.  Skip this digit, then. */
2440                 return 1;
2441         }
2442                         
2443         if (!ast_tvzero(chan->dtmf_tv) && 
2444                         ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2445                 /* We're not in the middle of a digit, but it hasn't been long enough
2446                  * since the last digit, so we'll have to skip DTMF for now. */
2447                 return 1;
2448         }
2449
2450         return 0;
2451 }
2452
2453 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2454 {
2455         struct ast_frame *f = NULL;     /* the return value */
2456         int blah;
2457         int prestate;
2458         int count = 0, cause = 0;
2459
2460         /* this function is very long so make sure there is only one return
2461          * point at the end (there are only two exceptions to this).
2462          */
2463         while(ast_channel_trylock(chan)) {
2464                 if(count++ > 10) 
2465                         /*cannot goto done since the channel is not locked*/
2466                         return &ast_null_frame;
2467                 usleep(1);
2468         }
2469
2470         if (chan->masq) {
2471                 if (ast_do_masquerade(chan))
2472                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2473                 else
2474                         f =  &ast_null_frame;
2475                 goto done;
2476         }
2477
2478         /* Stop if we're a zombie or need a soft hangup */
2479         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2480                 if (chan->generator)
2481                         ast_deactivate_generator(chan);
2482                 goto done;
2483         }
2484         prestate = chan->_state;
2485
2486         /* Read and ignore anything on the alertpipe, but read only
2487            one sizeof(blah) per frame that we send from it */
2488         if (chan->alertpipe[0] > -1) {
2489                 int flags = fcntl(chan->alertpipe[0], F_GETFL);
2490                 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
2491                  * which immediately causes a deadlock scenario.  Detect and prevent this. */
2492                 if ((flags & O_NONBLOCK) == 0) {
2493                         ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
2494                         if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2495                                 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
2496                                 f = &ast_null_frame;
2497                                 goto done;
2498                         }
2499                 }
2500                 if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
2501                         if (errno != EINTR && errno != EAGAIN)
2502                                 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
2503                 }
2504         }
2505
2506         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
2507                 enum ast_timer_event res;
2508
2509                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2510
2511                 res = ast_timer_get_event(chan->timingfd);
2512
2513                 switch (res) {
2514                 case AST_TIMING_EVENT_EXPIRED:
2515                         ast_timer_ack(chan->timingfd, 1);
2516
2517                         if (chan->timingfunc) {
2518                                 /* save a copy of func/data before unlocking the channel */
2519                                 int (*func)(const void *) = chan->timingfunc;
2520                                 void *data = chan->timingdata;
2521                                 ast_channel_unlock(chan);
2522                                 func(data);
2523                         } else {
2524                                 ast_timer_set_rate(chan->timingfd, 0);
2525                                 ast_channel_unlock(chan);
2526                         }
2527
2528                         /* cannot 'goto done' because the channel is already unlocked */
2529                         return &ast_null_frame;
2530
2531                 case AST_TIMING_EVENT_CONTINUOUS:
2532                         if (AST_LIST_EMPTY(&chan->readq) || 
2533                                 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2534                                 ast_timer_disable_continuous(chan->timingfd);
2535                         }
2536                         break;
2537                 }
2538
2539         } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2540                 /* if the AST_GENERATOR_FD is set, call the generator with args
2541                  * set to -1 so it can do whatever it needs to.
2542                  */
2543                 void *tmp = chan->generatordata;
2544                 chan->generatordata = NULL;     /* reset to let ast_write get through */
2545                 chan->generator->generate(chan, tmp, -1, -1);
2546                 chan->generatordata = tmp;
2547                 f = &ast_null_frame;
2548                 goto done;
2549         }
2550
2551         /* Check for pending read queue */
2552         if (!AST_LIST_EMPTY(&chan->readq)) {
2553                 int skip_dtmf = should_skip_dtmf(chan);
2554
2555                 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
2556                         /* We have to be picky about which frame we pull off of the readq because
2557                          * there are cases where we want to leave DTMF frames on the queue until
2558                          * some later time. */
2559
2560                         if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
2561                                 continue;
2562                         }
2563
2564                         AST_LIST_REMOVE_CURRENT(frame_list);
2565                         break;
2566                 }
2567                 AST_LIST_TRAVERSE_SAFE_END
2568                 
2569                 if (!f) {
2570                         /* There were no acceptable frames on the readq. */
2571                         f = &ast_null_frame;
2572                         if (chan->alertpipe[0] > -1) {
2573                                 int poke = 0;
2574                                 /* Restore the state of the alertpipe since we aren't ready for any
2575                                  * of the frames in the readq. */
2576                                 if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
2577                                         ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
2578                                 }
2579                         }
2580                 }
2581
2582                 /* Interpret hangup and return NULL */
2583                 /* XXX why not the same for frames from the channel ? */
2584                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2585                         cause = f->data.uint32;
2586                         ast_frfree(f);
2587                         f = NULL;
2588                 }
2589         } else {
2590                 chan->blocker = pthread_self();
2591                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2592                         if (chan->tech->exception)
2593                                 f = chan->tech->exception(chan);
2594                         else {
2595                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2596                                 f = &ast_null_frame;
2597                         }
2598                         /* Clear the exception flag */
2599                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2600                 } else if (chan->tech->read)
2601                         f = chan->tech->read(chan);
2602                 else
2603                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2604         }
2605
2606         if (f) {
2607                 /* if the channel driver returned more than one frame, stuff the excess
2608                    into the readq for the next ast_read call (note that we can safely assume
2609                    that the readq is empty, because otherwise we would not have called into
2610                    the channel driver and f would be only a single frame)
2611                 */
2612                 if (AST_LIST_NEXT(f, frame_list)) {
2613                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2614                         AST_LIST_NEXT(f, frame_list) = NULL;
2615                 }
2616
2617                 switch (f->frametype) {
2618                 case AST_FRAME_CONTROL:
2619                         if (f->subclass == AST_CONTROL_ANSWER) {
2620                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2621                                         ast_debug(1, "Ignoring answer on an inbound call!\n");
2622                                         ast_frfree(f);
2623                                         f = &ast_null_frame;
2624                                 } else if (prestate == AST_STATE_UP) {
2625                                         ast_debug(1, "Dropping duplicate answer!\n");
2626                                         ast_frfree(f);
2627                                         f = &ast_null_frame;
2628                                 } else {
2629                                         /* Answer the CDR */
2630                                         ast_setstate(chan, AST_STATE_UP);
2631                                         /* removed a call to ast_cdr_answer(chan->cdr) from here. */
2632                                 }
2633                         }
2634                         break;
2635                 case AST_FRAME_DTMF_END:
2636                         send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2637                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2638                         /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
2639                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2640                                 queue_dtmf_readq(chan, f);
2641                                 ast_frfree(f);
2642                                 f = &ast_null_frame;
2643                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2644                                 if (!ast_tvzero(chan->dtmf_tv) && 
2645                                     ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2646                                         /* If it hasn't been long enough, defer this digit */
2647                                         queue_dtmf_readq(chan, f);
2648                                         ast_frfree(f);
2649                                         f = &ast_null_frame;
2650                                 } else {
2651                                         /* There was no begin, turn this into a begin and send the end later */
2652                                         f->frametype = AST_FRAME_DTMF_BEGIN;
2653                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2654                                         chan->emulate_dtmf_digit = f->subclass;
2655                                         chan->dtmf_tv = ast_tvnow();
2656                                         if (f->len) {
2657                                                 if (f->len > AST_MIN_DTMF_DURATION)
2658                                                         chan->emulate_dtmf_duration = f->len;
2659                                                 else 
2660                                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2661                                         } else
2662                                                 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2663                                         ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2664                                 }
2665                                 if (chan->audiohooks) {
2666                                         struct ast_frame *old_frame = f;
2667                                         /*!
2668                                          * \todo XXX It is possible to write a digit to the audiohook twice
2669                                          * if the digit was originally read while the channel was in autoservice. */
2670                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2671                                         if (old_frame != f)
2672                                                 ast_frfree(old_frame);
2673                                 }
2674                         } else {
2675                                 struct timeval now = ast_tvnow();
2676                                 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2677                                         ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2678                                         ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2679                                         if (!f->len)
2680                                                 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2681                                 } else if (!f->len) {
2682                                         ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2683                                         f->len = AST_MIN_DTMF_DURATION;
2684                                 }
2685                                 if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2686                                         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);
2687                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2688                                         chan->emulate_dtmf_digit = f->subclass;
2689                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2690                                         ast_frfree(f);
2691                                         f = &ast_null_frame;
2692                                 } else {
2693                                         ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2694                                         if (f->len < AST_MIN_DTMF_DURATION) {
2695                                                 f->len = AST_MIN_DTMF_DURATION;
2696                                         }
2697                                         chan->dtmf_tv = now;
2698                                 }
2699                                 if (chan->audiohooks) {
2700                                         struct ast_frame *old_frame = f;
2701                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2702                                         if (old_frame != f)
2703                                                 ast_frfree(old_frame);
2704                                 }
2705                         }
2706                         break;
2707                 case AST_FRAME_DTMF_BEGIN:
2708                         send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2709                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2710                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) || 
2711                             (!ast_tvzero(chan->dtmf_tv) && 
2712                               ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2713                                 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2714                                 ast_frfree(f);
2715                                 f = &ast_null_frame;
2716                         } else {
2717                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2718                                 chan->dtmf_tv = ast_tvnow();
2719                                 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2720                         }
2721                         break;
2722                 case AST_FRAME_NULL:
2723                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2724                          * is reached , because we want to make sure we pass at least one
2725                          * voice frame through before starting the next digit, to ensure a gap
2726                          * between DTMF digits. */
2727                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2728                                 struct timeval now = ast_tvnow();
2729                                 if (!chan->emulate_dtmf_duration) {
2730                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2731                                         chan->emulate_dtmf_digit = 0;
2732                                 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2733                                         chan->emulate_dtmf_duration = 0;
2734                                         ast_frfree(f);
2735                                         f = &chan->dtmff;
2736                                         f->frametype = AST_FRAME_DTMF_END;
2737                                         f->subclass = chan->emulate_dtmf_digit;
2738                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2739                                         chan->dtmf_tv = now;
2740                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2741                                         chan->emulate_dtmf_digit = 0;
2742                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2743                                 }
2744                         }
2745                         break;
2746                 case AST_FRAME_VOICE:
2747                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2748                          * is reached , because we want to make sure we pass at least one
2749                          * voice frame through before starting the next digit, to ensure a gap
2750                          * between DTMF digits. */
2751                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2752                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2753                                 chan->emulate_dtmf_digit = 0;
2754                         }
2755
2756                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2757                                 if (dropaudio)
2758                                         ast_read_generator_actions(chan, f);
2759                                 ast_frfree(f);
2760                                 f = &ast_null_frame;
2761                         }
2762
2763                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2764                                 struct timeval now = ast_tvnow();
2765                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2766                                         chan->emulate_dtmf_duration = 0;
2767                                         ast_frfree(f);
2768                                         f = &chan->dtmff;
2769                                         f->frametype = AST_FRAME_DTMF_END;
2770                                         f->subclass = chan->emulate_dtmf_digit;
2771                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2772                                         chan->dtmf_tv = now;
2773                                         if (chan->audiohooks) {
2774                                                 struct ast_frame *old_frame = f;
2775                                                 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2776                                                 if (old_frame != f)
2777                                                         ast_frfree(old_frame);
2778                                         }
2779                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2780                                 } else {
2781                                         /* Drop voice frames while we're still in the middle of the digit */
2782                                         ast_frfree(f);
2783                                         f = &ast_null_frame;
2784                                 }
2785                         } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2786                                 /* This frame is not one of the current native formats -- drop it on the floor */
2787                                 char to[200];
2788                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2789                                         chan->name, ast_getformatname(f->subclass), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
2790                                 ast_frfree(f);
2791                                 f = &ast_null_frame;
2792                         } else if ((f->frametype == AST_FRAME_VOICE)) {
2793                                 /* Send frame to audiohooks if present */
2794                                 if (chan->audiohooks) {
2795                                         struct ast_frame *old_frame = f;
2796                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2797                                         if (old_frame != f)
2798                                                 ast_frfree(old_frame);
2799                                 }
2800                                 if (chan->monitor && chan->monitor->read_stream ) {
2801                                         /* XXX what does this do ? */
2802 #ifndef MONITOR_CONSTANT_DELAY
2803                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2804                                         if (jump >= 0) {
2805                                                 jump = chan->outsmpl - chan->insmpl;
2806                                                 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2807                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2808                                                 chan->insmpl += jump + f->samples;
2809                                         } else
2810                                                 chan->insmpl+= f->samples;
2811 #else
2812                                         int jump = chan->outsmpl - chan->insmpl;
2813                                         if (jump - MONITOR_DELAY >= 0) {
2814                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2815                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2816                                                 chan->insmpl += jump;
2817                                         } else
2818                                                 chan->insmpl += f->samples;
2819 #endif
2820                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2821                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2822                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2823                                         }
2824                                 }
2825
2826                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2827                                         f = &ast_null_frame;
2828                                 else
2829                                         /* Run generator sitting on the line if timing device not available
2830                                          * and synchronous generation of outgoing frames is necessary       */
2831                                         ast_read_generator_actions(chan, f);
2832                         }
2833                 default:
2834                         /* Just pass it on! */
2835                         break;
2836                 }
2837         } else {
2838                 /* Make sure we always return NULL in the future */
2839                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2840                 if (cause)
2841                         chan->hangupcause = cause;
2842                 if (chan->generator)
2843                         ast_deactivate_generator(chan);
2844                 /* We no longer End the CDR here */
2845         }
2846
2847         /* High bit prints debugging */
2848         if (chan->fin & DEBUGCHAN_FLAG)
2849                 ast_frame_dump(chan->name, f, "<<");
2850         chan->fin = FRAMECOUNT_INC(chan->fin);
2851
2852 done:
2853         if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2854                 chan->generator->digit(chan, f->subclass);
2855
2856         ast_channel_unlock(chan);
2857         return f;
2858 }
2859
2860 int ast_internal_timing_enabled(struct ast_channel *chan)
2861 {
2862         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2863         ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2864         return ret;
2865 }
2866
2867 struct ast_frame *ast_read(struct ast_channel *chan)
2868 {
2869         return __ast_read(chan, 0);
2870 }
2871
2872 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2873 {
2874         return __ast_read(chan, 1);
2875 }
2876
2877 int ast_indicate(struct ast_channel *chan, int condition)
2878 {
2879         return ast_indicate_data(chan, condition, NULL, 0);
2880 }
2881
2882 static int attribute_const is_visible_indication(enum ast_control_frame_type condition)
2883 {
2884         /* Don't include a default case here so that we get compiler warnings
2885          * when a new type is added. */
2886
2887         switch (condition) {
2888         case AST_CONTROL_PROGRESS:
2889         case AST_CONTROL_PROCEEDING:
2890         case AST_CONTROL_VIDUPDATE:
2891         case AST_CONTROL_SRCUPDATE:
2892         case AST_CONTROL_RADIO_KEY:
2893         case AST_CONTROL_RADIO_UNKEY:
2894         case AST_CONTROL_OPTION:
2895         case AST_CONTROL_WINK:
2896         case AST_CONTROL_FLASH:
2897         case AST_CONTROL_OFFHOOK:
2898         case AST_CONTROL_TAKEOFFHOOK:
2899         case AST_CONTROL_ANSWER:
2900         case AST_CONTROL_HANGUP:
2901         case AST_CONTROL_T38:
2902                 return 0;
2903
2904         case AST_CONTROL_CONGESTION:
2905         case AST_CONTROL_BUSY:
2906         case AST_CONTROL_RINGING:
2907         case AST_CONTROL_RING:
2908         case AST_CONTROL_HOLD:
2909         case AST_CONTROL_UNHOLD:
2910                 return 1;
2911         }
2912
2913         return 0;
2914 }
2915
2916 int ast_indicate_data(struct ast_channel *chan, int _condition,
2917                 const void *data, size_t datalen)
2918 {
2919         /* By using an enum, we'll get compiler warnings for values not handled 
2920          * in switch statements. */
2921         enum ast_control_frame_type condition = _condition;
2922         struct ast_tone_zone_sound *ts = NULL;
2923         int res = -1;
2924
2925         ast_channel_lock(chan);
2926
2927         /* Don't bother if the channel is about to go away, anyway. */
2928         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2929                 ast_channel_unlock(chan);
2930                 return -1;
2931         }
2932
2933         if (chan->tech->indicate) {
2934                 /* See if the channel driver can handle this condition. */
2935                 res = chan->tech->indicate(chan, condition, data, datalen);
2936         }
2937
2938         ast_channel_unlock(chan);
2939
2940         if (chan->tech->indicate && !res) {
2941                 /* The channel driver successfully handled this indication */
2942                 if (is_visible_indication(condition)) {
2943                         chan->visible_indication = condition;
2944                 }
2945                 return 0;
2946         }
2947
2948         /* The channel driver does not support this indication, let's fake
2949          * it by doing our own tone generation if applicable. */
2950
2951         /*!\note If we compare the enumeration type, which does not have any
2952          * negative constants, the compiler may optimize this code away.
2953          * Therefore, we must perform an integer comparison here. */
2954         if (_condition < 0) {
2955                 /* Stop any tones that are playing */
2956                 ast_playtones_stop(chan);
2957                 return 0;
2958         }
2959
2960         /* Handle conditions that we have tones for. */
2961         switch (condition) {
2962         case AST_CONTROL_RINGING:
2963                 ts = ast_get_indication_tone(chan->zone, "ring");
2964                 break;
2965         case AST_CONTROL_BUSY:
2966                 ts = ast_get_indication_tone(chan->zone, "busy");
2967                 break;
2968         case AST_CONTROL_CONGESTION:
2969                 ts = ast_get_indication_tone(chan->zone, "congestion");
2970                 break;
2971         case AST_CONTROL_PROGRESS:
2972         case AST_CONTROL_PROCEEDING:
2973         case AST_CONTROL_VIDUPDATE:
2974         case AST_CONTROL_SRCUPDATE:
2975         case AST_CONTROL_RADIO_KEY:
2976         case AST_CONTROL_RADIO_UNKEY:
2977         case AST_CONTROL_OPTION:
2978         case AST_CONTROL_WINK:
2979         case AST_CONTROL_FLASH:
2980         case AST_CONTROL_OFFHOOK:
2981         case AST_CONTROL_TAKEOFFHOOK:
2982         case AST_CONTROL_ANSWER:
2983         case AST_CONTROL_HANGUP:
2984         case AST_CONTROL_RING:
2985         case AST_CONTROL_HOLD:
2986         case AST_CONTROL_UNHOLD:
2987         case AST_CONTROL_T38:
2988                 /* Nothing left to do for these. */
2989                 res = 0;
2990                 break;
2991         }
2992
2993         if (ts) {
2994                 /* We have a tone to play, yay. */
2995                 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2996                 ast_playtones_start(chan, 0, ts->data, 1);
2997                 ts = ast_tone_zone_sound_unref(ts);
2998                 res = 0;
2999                 chan->visible_indication = condition;
3000         }
3001
3002         if (res) {
3003                 /* not handled */
3004                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
3005         }
3006
3007         return res;
3008 }
3009
3010 int ast_recvchar(struct ast_channel *chan, int timeout)
3011 {
3012         int c;
3013         char *buf = ast_recvtext(chan, timeout);
3014         if (buf == NULL)
3015                 return -1;      /* error or timeout */
3016         c = *(unsigned char *)buf;
3017         ast_free(buf);
3018         return c;
3019 }
3020
3021 char *ast_recvtext(struct ast_channel *chan, int timeout)
3022 {
3023         int res, done = 0;
3024         char *buf = NULL;
3025         
3026         while (!done) {
3027                 struct ast_frame *f;
3028                 if (ast_check_hangup(chan))
3029                         break;
3030                 res = ast_waitfor(chan, timeout);
3031                 if (res <= 0) /* timeout or error */
3032                         break;
3033                 timeout = res;  /* update timeout */
3034                 f = ast_read(chan);
3035                 if (f == NULL)
3036                         break; /* no frame */
3037                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
3038                         done = 1;       /* force a break */
3039                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
3040                         buf = ast_strndup((char *) f->data.ptr, f->datalen);    /* dup and break */
3041                         done = 1;
3042                 }
3043                 ast_frfree(f);
3044         }
3045         return buf;
3046 }
3047
3048 int ast_sendtext(struct ast_channel *chan, const char *text)
3049 {
3050         int res = 0;
3051         /* Stop if we're a zombie or need a soft hangup */
3052         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
3053                 return -1;
3054         CHECK_BLOCKING(chan);
3055         if (chan->tech->send_text)
3056                 res = chan->tech->send_text(chan, text);
3057         ast_clear_flag(chan, AST_FLAG_BLOCKING);
3058         return res;
3059 }
3060
3061 int ast_senddigit_begin(struct ast_channel *chan, char digit)
3062 {
3063         /* Device does not support DTMF tones, lets fake
3064          * it by doing our own generation. */
3065         static const char* dtmf_tones[] = {
3066                 "941+1336", /* 0 */
3067                 "697+1209", /* 1 */
3068                 "697+1336", /* 2 */
3069                 "697+1477", /* 3 */
3070                 "770+1209", /* 4 */
3071                 "770+1336", /* 5 */
3072                 "770+1477", /* 6 */
3073                 "852+1209", /* 7 */
3074                 "852+1336", /* 8 */
3075                 "852+1477", /* 9 */
3076                 "697+1633", /* A */
3077                 "770+1633", /* B */
3078                 "852+1633", /* C */
3079                 "941+1633", /* D */
3080                 "941+1209", /* * */
3081                 "941+1477"  /* # */
3082         };
3083
3084         if (!chan->tech->send_digit_begin)
3085                 return 0;
3086
3087         if (!chan->tech->send_digit_begin(chan, digit))
3088                 return 0;
3089
3090         if (digit >= '0' && digit <='9')
3091                 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
3092         else if (digit >= 'A' && digit <= 'D')
3093                 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
3094         else if (digit == '*')
3095                 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
3096         else if (digit == '#')
3097                 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
3098         else {
3099                 /* not handled */
3100                 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
3101         }
3102
3103         return 0;
3104 }
3105
3106 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
3107 {
3108         int res = -1;
3109
3110         if (chan->tech->send_digit_end)
3111                 res = chan->tech->send_digit_end(chan, digit, duration);
3112
3113         if (res && chan->generator)
3114                 ast_playtones_stop(chan);
3115         
3116         return 0;
3117 }
3118
3119 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
3120 {
3121         if (chan->tech->send_digit_begin) {
3122                 ast_senddigit_begin(chan, digit);
3123                 ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
3124         }
3125