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