Improve behavior of ast_answer() to not lose incoming frames
[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 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
1704 {
1705         int res = 0;
1706
1707         ast_channel_lock(chan);
1708
1709         /* You can't answer an outbound call */
1710         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1711                 ast_channel_unlock(chan);
1712                 return 0;
1713         }
1714
1715         /* Stop if we're a zombie or need a soft hangup */
1716         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1717                 ast_channel_unlock(chan);
1718                 return -1;
1719         }
1720
1721         ast_channel_unlock(chan);
1722
1723         switch (chan->_state) {
1724         case AST_STATE_RINGING:
1725         case AST_STATE_RING:
1726                 ast_channel_lock(chan);
1727                 if (chan->tech->answer) {
1728                         res = chan->tech->answer(chan);
1729                 }
1730                 ast_setstate(chan, AST_STATE_UP);
1731                 if (cdr_answer) {
1732                         ast_cdr_answer(chan->cdr);
1733                 }
1734                 ast_channel_unlock(chan);
1735                 break;
1736         case AST_STATE_UP:
1737                 /* Calling ast_cdr_answer when it it has previously been called
1738                  * is essentially a no-op, so it is safe.
1739                  */
1740                 if (cdr_answer) {
1741                         ast_cdr_answer(chan->cdr);
1742                 }
1743                 break;
1744         default:
1745                 break;
1746         }
1747
1748         ast_indicate(chan, -1);
1749         chan->visible_indication = 0;
1750
1751         return res;
1752 }
1753
1754 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
1755 {
1756         int res = 0;
1757         enum ast_channel_state old_state;
1758
1759         old_state = chan->_state;
1760         if ((res = ast_raw_answer(chan, cdr_answer))) {
1761                 return res;
1762         }
1763
1764         switch (old_state) {
1765         case AST_STATE_RINGING:
1766         case AST_STATE_RING:
1767                 /* wait for media to start flowing, but don't wait any longer
1768                  * than 'delay' or 500 milliseconds, whichever is longer
1769                  */
1770                 do {
1771                         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1772                         struct ast_frame *cur, *new;
1773                         int ms = MAX(delay, 500);
1774                         unsigned int done = 0;
1775
1776                         AST_LIST_HEAD_INIT_NOLOCK(&frames);
1777
1778                         for (;;) {
1779                                 ms = ast_waitfor(chan, ms);
1780                                 if (ms < 0) {
1781                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
1782                                         res = -1;
1783                                         break;
1784                                 }
1785                                 if (ms == 0) {
1786                                         ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
1787                                         break;
1788                                 }
1789                                 cur = ast_read(chan);
1790                                 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
1791                                              (cur->subclass == AST_CONTROL_HANGUP))) {
1792                                         if (cur) {
1793                                                 ast_frfree(cur);
1794                                         }
1795                                         res = -1;
1796                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
1797                                         break;
1798                                 }
1799
1800                                 if ((new = ast_frisolate(cur)) != cur) {
1801                                         ast_frfree(cur);
1802                                 }
1803
1804                                 AST_LIST_INSERT_TAIL(&frames, new, frame_list);
1805
1806                                 /* if a specific delay period was requested, continue
1807                                  * until that delay has passed. don't stop just because
1808                                  * incoming media has arrived.
1809                                  */
1810                                 if (delay) {
1811                                         continue;
1812                                 }
1813
1814                                 switch (new->frametype) {
1815                                         /* all of these frametypes qualify as 'media' */
1816                                 case AST_FRAME_VOICE:
1817                                 case AST_FRAME_VIDEO:
1818                                 case AST_FRAME_TEXT:
1819                                 case AST_FRAME_DTMF_BEGIN:
1820                                 case AST_FRAME_DTMF_END:
1821                                 case AST_FRAME_IMAGE:
1822                                 case AST_FRAME_HTML:
1823                                 case AST_FRAME_MODEM:
1824                                         done = 1;
1825                                         break;
1826                                 case AST_FRAME_CONTROL:
1827                                 case AST_FRAME_IAX:
1828                                 case AST_FRAME_NULL:
1829                                 case AST_FRAME_CNG:
1830                                         break;
1831                                 }
1832
1833                                 if (done) {
1834                                         break;
1835                                 }
1836                         }
1837
1838                         if (res == 0) {
1839                                 ast_channel_lock(chan);
1840                                 while ((cur = AST_LIST_REMOVE(&frames, AST_LIST_LAST(&frames), frame_list))) {
1841                                         ast_queue_frame_head(chan, cur);
1842                                         ast_frfree(cur);
1843                                 }
1844                                 ast_channel_unlock(chan);
1845                         }
1846                 } while (0);
1847                 break;
1848         default:
1849                 break;
1850         }
1851
1852         return res;
1853 }
1854
1855 int ast_answer(struct ast_channel *chan)
1856 {
1857         return __ast_answer(chan, 0, 1);
1858 }
1859
1860 void ast_deactivate_generator(struct ast_channel *chan)
1861 {
1862         ast_channel_lock(chan);
1863         if (chan->generatordata) {
1864                 if (chan->generator && chan->generator->release)
1865                         chan->generator->release(chan, chan->generatordata);
1866                 chan->generatordata = NULL;
1867                 chan->generator = NULL;
1868                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
1869                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1870                 ast_settimeout(chan, 0, NULL, NULL);
1871         }
1872         ast_channel_unlock(chan);
1873 }
1874
1875 static int generator_force(const void *data)
1876 {
1877         /* Called if generator doesn't have data */
1878         void *tmp;
1879         int res;
1880         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1881         struct ast_channel *chan = (struct ast_channel *)data;
1882
1883         ast_channel_lock(chan);
1884         tmp = chan->generatordata;
1885         chan->generatordata = NULL;
1886         if (chan->generator)
1887                 generate = chan->generator->generate;
1888         ast_channel_unlock(chan);
1889
1890         if (!tmp || !generate)
1891                 return 0;
1892
1893         res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
1894
1895         chan->generatordata = tmp;
1896
1897         if (res) {
1898                 ast_debug(1, "Auto-deactivating generator\n");
1899                 ast_deactivate_generator(chan);
1900         }
1901
1902         return 0;
1903 }
1904
1905 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1906 {
1907         int res = 0;
1908
1909         ast_channel_lock(chan);
1910
1911         if (chan->generatordata) {
1912                 if (chan->generator && chan->generator->release)
1913                         chan->generator->release(chan, chan->generatordata);
1914                 chan->generatordata = NULL;
1915         }
1916
1917         ast_prod(chan);
1918         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1919                 res = -1;
1920         }
1921         
1922         if (!res) {
1923                 ast_settimeout(chan, 50, generator_force, chan);
1924                 chan->generator = gen;
1925         }
1926
1927         ast_channel_unlock(chan);
1928
1929         return res;
1930 }
1931
1932 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1933 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1934 {
1935         int winner = -1;
1936         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1937         return winner;
1938 }
1939
1940 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1941 #ifdef HAVE_EPOLL
1942 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
1943                                         int *exception, int *outfd, int *ms)
1944 #else
1945 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1946                                         int *exception, int *outfd, int *ms)
1947 #endif
1948 {
1949         struct timeval start = { 0 , 0 };
1950         struct pollfd *pfds = NULL;
1951         int res;
1952         long rms;
1953         int x, y, max;
1954         int sz;
1955         struct timeval now = { 0, 0 };
1956         struct timeval whentohangup = { 0, 0 }, diff;
1957         struct ast_channel *winner = NULL;
1958         struct fdmap {
1959                 int chan;
1960                 int fdno;
1961         } *fdmap = NULL;
1962
1963         if ((sz = n * AST_MAX_FDS + nfds)) {
1964                 pfds = alloca(sizeof(*pfds) * sz);
1965                 fdmap = alloca(sizeof(*fdmap) * sz);
1966         }
1967
1968         if (outfd)
1969                 *outfd = -99999;
1970         if (exception)
1971                 *exception = 0;
1972         
1973         /* Perform any pending masquerades */
1974         for (x = 0; x < n; x++) {
1975                 ast_channel_lock(c[x]);
1976                 if (c[x]->masq && ast_do_masquerade(c[x])) {
1977                         ast_log(LOG_WARNING, "Masquerade failed\n");
1978                         *ms = -1;
1979                         ast_channel_unlock(c[x]);
1980                         return NULL;
1981                 }
1982                 if (!ast_tvzero(c[x]->whentohangup)) {
1983                         if (ast_tvzero(whentohangup))
1984                                 now = ast_tvnow();
1985                         diff = ast_tvsub(c[x]->whentohangup, now);
1986                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
1987                                 /* Should already be hungup */
1988                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1989                                 ast_channel_unlock(c[x]);
1990                                 return c[x];
1991                         }
1992                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
1993                                 whentohangup = diff;
1994                 }
1995                 ast_channel_unlock(c[x]);
1996         }
1997         /* Wait full interval */
1998         rms = *ms;
1999         if (!ast_tvzero(whentohangup)) {
2000                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
2001                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
2002                         rms =  *ms;
2003         }
2004         /*
2005          * Build the pollfd array, putting the channels' fds first,
2006          * followed by individual fds. Order is important because
2007          * individual fd's must have priority over channel fds.
2008          */
2009         max = 0;
2010         for (x = 0; x < n; x++) {
2011                 for (y = 0; y < AST_MAX_FDS; y++) {
2012                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
2013                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
2014                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
2015                 }
2016                 CHECK_BLOCKING(c[x]);
2017         }
2018         /* Add the individual fds */
2019         for (x = 0; x < nfds; x++) {
2020                 fdmap[max].chan = -1;
2021                 max += ast_add_fd(&pfds[max], fds[x]);
2022         }
2023
2024         if (*ms > 0)
2025                 start = ast_tvnow();
2026         
2027         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
2028                 do {
2029                         int kbrms = rms;
2030                         if (kbrms > 600000)
2031                                 kbrms = 600000;
2032                         res = poll(pfds, max, kbrms);
2033                         if (!res)
2034                                 rms -= kbrms;
2035                 } while (!res && (rms > 0));
2036         } else {
2037                 res = poll(pfds, max, rms);
2038         }
2039         for (x = 0; x < n; x++)
2040                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
2041         if (res < 0) { /* Simulate a timeout if we were interrupted */
2042                 if (errno != EINTR)
2043                         *ms = -1;
2044                 return NULL;
2045         }
2046         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
2047                 now = ast_tvnow();
2048                 for (x = 0; x < n; x++) {
2049                         if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
2050                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2051                                 if (winner == NULL)
2052                                         winner = c[x];
2053                         }
2054                 }
2055         }
2056         if (res == 0) { /* no fd ready, reset timeout and done */
2057                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
2058                 return winner;
2059         }
2060         /*
2061          * Then check if any channel or fd has a pending event.
2062          * Remember to check channels first and fds last, as they
2063          * must have priority on setting 'winner'
2064          */
2065         for (x = 0; x < max; x++) {
2066                 res = pfds[x].revents;
2067                 if (res == 0)
2068                         continue;
2069                 if (fdmap[x].chan >= 0) {       /* this is a channel */
2070                         winner = c[fdmap[x].chan];      /* override previous winners */
2071                         if (res & POLLPRI)
2072                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2073                         else
2074                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2075                         winner->fdno = fdmap[x].fdno;
2076                 } else {                        /* this is an fd */
2077                         if (outfd)
2078                                 *outfd = pfds[x].fd;
2079                         if (exception)
2080                                 *exception = (res & POLLPRI) ? -1 : 0;
2081                         winner = NULL;
2082                 }
2083         }
2084         if (*ms > 0) {
2085                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2086                 if (*ms < 0)
2087                         *ms = 0;
2088         }
2089         return winner;
2090 }
2091
2092 #ifdef HAVE_EPOLL
2093 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
2094 {
2095         struct timeval start = { 0 , 0 };
2096         int res = 0;
2097         struct epoll_event ev[1];
2098         long diff, rms = *ms;
2099         struct ast_channel *winner = NULL;
2100         struct ast_epoll_data *aed = NULL;
2101
2102         ast_channel_lock(chan);
2103
2104         /* See if this channel needs to be masqueraded */
2105         if (chan->masq && ast_do_masquerade(chan)) {
2106                 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
2107                 *ms = -1;
2108                 ast_channel_unlock(chan);
2109                 return NULL;
2110         }
2111
2112         /* Figure out their timeout */
2113         if (!ast_tvzero(chan->whentohangup)) {
2114                 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
2115                         /* They should already be hungup! */
2116                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2117                         ast_channel_unlock(chan);
2118                         return NULL;
2119                 }
2120                 /* If this value is smaller then the current one... make it priority */
2121                 if (rms > diff)
2122                         rms = diff;
2123         }
2124
2125         ast_channel_unlock(chan);
2126
2127         /* Time to make this channel block... */
2128         CHECK_BLOCKING(chan);
2129
2130         if (*ms > 0)
2131                 start = ast_tvnow();
2132
2133         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
2134         res = epoll_wait(chan->epfd, ev, 1, rms);
2135
2136         /* Stop blocking */
2137         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2138
2139         /* Simulate a timeout if we were interrupted */
2140         if (res < 0) {
2141                 if (errno != EINTR)
2142                         *ms = -1;
2143                 return NULL;
2144         }
2145
2146         /* If this channel has a timeout see if it expired */
2147         if (!ast_tvzero(chan->whentohangup)) {
2148                 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
2149                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2150                         winner = chan;
2151                 }
2152         }
2153
2154         /* No fd ready, reset timeout and be done for now */
2155         if (!res) {
2156                 *ms = 0;
2157                 return winner;
2158         }
2159
2160         /* See what events are pending */
2161         aed = ev[0].data.ptr;
2162         chan->fdno = aed->which;
2163         if (ev[0].events & EPOLLPRI)
2164                 ast_set_flag(chan, AST_FLAG_EXCEPTION);
2165         else
2166                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2167
2168         if (*ms > 0) {
2169                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2170                 if (*ms < 0)
2171                         *ms = 0;
2172         }
2173
2174         return chan;
2175 }
2176
2177 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2178 {
2179         struct timeval start = { 0 , 0 };
2180         int res = 0, i;
2181         struct epoll_event ev[25] = { { 0, } };
2182         struct timeval now = { 0, 0 };
2183         long whentohangup = 0, diff = 0, rms = *ms;
2184         struct ast_channel *winner = NULL;
2185
2186         for (i = 0; i < n; i++) {
2187                 ast_channel_lock(c[i]);
2188                 if (c[i]->masq && ast_do_masquerade(c[i])) {
2189                         ast_log(LOG_WARNING, "Masquerade failed\n");
2190                         *ms = -1;
2191                         ast_channel_unlock(c[i]);
2192                         return NULL;
2193                 }
2194                 if (!ast_tvzero(c[i]->whentohangup)) {
2195                         if (whentohangup == 0)
2196                                 now = ast_tvnow();
2197                         if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
2198                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2199                                 ast_channel_unlock(c[i]);
2200                                 return c[i];
2201                         }
2202                         if (!whentohangup || whentohangup > diff)
2203                                 whentohangup = diff;
2204                 }
2205                 ast_channel_unlock(c[i]);
2206                 CHECK_BLOCKING(c[i]);
2207         }
2208
2209         rms = *ms;
2210         if (whentohangup) {
2211                 rms = whentohangup;
2212                 if (*ms >= 0 && *ms < rms)
2213                         rms = *ms;
2214         }
2215
2216         if (*ms > 0)
2217                 start = ast_tvnow();
2218
2219         res = epoll_wait(c[0]->epfd, ev, 25, rms);
2220
2221         for (i = 0; i < n; i++)
2222                 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2223
2224         if (res < 0) {
2225                 if (errno != EINTR)
2226                         *ms = -1;
2227                 return NULL;
2228         }
2229
2230         if (whentohangup) {
2231                 now = ast_tvnow();
2232                 for (i = 0; i < n; i++) {
2233                         if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
2234                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2235                                 if (!winner)
2236                                         winner = c[i];
2237                         }
2238                 }
2239         }
2240
2241         if (!res) {
2242                 *ms = 0;
2243                 return winner;
2244         }
2245
2246         for (i = 0; i < res; i++) {
2247                 struct ast_epoll_data *aed = ev[i].data.ptr;
2248
2249                 if (!ev[i].events || !aed)
2250                         continue;
2251
2252                 winner = aed->chan;
2253                 if (ev[i].events & EPOLLPRI)
2254                         ast_set_flag(winner, AST_FLAG_EXCEPTION);
2255                 else
2256                         ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2257                 winner->fdno = aed->which;
2258         }
2259
2260         if (*ms > 0) {
2261                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2262                 if (*ms < 0)
2263                         *ms = 0;
2264         }
2265
2266         return winner;
2267 }
2268
2269 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2270                                         int *exception, int *outfd, int *ms)
2271 {
2272         /* Clear all provided values in one place. */
2273         if (outfd)
2274                 *outfd = -99999;
2275         if (exception)
2276                 *exception = 0;
2277
2278         /* If no epoll file descriptor is available resort to classic nandfds */
2279         if (!n || nfds || c[0]->epfd == -1)
2280                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2281         else if (!nfds && n == 1)
2282                 return ast_waitfor_nandfds_simple(c[0], ms);
2283         else
2284                 return ast_waitfor_nandfds_complex(c, n, ms);
2285 }
2286 #endif
2287
2288 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2289 {
2290         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2291 }
2292
2293 int ast_waitfor(struct ast_channel *c, int ms)
2294 {
2295         int oldms = ms; /* -1 if no timeout */
2296
2297         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2298         if ((ms < 0) && (oldms < 0))
2299                 ms = 0;
2300         return ms;
2301 }
2302
2303 /* XXX never to be called with ms = -1 */
2304 int ast_waitfordigit(struct ast_channel *c, int ms)
2305 {
2306         return ast_waitfordigit_full(c, ms, -1, -1);
2307 }
2308
2309 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
2310 {
2311         int res;
2312         unsigned int real_rate = rate, max_rate;
2313
2314         ast_channel_lock(c);
2315
2316         if (c->timingfd == -1) {
2317                 ast_channel_unlock(c);
2318                 return -1;
2319         }
2320
2321         if (!func) {
2322                 rate = 0;
2323                 data = NULL;
2324         }
2325
2326         if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timingfd))) {
2327                 real_rate = max_rate;
2328         }
2329
2330         ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
2331
2332         res = ast_timer_set_rate(c->timingfd, real_rate);
2333
2334         c->timingfunc = func;
2335         c->timingdata = data;
2336
2337         ast_channel_unlock(c);
2338
2339         return res;
2340 }
2341
2342 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2343 {
2344         /* Stop if we're a zombie or need a soft hangup */
2345         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2346                 return -1;
2347
2348         /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2349         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2350
2351         /* Wait for a digit, no more than ms milliseconds total. */
2352         
2353         while (ms) {
2354                 struct ast_channel *rchan;
2355                 int outfd=-1;
2356
2357                 errno = 0;
2358                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2359                 
2360                 if (!rchan && outfd < 0 && ms) {
2361                         if (errno == 0 || errno == EINTR)
2362                                 continue;
2363                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2364                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2365                         return -1;
2366                 } else if (outfd > -1) {
2367                         /* The FD we were watching has something waiting */
2368                         ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2369                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2370                         return 1;
2371                 } else if (rchan) {
2372                         int res;
2373                         struct ast_frame *f = ast_read(c);
2374                         if (!f)
2375                                 return -1;
2376
2377                         switch (f->frametype) {
2378                         case AST_FRAME_DTMF_BEGIN:
2379                                 break;
2380                         case AST_FRAME_DTMF_END:
2381                                 res = f->subclass;
2382                                 ast_frfree(f);
2383                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2384                                 return res;
2385                         case AST_FRAME_CONTROL:
2386                                 switch (f->subclass) {
2387                                 case AST_CONTROL_HANGUP:
2388                                         ast_frfree(f);
2389                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2390                                         return -1;
2391                                 case AST_CONTROL_RINGING:
2392                                 case AST_CONTROL_ANSWER:
2393                                 case AST_CONTROL_SRCUPDATE:
2394                                         /* Unimportant */
2395                                         break;
2396                                 default:
2397                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2398                                         break;
2399                                 }
2400                                 break;
2401                         case AST_FRAME_VOICE:
2402                                 /* Write audio if appropriate */
2403                                 if (audiofd > -1) {
2404                                         if (write(audiofd, f->data.ptr, f->datalen) < 0) {
2405                                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
2406                                         }
2407                                 }
2408                         default:
2409                                 /* Ignore */
2410                                 break;
2411                         }
2412                         ast_frfree(f);
2413                 }
2414         }
2415
2416         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2417
2418         return 0; /* Time is up */
2419 }
2420
2421 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2422 {
2423         manager_event(EVENT_FLAG_DTMF,
2424                         "DTMF",
2425                         "Channel: %s\r\n"
2426                         "Uniqueid: %s\r\n"
2427                         "Digit: %c\r\n"
2428                         "Direction: %s\r\n"
2429                         "Begin: %s\r\n"
2430                         "End: %s\r\n",
2431                         chan->name, chan->uniqueid, digit, direction, begin, end);
2432 }
2433
2434 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2435 {
2436         if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2437                 void *tmp = chan->generatordata;
2438                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2439                 int res;
2440                 int samples;
2441
2442                 if (chan->timingfunc) {
2443                         ast_debug(1, "Generator got voice, switching to phase locked mode\n");
2444                         ast_settimeout(chan, 0, NULL, NULL);
2445                 }
2446
2447                 chan->generatordata = NULL;     /* reset, to let writes go through */
2448
2449                 if (f->subclass != chan->writeformat) {
2450                         float factor;
2451                         factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass));
2452                         samples = (int) ( ((float) f->samples) * factor );
2453                 } else {
2454                         samples = f->samples;
2455                 }
2456                 
2457                 if (chan->generator->generate) {
2458                         generate = chan->generator->generate;
2459                 }
2460                 /* This unlock is here based on two assumptions that hold true at this point in the
2461                  * code. 1) this function is only called from within __ast_read() and 2) all generators
2462                  * call ast_write() in their generate callback.
2463                  *
2464                  * The reason this is added is so that when ast_write is called, the lock that occurs 
2465                  * there will not recursively lock the channel. Doing this will cause intended deadlock 
2466                  * avoidance not to work in deeper functions
2467                  */
2468                 ast_channel_unlock(chan);
2469                 res = generate(chan, tmp, f->datalen, samples);
2470                 ast_channel_lock(chan);
2471                 chan->generatordata = tmp;
2472                 if (res) {
2473                         ast_debug(1, "Auto-deactivating generator\n");
2474                         ast_deactivate_generator(chan);
2475                 }
2476
2477         } else if (f->frametype == AST_FRAME_CNG) {
2478                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2479                         ast_debug(1, "Generator got CNG, switching to timed mode\n");
2480                         ast_settimeout(chan, 50, generator_force, chan);
2481                 }
2482         }
2483 }
2484
2485 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
2486 {
2487         struct ast_frame *fr = &chan->dtmff;
2488
2489         fr->frametype = AST_FRAME_DTMF_END;
2490         fr->subclass = f->subclass;
2491         fr->len = f->len;
2492
2493         /* The only time this function will be called is for a frame that just came
2494          * out of the channel driver.  So, we want to stick it on the tail of the
2495          * readq. */
2496
2497         ast_queue_frame(chan, fr);
2498 }
2499
2500 /*!
2501  * \brief Determine whether or not we should ignore DTMF in the readq
2502  */
2503 static inline int should_skip_dtmf(struct ast_channel *chan)
2504 {
2505         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
2506                 /* We're in the middle of emulating a digit, or DTMF has been
2507                  * explicitly deferred.  Skip this digit, then. */
2508                 return 1;
2509         }
2510                         
2511         if (!ast_tvzero(chan->dtmf_tv) && 
2512                         ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2513                 /* We're not in the middle of a digit, but it hasn't been long enough
2514                  * since the last digit, so we'll have to skip DTMF for now. */
2515                 return 1;
2516         }
2517
2518         return 0;
2519 }
2520
2521 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2522 {
2523         struct ast_frame *f = NULL;     /* the return value */
2524         int blah;
2525         int prestate;
2526         int count = 0, cause = 0;
2527
2528         /* this function is very long so make sure there is only one return
2529          * point at the end (there are only two exceptions to this).
2530          */
2531         while(ast_channel_trylock(chan)) {
2532                 if(count++ > 10) 
2533                         /*cannot goto done since the channel is not locked*/
2534                         return &ast_null_frame;
2535                 usleep(1);
2536         }
2537
2538         if (chan->fdno == -1) {
2539                 ast_log(LOG_ERROR, "ast_read() called with no recorded file descriptor.\n");
2540                 f = &ast_null_frame;
2541                 goto done;
2542         }
2543
2544         if (chan->masq) {
2545                 if (ast_do_masquerade(chan))
2546                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2547                 else
2548                         f =  &ast_null_frame;
2549                 goto done;
2550         }
2551
2552         /* Stop if we're a zombie or need a soft hangup */
2553         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2554                 if (chan->generator)
2555                         ast_deactivate_generator(chan);
2556                 goto done;
2557         }
2558         prestate = chan->_state;
2559
2560         /* Read and ignore anything on the alertpipe, but read only
2561            one sizeof(blah) per frame that we send from it */
2562         if (chan->alertpipe[0] > -1) {
2563                 int flags = fcntl(chan->alertpipe[0], F_GETFL);
2564                 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
2565                  * which immediately causes a deadlock scenario.  Detect and prevent this. */
2566                 if ((flags & O_NONBLOCK) == 0) {
2567                         ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
2568                         if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2569                                 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
2570                                 f = &ast_null_frame;
2571                                 goto done;
2572                         }
2573                 }
2574                 if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
2575                         if (errno != EINTR && errno != EAGAIN)
2576                                 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
2577                 }
2578         }
2579
2580         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
2581                 enum ast_timer_event res;
2582
2583                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2584
2585                 res = ast_timer_get_event(chan->timingfd);
2586
2587                 switch (res) {
2588                 case AST_TIMING_EVENT_EXPIRED:
2589                         ast_timer_ack(chan->timingfd, 1);
2590
2591                         if (chan->timingfunc) {
2592                                 /* save a copy of func/data before unlocking the channel */
2593                                 int (*func)(const void *) = chan->timingfunc;
2594                                 void *data = chan->timingdata;
2595                                 chan->fdno = -1;
2596                                 ast_channel_unlock(chan);
2597                                 func(data);
2598                         } else {
2599                                 ast_timer_set_rate(chan->timingfd, 0);
2600                                 chan->fdno = -1;
2601                                 ast_channel_unlock(chan);
2602                         }
2603
2604                         /* cannot 'goto done' because the channel is already unlocked */
2605                         return &ast_null_frame;
2606
2607                 case AST_TIMING_EVENT_CONTINUOUS:
2608                         if (AST_LIST_EMPTY(&chan->readq) || 
2609                                 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2610                                 ast_timer_disable_continuous(chan->timingfd);
2611                         }
2612                         break;
2613                 }
2614
2615         } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2616                 /* if the AST_GENERATOR_FD is set, call the generator with args
2617                  * set to -1 so it can do whatever it needs to.
2618                  */
2619                 void *tmp = chan->generatordata;
2620                 chan->generatordata = NULL;     /* reset to let ast_write get through */
2621                 chan->generator->generate(chan, tmp, -1, -1);
2622                 chan->generatordata = tmp;
2623                 f = &ast_null_frame;
2624                 chan->fdno = -1;
2625                 goto done;
2626         }
2627
2628         /* Check for pending read queue */
2629         if (!AST_LIST_EMPTY(&chan->readq)) {
2630                 int skip_dtmf = should_skip_dtmf(chan);
2631
2632                 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
2633                         /* We have to be picky about which frame we pull off of the readq because
2634                          * there are cases where we want to leave DTMF frames on the queue until
2635                          * some later time. */
2636
2637                         if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
2638                                 continue;
2639                         }
2640
2641                         AST_LIST_REMOVE_CURRENT(frame_list);
2642                         break;
2643                 }
2644                 AST_LIST_TRAVERSE_SAFE_END
2645                 
2646                 if (!f) {
2647                         /* There were no acceptable frames on the readq. */
2648                         f = &ast_null_frame;
2649                         if (chan->alertpipe[0] > -1) {
2650                                 int poke = 0;
2651                                 /* Restore the state of the alertpipe since we aren't ready for any
2652                                  * of the frames in the readq. */
2653                                 if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
2654                                         ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
2655                                 }
2656                         }
2657                 }
2658
2659                 /* Interpret hangup and return NULL */
2660                 /* XXX why not the same for frames from the channel ? */
2661                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2662                         cause = f->data.uint32;
2663                         ast_frfree(f);
2664                         f = NULL;
2665                 }
2666         } else {
2667                 chan->blocker = pthread_self();
2668                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2669                         if (chan->tech->exception)
2670                                 f = chan->tech->exception(chan);
2671                         else {
2672                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2673                                 f = &ast_null_frame;
2674                         }
2675                         /* Clear the exception flag */
2676                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2677                 } else if (chan->tech->read)
2678                         f = chan->tech->read(chan);
2679                 else
2680                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2681         }
2682
2683         /*
2684          * Reset the recorded file descriptor that triggered this read so that we can
2685          * easily detect when ast_read() is called without properly using ast_waitfor().
2686          */
2687         chan->fdno = -1;
2688
2689         if (f) {
2690                 /* if the channel driver returned more than one frame, stuff the excess
2691                    into the readq for the next ast_read call (note that we can safely assume
2692                    that the readq is empty, because otherwise we would not have called into
2693                    the channel driver and f would be only a single frame)
2694                 */
2695                 if (AST_LIST_NEXT(f, frame_list)) {
2696                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2697                         AST_LIST_NEXT(f, frame_list) = NULL;
2698                 }
2699
2700                 switch (f->frametype) {
2701                 case AST_FRAME_CONTROL:
2702                         if (f->subclass == AST_CONTROL_ANSWER) {
2703                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2704                                         ast_debug(1, "Ignoring answer on an inbound call!\n");
2705                                         ast_frfree(f);
2706                                         f = &ast_null_frame;
2707                                 } else if (prestate == AST_STATE_UP) {
2708                                         ast_debug(1, "Dropping duplicate answer!\n");
2709                                         ast_frfree(f);
2710                                         f = &ast_null_frame;
2711                                 } else {
2712                                         /* Answer the CDR */
2713                                         ast_setstate(chan, AST_STATE_UP);
2714                                         /* removed a call to ast_cdr_answer(chan->cdr) from here. */
2715                                 }
2716                         }
2717                         break;
2718                 case AST_FRAME_DTMF_END:
2719                         send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2720                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2721                         /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
2722                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2723                                 queue_dtmf_readq(chan, f);
2724                                 ast_frfree(f);
2725                                 f = &ast_null_frame;
2726                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2727                                 if (!ast_tvzero(chan->dtmf_tv) && 
2728                                     ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2729                                         /* If it hasn't been long enough, defer this digit */
2730                                         queue_dtmf_readq(chan, f);
2731                                         ast_frfree(f);
2732                                         f = &ast_null_frame;
2733                                 } else {
2734                                         /* There was no begin, turn this into a begin and send the end later */
2735                                         f->frametype = AST_FRAME_DTMF_BEGIN;
2736                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2737                                         chan->emulate_dtmf_digit = f->subclass;
2738                                         chan->dtmf_tv = ast_tvnow();
2739                                         if (f->len) {
2740                                                 if (f->len > AST_MIN_DTMF_DURATION)
2741                                                         chan->emulate_dtmf_duration = f->len;
2742                                                 else 
2743                                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2744                                         } else
2745                                                 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2746                                         ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2747                                 }
2748                                 if (chan->audiohooks) {
2749                                         struct ast_frame *old_frame = f;
2750                                         /*!
2751                                          * \todo XXX It is possible to write a digit to the audiohook twice
2752                                          * if the digit was originally read while the channel was in autoservice. */
2753                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2754                                         if (old_frame != f)
2755                                                 ast_frfree(old_frame);
2756                                 }
2757                         } else {
2758                                 struct timeval now = ast_tvnow();
2759                                 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2760                                         ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2761                                         ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2762                                         if (!f->len)
2763                                                 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2764                                 } else if (!f->len) {
2765                                         ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2766                                         f->len = AST_MIN_DTMF_DURATION;
2767                                 }
2768                                 if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2769                                         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);
2770                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2771                                         chan->emulate_dtmf_digit = f->subclass;
2772                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2773                                         ast_frfree(f);
2774                                         f = &ast_null_frame;
2775                                 } else {
2776                                         ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2777                                         if (f->len < AST_MIN_DTMF_DURATION) {
2778                                                 f->len = AST_MIN_DTMF_DURATION;
2779                                         }
2780                                         chan->dtmf_tv = now;
2781                                 }
2782                                 if (chan->audiohooks) {
2783                                         struct ast_frame *old_frame = f;
2784                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2785                                         if (old_frame != f)
2786                                                 ast_frfree(old_frame);
2787                                 }
2788                         }
2789                         break;
2790                 case AST_FRAME_DTMF_BEGIN:
2791                         send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2792                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2793                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) || 
2794                             (!ast_tvzero(chan->dtmf_tv) && 
2795                               ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2796                                 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2797                                 ast_frfree(f);
2798                                 f = &ast_null_frame;
2799                         } else {
2800                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2801                                 chan->dtmf_tv = ast_tvnow();
2802                                 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2803                         }
2804                         break;
2805                 case AST_FRAME_NULL:
2806                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2807                          * is reached , because we want to make sure we pass at least one
2808                          * voice frame through before starting the next digit, to ensure a gap
2809                          * between DTMF digits. */
2810                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2811                                 struct timeval now = ast_tvnow();
2812                                 if (!chan->emulate_dtmf_duration) {
2813                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2814                                         chan->emulate_dtmf_digit = 0;
2815                                 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2816                                         chan->emulate_dtmf_duration = 0;
2817                                         ast_frfree(f);
2818                                         f = &chan->dtmff;
2819                                         f->frametype = AST_FRAME_DTMF_END;
2820                                         f->subclass = chan->emulate_dtmf_digit;
2821                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2822                                         chan->dtmf_tv = now;
2823                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2824                                         chan->emulate_dtmf_digit = 0;
2825                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2826                                 }
2827                         }
2828                         break;
2829                 case AST_FRAME_VOICE:
2830                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2831                          * is reached , because we want to make sure we pass at least one
2832                          * voice frame through before starting the next digit, to ensure a gap
2833                          * between DTMF digits. */
2834                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2835                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2836                                 chan->emulate_dtmf_digit = 0;
2837                         }
2838
2839                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2840                                 if (dropaudio)
2841                                         ast_read_generator_actions(chan, f);
2842                                 ast_frfree(f);
2843                                 f = &ast_null_frame;
2844                         }
2845
2846                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2847                                 struct timeval now = ast_tvnow();
2848                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2849                                         chan->emulate_dtmf_duration = 0;
2850                                         ast_frfree(f);
2851                                         f = &chan->dtmff;
2852                                         f->frametype = AST_FRAME_DTMF_END;
2853                                         f->subclass = chan->emulate_dtmf_digit;
2854                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2855                                         chan->dtmf_tv = now;
2856                                         if (chan->audiohooks) {
2857                                                 struct ast_frame *old_frame = f;
2858                                                 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2859                                                 if (old_frame != f)
2860                                                         ast_frfree(old_frame);
2861                                         }
2862                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2863                                 } else {
2864                                         /* Drop voice frames while we're still in the middle of the digit */
2865                                         ast_frfree(f);
2866                                         f = &ast_null_frame;
2867                                 }
2868                         } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2869                                 /* This frame is not one of the current native formats -- drop it on the floor */
2870                                 char to[200];
2871                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2872                                         chan->name, ast_getformatname(f->subclass), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
2873                                 ast_frfree(f);
2874                                 f = &ast_null_frame;
2875                         } else if ((f->frametype == AST_FRAME_VOICE)) {
2876                                 /* Send frame to audiohooks if present */
2877                                 if (chan->audiohooks) {
2878                                         struct ast_frame *old_frame = f;
2879                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2880                                         if (old_frame != f)
2881                                                 ast_frfree(old_frame);
2882                                 }
2883                                 if (chan->monitor && chan->monitor->read_stream ) {
2884                                         /* XXX what does this do ? */
2885 #ifndef MONITOR_CONSTANT_DELAY
2886                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2887                                         if (jump >= 0) {
2888                                                 jump = chan->outsmpl - chan->insmpl;
2889                                                 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2890                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2891                                                 chan->insmpl += jump + f->samples;
2892                                         } else
2893                                                 chan->insmpl+= f->samples;
2894 #else
2895                                         int jump = chan->outsmpl - chan->insmpl;
2896                                         if (jump - MONITOR_DELAY >= 0) {
2897                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2898                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2899                                                 chan->insmpl += jump;
2900                                         } else
2901                                                 chan->insmpl += f->samples;
2902 #endif
2903                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2904                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2905                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2906                                         }
2907                                 }
2908
2909                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2910                                         f = &ast_null_frame;
2911                                 else
2912                                         /* Run generator sitting on the line if timing device not available
2913                                          * and synchronous generation of outgoing frames is necessary       */
2914                                         ast_read_generator_actions(chan, f);
2915                         }
2916                 default:
2917                         /* Just pass it on! */
2918                         break;
2919                 }
2920         } else {
2921                 /* Make sure we always return NULL in the future */
2922                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2923                 if (cause)
2924                         chan->hangupcause = cause;
2925                 if (chan->generator)
2926                         ast_deactivate_generator(chan);
2927                 /* We no longer End the CDR here */
2928         }
2929
2930         /* High bit prints debugging */
2931         if (chan->fin & DEBUGCHAN_FLAG)
2932                 ast_frame_dump(chan->name, f, "<<");
2933         chan->fin = FRAMECOUNT_INC(chan->fin);
2934
2935 done:
2936         if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2937                 chan->generator->digit(chan, f->subclass);
2938
2939         ast_channel_unlock(chan);
2940         return f;
2941 }
2942
2943 int ast_internal_timing_enabled(struct ast_channel *chan)
2944 {
2945         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2946         ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2947         return ret;
2948 }
2949
2950 struct ast_frame *ast_read(struct ast_channel *chan)
2951 {
2952         return __ast_read(chan, 0);
2953 }
2954
2955 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2956 {
2957         return __ast_read(chan, 1);
2958 }
2959
2960 int ast_indicate(struct ast_channel *chan, int condition)
2961 {
2962         return ast_indicate_data(chan, condition, NULL, 0);
2963 }
2964
2965 static int attribute_const is_visible_indication(enum ast_control_frame_type condition)
2966 {
2967         /* Don't include a default case here so that we get compiler warnings
2968          * when a new type is added. */
2969
2970         switch (condition) {
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_T38:
2985                 return 0;
2986
2987         case AST_CONTROL_CONGESTION:
2988         case AST_CONTROL_BUSY:
2989         case AST_CONTROL_RINGING:
2990         case AST_CONTROL_RING:
2991         case AST_CONTROL_HOLD:
2992         case AST_CONTROL_UNHOLD:
2993                 return 1;
2994         }
2995
2996         return 0;
2997 }
2998
2999 int ast_indicate_data(struct ast_channel *chan, int _condition,
3000                 const void *data, size_t datalen)
3001 {
3002         /* By using an enum, we'll get compiler warnings for values not handled 
3003          * in switch statements. */
3004         enum ast_control_frame_type condition = _condition;
3005         struct ast_tone_zone_sound *ts = NULL;
3006         int res = -1;
3007
3008         ast_channel_lock(chan);
3009
3010         /* Don't bother if the channel is about to go away, anyway. */
3011         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
3012                 ast_channel_unlock(chan);
3013                 return -1;
3014         }
3015
3016         if (chan->tech->indicate) {
3017                 /* See if the channel driver can handle this condition. */
3018                 res = chan->tech->indicate(chan, condition, data, datalen);
3019         }
3020
3021         ast_channel_unlock(chan);
3022
3023         if (chan->tech->indicate && !res) {
3024                 /* The channel driver successfully handled this indication */
3025                 if (is_visible_indication(condition)) {
3026                         chan->visible_indication = condition;
3027                 }
3028                 return 0;
3029         }
3030
3031         /* The channel driver does not support this indication, let's fake
3032          * it by doing our own tone generation if applicable. */
3033
3034         /*!\note If we compare the enumeration type, which does not have any
3035          * negative constants, the compiler may optimize this code away.
3036          * Therefore, we must perform an integer comparison here. */
3037         if (_condition < 0) {
3038                 /* Stop any tones that are playing */
3039                 ast_playtones_stop(chan);
3040                 return 0;
3041         }
3042
3043         /* Handle conditions that we have tones for. */
3044         switch (condition) {
3045         case AST_CONTROL_RINGING:
3046                 ts = ast_get_indication_tone(chan->zone, "ring");
3047                 break;
3048         case AST_CONTROL_BUSY:
3049                 ts = ast_get_indication_tone(chan->zone, "busy");
3050                 break;
3051         case AST_CONTROL_CONGESTION:
3052                 ts = ast_get_indication_tone(chan->zone, "congestion");
3053                 break;
3054         case AST_CONTROL_PROGRESS:
3055         case AST_CONTROL_PROCEEDING:
3056         case AST_CONTROL_VIDUPDATE:
3057         case AST_CONTROL_SRCUPDATE:
3058         case AST_CONTROL_RADIO_KEY:
3059         case AST_CONTROL_RADIO_UNKEY:
3060         case AST_CONTROL_OPTION:
3061         case AST_CONTROL_WINK:
3062         case AST_CONTROL_FLASH:
3063         case AST_CONTROL_OFFHOOK:
3064         case AST_CONTROL_TAKEOFFHOOK:
3065         case AST_CONTROL_ANSWER:
3066         case AST_CONTROL_HANGUP:
3067         case AST_CONTROL_RING:
3068         case AST_CONTROL_HOLD:
3069         case AST_CONTROL_UNHOLD:
3070         case AST_CONTROL_T38:
3071                 /* Nothing left to do for these. */
3072                 res = 0;
3073                 break;
3074         }
3075
3076         if (ts) {
3077                 /* We have a tone to play, yay. */
3078                 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
3079                 ast_playtones_start(chan, 0, ts->data, 1);
3080                 ts = ast_tone_zone_sound_unref(ts);
3081                 res = 0;
3082                 chan->visible_indication = condition;
3083         }
3084
3085         if (res) {
3086                 /* not handled */
3087                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
3088         }
3089
3090         return res;
3091 }
3092
3093 int ast_recvchar(struct ast_channel *chan, int timeout)
3094 {
3095         int c;
3096         char *buf = ast_recvtext(chan, timeout);
3097         if (buf == NULL)
3098                 return -1;      /* error or timeout */
3099         c = *(unsigned char *)buf;
3100         ast_free(buf);
3101         return c;
3102 }
3103
3104 char *ast_recvtext(struct ast_channel *chan, int timeout)
3105 {
3106         int res, done = 0;
3107         char *buf = NULL;
3108         
3109         while (!done) {
3110                 struct ast_frame *f;
3111                 if (ast_check_hangup(chan))
3112                         break;
3113                 res = ast_waitfor(chan, timeout);
3114                 if (res <= 0) /* timeout or error */