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