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