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