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