Merged revisions 235635 via svnmerge from
[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! Try increasing max file descriptors with ulimit -n\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                 ast_manager_event(tmp, 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                         ast_channel_unlock(chan);
1088                         return -1;
1089                 }
1090
1091                 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1092                 new_frames++;
1093                 if (f->frametype == AST_FRAME_VOICE) {
1094                         new_voice_frames++;
1095                 }
1096         }
1097
1098         /* Count how many frames exist on the queue */
1099         AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1100                 queued_frames++;
1101                 if (cur->frametype == AST_FRAME_VOICE) {
1102                         queued_voice_frames++;
1103                 }
1104         }
1105
1106         if ((queued_frames + new_frames) > 128) {
1107                 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
1108                 while ((f = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
1109                         ast_frfree(f);
1110                 }
1111                 ast_channel_unlock(chan);
1112                 return 0;
1113         }
1114
1115         if ((queued_voice_frames + new_voice_frames) > 96) {
1116                 ast_log(LOG_WARNING, "Exceptionally long voice queue length queuing to %s\n", chan->name);
1117                 while ((f = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
1118                         ast_frfree(f);
1119                 }
1120                 ast_channel_unlock(chan);
1121                 return 0;
1122         }
1123
1124         if (after) {
1125                 AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1126         } else {
1127                 if (head) {
1128                         AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1129                         AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1130                 }
1131                 AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1132         }
1133
1134         if (chan->alertpipe[1] > -1) {
1135                 if (write(chan->alertpipe[1], &blah, new_frames * sizeof(blah)) != (new_frames * sizeof(blah))) {
1136                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1137                                 chan->name, queued_frames, strerror(errno));
1138                 }
1139         } else if (chan->timingfd > -1) {
1140                 ast_timer_enable_continuous(chan->timer);
1141         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1142                 pthread_kill(chan->blocker, SIGURG);
1143         }
1144
1145         ast_channel_unlock(chan);
1146
1147         return 0;
1148 }
1149
1150 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1151 {
1152         return __ast_queue_frame(chan, fin, 0, NULL);
1153 }
1154
1155 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1156 {
1157         return __ast_queue_frame(chan, fin, 1, NULL);
1158 }
1159
1160 /*! \brief Queue a hangup frame for channel */
1161 int ast_queue_hangup(struct ast_channel *chan)
1162 {
1163         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1164         /* Yeah, let's not change a lock-critical value without locking */
1165         if (!ast_channel_trylock(chan)) {
1166                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1167                 ast_channel_unlock(chan);
1168         }
1169         return ast_queue_frame(chan, &f);
1170 }
1171
1172 /*! \brief Queue a hangup frame for channel */
1173 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1174 {
1175         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1176
1177         if (cause >= 0)
1178                 f.data.uint32 = cause;
1179
1180         /* Yeah, let's not change a lock-critical value without locking */
1181         if (!ast_channel_trylock(chan)) {
1182                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1183                 if (cause < 0)
1184                         f.data.uint32 = chan->hangupcause;
1185
1186                 ast_channel_unlock(chan);
1187         }
1188
1189         return ast_queue_frame(chan, &f);
1190 }
1191
1192 /*! \brief Queue a control frame */
1193 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1194 {
1195         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1196         return ast_queue_frame(chan, &f);
1197 }
1198
1199 /*! \brief Queue a control frame with payload */
1200 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1201                            const void *data, size_t datalen)
1202 {
1203         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1204         return ast_queue_frame(chan, &f);
1205 }
1206
1207 /*! \brief Set defer DTMF flag on channel */
1208 int ast_channel_defer_dtmf(struct ast_channel *chan)
1209 {
1210         int pre = 0;
1211
1212         if (chan) {
1213                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1214                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1215         }
1216         return pre;
1217 }
1218
1219 /*! \brief Unset defer DTMF flag on channel */
1220 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1221 {
1222         if (chan)
1223                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1224 }
1225
1226 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1227                 void *data, int ao2_flags)
1228 {
1229         return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1230 }
1231
1232 struct ast_channel_iterator {
1233         /* storage for non-dynamically allocated iterator */
1234         struct ao2_iterator simple_iterator;
1235         /* pointer to the actual iterator (simple_iterator or a dynamically
1236          * allocated iterator)
1237          */
1238         struct ao2_iterator *active_iterator;
1239 };
1240
1241 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1242 {
1243         ao2_iterator_destroy(i->active_iterator);
1244         ast_free(i);
1245
1246         return NULL;
1247 }
1248
1249 static struct ast_channel_iterator *channel_iterator_search(const char *name,
1250                                                             size_t name_len, const char *exten,
1251                                                             const char *context)
1252 {
1253         struct ast_channel_iterator *i;
1254         struct ast_channel tmp_chan = {
1255                 .name = name,
1256                 /* This is sort of a hack.  Basically, we're using an arbitrary field
1257                  * in ast_channel to pass the name_len for a prefix match.  If this
1258                  * gets changed, then the compare callback must be changed, too. */
1259                 .rings = name_len,
1260         };
1261
1262         if (!(i = ast_calloc(1, sizeof(*i)))) {
1263                 return NULL;
1264         }
1265
1266         if (exten) {
1267                 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1268         }
1269
1270         if (context) {
1271                 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1272         }
1273
1274         if (!(i->active_iterator = ao2_find(channels, &tmp_chan,
1275                                             OBJ_MULTIPLE | ((!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0)))) {
1276                     ast_free(i);
1277                     return NULL;
1278         }
1279
1280         return i;
1281 }
1282
1283 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1284 {
1285         return channel_iterator_search(NULL, 0, exten, context);
1286 }
1287
1288 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1289 {
1290         return channel_iterator_search(name, name_len, NULL, NULL);
1291 }
1292
1293 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1294 {
1295         struct ast_channel_iterator *i;
1296
1297         if (!(i = ast_calloc(1, sizeof(*i)))) {
1298                 return NULL;
1299         }
1300
1301         i->simple_iterator = ao2_iterator_init(channels, 0);
1302         i->active_iterator = &i->simple_iterator;
1303
1304         return i;
1305 }
1306
1307 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1308 {
1309         return ao2_iterator_next(i->active_iterator);
1310 }
1311
1312 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1313 {
1314         struct ast_channel *chan = obj, *cmp_args = arg;
1315         size_t name_len;
1316         int ret = CMP_MATCH;
1317
1318         /* This is sort of a hack.  Basically, we're using an arbitrary field
1319          * in ast_channel to pass the name_len for a prefix match.  If this
1320          * gets changed, then the uses of ao2_find() must be changed, too. */
1321         name_len = cmp_args->rings;
1322
1323         ast_channel_lock(chan);
1324
1325         if (!ast_strlen_zero(cmp_args->name)) { /* match by name */
1326                 if ((!name_len && strcasecmp(chan->name, cmp_args->name)) ||
1327                                 (name_len && strncasecmp(chan->name, cmp_args->name, name_len))) {
1328                         ret = 0; /* name match failed */
1329                 }
1330         } else if (!ast_strlen_zero(cmp_args->exten)) {
1331                 if (cmp_args->context && strcasecmp(chan->context, cmp_args->context) &&
1332                                 strcasecmp(chan->macrocontext, cmp_args->context)) {
1333                         ret = 0; /* context match failed */
1334                 }
1335                 if (ret && strcasecmp(chan->exten, cmp_args->exten) &&
1336                                 strcasecmp(chan->macroexten, cmp_args->exten)) {
1337                         ret = 0; /* exten match failed */
1338                 }
1339         } else if (!ast_strlen_zero(cmp_args->uniqueid)) {
1340                 if ((!name_len && strcasecmp(chan->uniqueid, cmp_args->uniqueid)) ||
1341                                 (name_len && strncasecmp(chan->uniqueid, cmp_args->uniqueid, name_len))) {
1342                         ret = 0; /* uniqueid match failed */
1343                 }
1344         } else {
1345                 ret = 0;
1346         }
1347
1348         ast_channel_unlock(chan);
1349
1350         return ret;
1351 }
1352
1353 static struct ast_channel *ast_channel_get_full(const char *name, size_t name_len,
1354                                                 const char *exten, const char *context)
1355 {
1356         struct ast_channel tmp_chan = {
1357                 .name = name,
1358                 /* This is sort of a hack.  Basically, we're using an arbitrary field
1359                  * in ast_channel to pass the name_len for a prefix match.  If this
1360                  * gets changed, then the compare callback must be changed, too. */
1361                 .rings = name_len,
1362         };
1363         struct ast_channel *chan;
1364
1365         if (exten) {
1366                 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1367         }
1368
1369         if (context) {
1370                 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1371         }
1372
1373         if ((chan = ao2_find(channels, &tmp_chan,
1374                              (!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0))) {
1375                 return chan;
1376         }
1377
1378         if (!name) {
1379                 return NULL;
1380         }
1381
1382         /* If name was specified, but the result was NULL, 
1383          * try a search on uniqueid, instead. */
1384
1385         {
1386                 struct ast_channel tmp_chan2 = {
1387                         .uniqueid = name,
1388                         .rings = name_len,
1389                 };
1390
1391                 return ao2_find(channels, &tmp_chan2, 0);
1392         }
1393 }
1394
1395 struct ast_channel *ast_channel_get_by_name(const char *name)
1396 {
1397         return ast_channel_get_full(name, 0, NULL, NULL);
1398 }
1399
1400 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1401 {
1402         return ast_channel_get_full(name, name_len, NULL, NULL);
1403 }
1404
1405 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1406 {
1407         return ast_channel_get_full(NULL, 0, exten, context);
1408 }
1409
1410 /*! \brief Wait, look for hangups and condition arg */
1411 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1412 {
1413         struct ast_frame *f;
1414
1415         while (ms > 0) {
1416                 if (cond && ((*cond)(data) == 0))
1417                         return 0;
1418                 ms = ast_waitfor(chan, ms);
1419                 if (ms < 0)
1420                         return -1;
1421                 if (ms > 0) {
1422                         f = ast_read(chan);
1423                         if (!f)
1424                                 return -1;
1425                         ast_frfree(f);
1426                 }
1427         }
1428         return 0;
1429 }
1430
1431 /*! \brief Wait, look for hangups */
1432 int ast_safe_sleep(struct ast_channel *chan, int ms)
1433 {
1434         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1435 }
1436
1437 static void free_cid(struct ast_callerid *cid)
1438 {
1439         if (cid->cid_dnid)
1440                 ast_free(cid->cid_dnid);
1441         if (cid->cid_num)
1442                 ast_free(cid->cid_num); 
1443         if (cid->cid_name)
1444                 ast_free(cid->cid_name);        
1445         if (cid->cid_ani)
1446                 ast_free(cid->cid_ani);
1447         if (cid->cid_rdnis)
1448                 ast_free(cid->cid_rdnis);
1449         cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1450         ast_party_subaddress_free(&cid->subaddress);
1451         ast_party_subaddress_free(&cid->dialed_subaddress);
1452 }
1453
1454 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1455 {
1456         /* Safe, even if already unlinked. */
1457         ao2_unlink(channels, chan);
1458         return ast_channel_unref(chan);
1459 }
1460
1461 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1462 {
1463         init->str = NULL;
1464         init->type = 0;
1465         init->odd_even_indicator = 0;
1466         init->valid = 0;
1467 }
1468
1469 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1470 {
1471         if (dest == src) {
1472                 /* Don't copy to self */
1473                 return;
1474         }
1475
1476         if (dest->str) {
1477                 ast_free(dest->str);
1478         }
1479         dest->str = ast_strdup(src->str);
1480         dest->type = src->type;
1481         dest->odd_even_indicator = src->odd_even_indicator;
1482         dest->valid = src->valid;
1483 }
1484
1485 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1486 {
1487         init->str = NULL;
1488         init->type = guide->type;
1489         init->odd_even_indicator = guide->odd_even_indicator;
1490         init->valid = guide->valid;
1491 }
1492
1493 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1494 {
1495         if (dest == src) {
1496                 /* Don't set to self */
1497                 return;
1498         }
1499
1500         if (src->str && src->str != dest->str) {
1501                 if (dest->str) {
1502                         ast_free(dest->str);
1503                 }
1504                 dest->str = ast_strdup(src->str);
1505         }
1506
1507         dest->type = src->type;
1508         dest->odd_even_indicator = src->odd_even_indicator;
1509         dest->valid = src->valid;
1510 }
1511
1512 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1513 {
1514         if (doomed->str) {
1515                 ast_free(doomed->str);
1516                 doomed->str = NULL;
1517         }
1518 }
1519
1520 /*!
1521  * \internal
1522  * \brief Initialize the given party id structure.
1523  *
1524  * \param init Party id structure to initialize.
1525  *
1526  * \return Nothing
1527  */
1528 static void ast_party_id_init(struct ast_party_id *init)
1529 {
1530         init->number = NULL;
1531         init->name = NULL;
1532         init->number_type = 0;  /* Unknown */
1533         init->number_presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1534         ast_party_subaddress_init(&init->subaddress);
1535 }
1536
1537 /*!
1538  * \internal
1539  * \brief Copy the source party id information to the destination party id.
1540  *
1541  * \param dest Destination party id
1542  * \param src Source party id
1543  *
1544  * \return Nothing
1545  */
1546 static void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1547 {
1548         if (dest == src) {
1549                 /* Don't copy to self */
1550                 return;
1551         }
1552
1553         if (dest->number) {
1554                 ast_free(dest->number);
1555         }
1556         dest->number = ast_strdup(src->number);
1557
1558         if (dest->name) {
1559                 ast_free(dest->name);
1560         }
1561         dest->name = ast_strdup(src->name);
1562
1563         dest->number_type = src->number_type;
1564         dest->number_presentation = src->number_presentation;
1565         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1566 }
1567
1568 /*!
1569  * \internal
1570  * \brief Initialize the given party id structure using the given guide
1571  * for a set update operation.
1572  *
1573  * \details
1574  * The initialization is needed to allow a set operation to know if a
1575  * value needs to be updated.  Simple integers need the guide's original
1576  * value in case the set operation is not trying to set a new value.
1577  * String values are simply set to NULL pointers if they are not going
1578  * to be updated.
1579  *
1580  * \param init Party id structure to initialize.
1581  * \param guide Source party id to use as a guide in initializing.
1582  *
1583  * \return Nothing
1584  */
1585 static void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1586 {
1587         init->number = NULL;
1588         init->name = NULL;
1589         init->number_type = guide->number_type;
1590         init->number_presentation = guide->number_presentation;
1591         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1592 }
1593
1594 /*!
1595  * \internal
1596  * \brief Set the source party id information into the destination party id.
1597  *
1598  * \param dest Destination party id
1599  * \param src Source party id
1600  *
1601  * \return Nothing
1602  */
1603 static void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src)
1604 {
1605         if (dest == src) {
1606                 /* Don't set to self */
1607                 return;
1608         }
1609
1610         if (src->name && src->name != dest->name) {
1611                 if (dest->name) {
1612                         ast_free(dest->name);
1613                 }
1614                 dest->name = ast_strdup(src->name);
1615         }
1616
1617         if (src->number && src->number != dest->number) {
1618                 if (dest->number) {
1619                         ast_free(dest->number);
1620                 }
1621                 dest->number = ast_strdup(src->number);
1622         }
1623
1624         dest->number_type = src->number_type;
1625         dest->number_presentation = src->number_presentation;
1626         ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1627 }
1628
1629 /*!
1630  * \internal
1631  * \brief Destroy the party id contents
1632  *
1633  * \param doomed The party id to destroy.
1634  *
1635  * \return Nothing
1636  */
1637 static void ast_party_id_free(struct ast_party_id *doomed)
1638 {
1639         if (doomed->number) {
1640                 ast_free(doomed->number);
1641                 doomed->number = NULL;
1642         }
1643
1644         if (doomed->name) {
1645                 ast_free(doomed->name);
1646                 doomed->name = NULL;
1647         }
1648         ast_party_subaddress_free(&doomed->subaddress);
1649 }
1650
1651 void ast_party_caller_init(struct ast_party_caller *init)
1652 {
1653         ast_party_id_init(&init->id);
1654         init->ani = NULL;
1655         init->ani2 = 0;
1656 }
1657
1658 void ast_party_caller_copy(struct ast_callerid *dest, const struct ast_callerid *src)
1659 {
1660         if (dest == src) {
1661                 /* Don't copy to self */
1662                 return;
1663         }
1664
1665 #if 1
1666         /* Copy caller-id specific information ONLY from struct ast_callerid */
1667         if (dest->cid_num)
1668         {
1669                 ast_free(dest->cid_num);
1670         }
1671         dest->cid_num = ast_strdup(src->cid_num);
1672
1673         if (dest->cid_name)
1674         {
1675                 ast_free(dest->cid_name);
1676         }
1677         dest->cid_name = ast_strdup(src->cid_name);
1678
1679         dest->cid_ton = src->cid_ton;
1680         dest->cid_pres = src->cid_pres;
1681
1682
1683         if (dest->cid_ani)
1684         {
1685                 ast_free(dest->cid_ani);
1686         }
1687         dest->cid_ani = ast_strdup(src->cid_ani);
1688
1689         dest->cid_ani2 = src->cid_ani2;
1690
1691         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1692
1693 #else
1694
1695         /* The src and dest parameter types will become struct ast_party_caller ptrs. */
1696         /* This is future code */
1697
1698         ast_party_id_copy(&dest->id, &src->id);
1699
1700         if (dest->ani) {
1701                 ast_free(dest->ani);
1702         }
1703         dest->ani = ast_strdup(src->ani);
1704
1705         dest->ani2 = src->ani2;
1706 #endif
1707 }
1708
1709 void ast_party_connected_line_init(struct ast_party_connected_line *init)
1710 {
1711         ast_party_id_init(&init->id);
1712         init->ani = NULL;
1713         init->ani2 = 0;
1714         init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
1715 }
1716
1717 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
1718 {
1719         if (dest == src) {
1720                 /* Don't copy to self */
1721                 return;
1722         }
1723
1724         ast_party_id_copy(&dest->id, &src->id);
1725
1726         if (dest->ani) {
1727                 ast_free(dest->ani);
1728         }
1729         dest->ani = ast_strdup(src->ani);
1730
1731         dest->ani2 = src->ani2;
1732         dest->source = src->source;
1733 }
1734
1735 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
1736 {
1737         ast_party_id_set_init(&init->id, &guide->id);
1738         init->ani = NULL;
1739         init->ani2 = guide->ani2;
1740         init->source = guide->source;
1741 }
1742
1743 void ast_party_connected_line_set(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
1744 {
1745         ast_party_id_set(&dest->id, &src->id);
1746
1747         if (src->ani && src->ani != dest->ani) {
1748                 if (dest->ani) {
1749                         ast_free(dest->ani);
1750                 }
1751                 dest->ani = ast_strdup(src->ani);
1752         }
1753
1754         dest->ani2 = src->ani2;
1755         dest->source = src->source;
1756 }
1757
1758 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_callerid *cid)
1759 {
1760         connected->id.number = cid->cid_num;
1761         connected->id.name = cid->cid_name;
1762         connected->id.number_type = cid->cid_ton;
1763         connected->id.number_presentation = cid->cid_pres;
1764         connected->id.subaddress = cid->subaddress;
1765
1766         connected->ani = cid->cid_ani;
1767         connected->ani2 = cid->cid_ani2;
1768         connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
1769 }
1770
1771 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
1772 {
1773         ast_party_id_free(&doomed->id);
1774
1775         if (doomed->ani) {
1776                 ast_free(doomed->ani);
1777                 doomed->ani = NULL;
1778         }
1779 }
1780
1781 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
1782 {
1783         if (dest == src) {
1784                 /* Don't copy to self */
1785                 return;
1786         }
1787
1788         ast_party_id_copy(&dest->from, &src->from);
1789         ast_party_id_copy(&dest->to, &src->to);
1790         dest->count = src->count;
1791         dest->reason = src->reason;
1792 }
1793
1794 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
1795 {
1796         ast_party_id_set_init(&init->from, &guide->from);
1797         ast_party_id_set_init(&init->to, &guide->to);
1798         init->count = guide->count;
1799         init->reason = guide->reason;
1800 }
1801
1802 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
1803 {
1804         ast_party_id_free(&doomed->from);
1805         ast_party_id_free(&doomed->to);
1806 }
1807
1808 /*! \brief Free a channel structure */
1809 static void ast_channel_destructor(void *obj)
1810 {
1811         struct ast_channel *chan = obj;
1812         int fd;
1813 #ifdef HAVE_EPOLL
1814         int i;
1815 #endif
1816         struct ast_var_t *vardata;
1817         struct ast_frame *f;
1818         struct varshead *headp;
1819         struct ast_datastore *datastore = NULL;
1820         char name[AST_CHANNEL_NAME], *dashptr;
1821
1822         headp = &chan->varshead;
1823
1824         ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
1825         ast_cel_check_retire_linkedid(chan);
1826
1827         /* Get rid of each of the data stores on the channel */
1828         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1829                 /* Free the data store */
1830                 ast_datastore_free(datastore);
1831
1832         /* Lock and unlock the channel just to be sure nobody has it locked still
1833            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1834         ast_channel_lock(chan);
1835         ast_channel_unlock(chan);
1836
1837         if (chan->tech_pvt) {
1838                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1839                 ast_free(chan->tech_pvt);
1840         }
1841
1842         if (chan->sched)
1843                 sched_context_destroy(chan->sched);
1844
1845         ast_copy_string(name, chan->name, sizeof(name));
1846         if ((dashptr = strrchr(name, '-'))) {
1847                 *dashptr = '\0';
1848         }
1849
1850         /* Stop monitoring */
1851         if (chan->monitor)
1852                 chan->monitor->stop( chan, 0 );
1853
1854         /* If there is native format music-on-hold state, free it */
1855         if (chan->music_state)
1856                 ast_moh_cleanup(chan);
1857
1858         /* Free translators */
1859         if (chan->readtrans)
1860                 ast_translator_free_path(chan->readtrans);
1861         if (chan->writetrans)
1862                 ast_translator_free_path(chan->writetrans);
1863         if (chan->pbx)
1864                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1865
1866         free_cid(&chan->cid);
1867         ast_party_connected_line_free(&chan->connected);
1868         ast_party_redirecting_free(&chan->redirecting);
1869
1870         /* Close pipes if appropriate */
1871         if ((fd = chan->alertpipe[0]) > -1)
1872                 close(fd);
1873         if ((fd = chan->alertpipe[1]) > -1)
1874                 close(fd);
1875         if (chan->timer) {
1876                 ast_timer_close(chan->timer);
1877         }
1878 #ifdef HAVE_EPOLL
1879         for (i = 0; i < AST_MAX_FDS; i++) {
1880                 if (chan->epfd_data[i])
1881                         free(chan->epfd_data[i]);
1882         }
1883         close(chan->epfd);
1884 #endif
1885         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1886                 ast_frfree(f);
1887         
1888         /* loop over the variables list, freeing all data and deleting list items */
1889         /* no need to lock the list, as the channel is already locked */
1890         
1891         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1892                 ast_var_delete(vardata);
1893
1894         ast_app_group_discard(chan);
1895
1896         /* Destroy the jitterbuffer */
1897         ast_jb_destroy(chan);
1898
1899         if (chan->cdr) {
1900                 ast_cdr_discard(chan->cdr);
1901                 chan->cdr = NULL;
1902         }
1903
1904         if (chan->zone) {
1905                 chan->zone = ast_tone_zone_unref(chan->zone);
1906         }
1907
1908         ast_string_field_free_memory(chan);
1909
1910         /* Queue an unknown state, because, while we know that this particular
1911          * instance is dead, we don't know the state of all other possible
1912          * instances. */
1913         ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, name);
1914 }
1915
1916 /*! \brief Free a dummy channel structure */
1917 static void ast_dummy_channel_destructor(void *obj)
1918 {
1919         struct ast_channel *chan = obj;
1920         struct ast_var_t *vardata;
1921         struct varshead *headp;
1922
1923         headp = &chan->varshead;
1924
1925         free_cid(&chan->cid);
1926
1927         /* loop over the variables list, freeing all data and deleting list items */
1928         /* no need to lock the list, as the channel is already locked */
1929         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1930                 ast_var_delete(vardata);
1931
1932         if (chan->cdr) {
1933                 ast_cdr_discard(chan->cdr);
1934                 chan->cdr = NULL;
1935         }
1936
1937         ast_string_field_free_memory(chan);
1938 }
1939
1940 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1941 {
1942         return ast_datastore_alloc(info, uid);
1943 }
1944
1945 int ast_channel_datastore_free(struct ast_datastore *datastore)
1946 {
1947         return ast_datastore_free(datastore);
1948 }
1949
1950 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1951 {
1952         struct ast_datastore *datastore = NULL, *datastore2;
1953
1954         AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1955                 if (datastore->inheritance > 0) {
1956                         datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
1957                         if (datastore2) {
1958                                 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
1959                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1960                                 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1961                         }
1962                 }
1963         }
1964         return 0;
1965 }
1966
1967 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1968 {
1969         int res = 0;
1970
1971         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1972
1973         return res;
1974 }
1975
1976 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1977 {
1978         return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1979 }
1980
1981 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1982 {
1983         struct ast_datastore *datastore = NULL;
1984         
1985         if (info == NULL)
1986                 return NULL;
1987
1988         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1989                 if (datastore->info != info) {
1990                         continue;
1991                 }
1992
1993                 if (uid == NULL) {
1994                         /* matched by type only */
1995                         break;
1996                 }
1997
1998                 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
1999                         /* Matched by type AND uid */
2000                         break;
2001                 }
2002         }
2003         AST_LIST_TRAVERSE_SAFE_END;
2004
2005         return datastore;
2006 }
2007
2008 /*! Set the file descriptor on the channel */
2009 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2010 {
2011 #ifdef HAVE_EPOLL
2012         struct epoll_event ev;
2013         struct ast_epoll_data *aed = NULL;
2014
2015         if (chan->fds[which] > -1) {
2016                 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2017                 aed = chan->epfd_data[which];
2018         }
2019
2020         /* If this new fd is valid, add it to the epoll */
2021         if (fd > -1) {
2022                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2023                         return;
2024                 
2025                 chan->epfd_data[which] = aed;
2026                 aed->chan = chan;
2027                 aed->which = which;
2028                 
2029                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2030                 ev.data.ptr = aed;
2031                 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2032         } else if (aed) {
2033                 /* We don't have to keep around this epoll data structure now */
2034                 free(aed);
2035                 chan->epfd_data[which] = NULL;
2036         }
2037 #endif
2038         chan->fds[which] = fd;
2039         return;
2040 }
2041
2042 /*! Add a channel to an optimized waitfor */
2043 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2044 {
2045 #ifdef HAVE_EPOLL
2046         struct epoll_event ev;
2047         int i = 0;
2048
2049         if (chan0->epfd == -1)
2050                 return;
2051
2052         /* Iterate through the file descriptors on chan1, adding them to chan0 */
2053         for (i = 0; i < AST_MAX_FDS; i++) {
2054                 if (chan1->fds[i] == -1)
2055                         continue;
2056                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2057                 ev.data.ptr = chan1->epfd_data[i];
2058                 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2059         }
2060
2061 #endif
2062         return;
2063 }
2064
2065 /*! Delete a channel from an optimized waitfor */
2066 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2067 {
2068 #ifdef HAVE_EPOLL
2069         struct epoll_event ev;
2070         int i = 0;
2071
2072         if (chan0->epfd == -1)
2073                 return;
2074
2075         for (i = 0; i < AST_MAX_FDS; i++) {
2076                 if (chan1->fds[i] == -1)
2077                         continue;
2078                 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2079         }
2080
2081 #endif
2082         return;
2083 }
2084
2085 /*! \brief Softly hangup a channel, don't lock */
2086 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2087 {
2088         ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
2089         /* Inform channel driver that we need to be hung up, if it cares */
2090         chan->_softhangup |= cause;
2091         ast_queue_frame(chan, &ast_null_frame);
2092         /* Interrupt any poll call or such */
2093         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2094                 pthread_kill(chan->blocker, SIGURG);
2095         return 0;
2096 }
2097
2098 /*! \brief Softly hangup a channel, lock */
2099 int ast_softhangup(struct ast_channel *chan, int cause)
2100 {
2101         int res;
2102
2103         ast_channel_lock(chan);
2104         res = ast_softhangup_nolock(chan, cause);
2105         ast_channel_unlock(chan);
2106
2107         return res;
2108 }
2109
2110 static void free_translation(struct ast_channel *clonechan)
2111 {
2112         if (clonechan->writetrans)
2113                 ast_translator_free_path(clonechan->writetrans);
2114         if (clonechan->readtrans)
2115                 ast_translator_free_path(clonechan->readtrans);
2116         clonechan->writetrans = NULL;
2117         clonechan->readtrans = NULL;
2118         clonechan->rawwriteformat = clonechan->nativeformats;
2119         clonechan->rawreadformat = clonechan->nativeformats;
2120 }
2121
2122 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2123 {
2124         struct ast_channel *bridge;
2125
2126         ast_channel_lock(chan);
2127         if (force || ast_strlen_zero(chan->hangupsource)) {
2128                 ast_string_field_set(chan, hangupsource, source);
2129         }
2130         bridge = ast_bridged_channel(chan);
2131         ast_channel_unlock(chan);
2132
2133         if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
2134                 ast_channel_lock(bridge);
2135                 ast_string_field_set(chan, hangupsource, source);
2136                 ast_channel_unlock(bridge);
2137         }
2138 }
2139
2140 /*! \brief Hangup a channel */
2141 int ast_hangup(struct ast_channel *chan)
2142 {
2143         int res = 0;
2144         char extra_str[64]; /* used for cel logging below */
2145
2146         /* Don't actually hang up a channel that will masquerade as someone else, or
2147            if someone is going to masquerade as us */
2148         ast_channel_lock(chan);
2149
2150         if (chan->audiohooks) {
2151                 ast_audiohook_detach_list(chan->audiohooks);
2152                 chan->audiohooks = NULL;
2153         }
2154
2155         ast_autoservice_stop(chan);
2156
2157         if (chan->masq) {
2158                 ast_channel_unlock(chan);
2159                 if (ast_do_masquerade(chan)) {
2160                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2161                 }
2162                 ast_channel_lock(chan);
2163         }
2164
2165         if (chan->masq) {
2166                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
2167                 ast_channel_unlock(chan);
2168                 return 0;
2169         }
2170         /* If this channel is one which will be masqueraded into something,
2171            mark it as a zombie already, so we know to free it later */
2172         if (chan->masqr) {
2173                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2174                 ast_channel_unlock(chan);
2175                 return 0;
2176         }
2177         ast_channel_unlock(chan);
2178
2179         ao2_unlink(channels, chan);
2180
2181         ast_channel_lock(chan);
2182         free_translation(chan);
2183         /* Close audio stream */
2184         if (chan->stream) {
2185                 ast_closestream(chan->stream);
2186                 chan->stream = NULL;
2187         }
2188         /* Close video stream */
2189         if (chan->vstream) {
2190                 ast_closestream(chan->vstream);
2191                 chan->vstream = NULL;
2192         }
2193         if (chan->sched) {
2194                 sched_context_destroy(chan->sched);
2195                 chan->sched = NULL;
2196         }
2197
2198         if (chan->generatordata)        /* Clear any tone stuff remaining */
2199                 if (chan->generator && chan->generator->release)
2200                         chan->generator->release(chan, chan->generatordata);
2201         chan->generatordata = NULL;
2202         chan->generator = NULL;
2203
2204         snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2205         ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2206
2207         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2208                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2209                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
2210                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
2211                 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2212         }
2213         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
2214                 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
2215                 if (chan->tech->hangup)
2216                         res = chan->tech->hangup(chan);
2217         } else {
2218                 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
2219         }
2220                         
2221         ast_channel_unlock(chan);
2222         ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2223                         "Channel: %s\r\n"
2224                         "Uniqueid: %s\r\n"
2225                         "CallerIDNum: %s\r\n"
2226                         "CallerIDName: %s\r\n"
2227                         "Cause: %d\r\n"
2228                         "Cause-txt: %s\r\n",
2229                         chan->name,
2230                         chan->uniqueid,
2231                         S_OR(chan->cid.cid_num, "<unknown>"),
2232                         S_OR(chan->cid.cid_name, "<unknown>"),
2233                         chan->hangupcause,
2234                         ast_cause2str(chan->hangupcause)
2235                         );
2236
2237         if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) && 
2238                 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) && 
2239             (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2240                 ast_channel_lock(chan);
2241                         
2242                 ast_cdr_end(chan->cdr);
2243                 ast_cdr_detach(chan->cdr);
2244                 chan->cdr = NULL;
2245                 ast_channel_unlock(chan);
2246         }
2247
2248         chan = ast_channel_release(chan);
2249
2250         return res;
2251 }
2252
2253 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2254 {
2255         int res = 0;
2256
2257         ast_channel_lock(chan);
2258
2259         /* You can't answer an outbound call */
2260         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2261                 ast_channel_unlock(chan);
2262                 return 0;
2263         }
2264
2265         /* Stop if we're a zombie or need a soft hangup */
2266         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2267                 ast_channel_unlock(chan);
2268                 return -1;
2269         }
2270
2271         ast_channel_unlock(chan);
2272
2273         switch (chan->_state) {
2274         case AST_STATE_RINGING:
2275         case AST_STATE_RING:
2276                 ast_channel_lock(chan);
2277                 if (chan->tech->answer) {
2278                         res = chan->tech->answer(chan);
2279                 }
2280                 ast_setstate(chan, AST_STATE_UP);
2281                 if (cdr_answer) {
2282                         ast_cdr_answer(chan->cdr);
2283                 }
2284                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2285                 ast_channel_unlock(chan);
2286                 break;
2287         case AST_STATE_UP:
2288                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2289                 /* Calling ast_cdr_answer when it it has previously been called
2290                  * is essentially a no-op, so it is safe.
2291                  */
2292                 if (cdr_answer) {
2293                         ast_cdr_answer(chan->cdr);
2294                 }
2295                 break;
2296         default:
2297                 break;
2298         }
2299
2300         ast_indicate(chan, -1);
2301         chan->visible_indication = 0;
2302
2303         return res;
2304 }
2305
2306 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2307 {
2308         int res = 0;
2309         enum ast_channel_state old_state;
2310
2311         old_state = chan->_state;
2312         if ((res = ast_raw_answer(chan, cdr_answer))) {
2313                 return res;
2314         }
2315
2316         switch (old_state) {
2317         case AST_STATE_RINGING:
2318         case AST_STATE_RING:
2319                 /* wait for media to start flowing, but don't wait any longer
2320                  * than 'delay' or 500 milliseconds, whichever is longer
2321                  */
2322                 do {
2323                         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2324                         struct ast_frame *cur, *new;
2325                         int ms = MAX(delay, 500);
2326                         unsigned int done = 0;
2327
2328                         AST_LIST_HEAD_INIT_NOLOCK(&frames);
2329
2330                         for (;;) {
2331                                 ms = ast_waitfor(chan, ms);
2332                                 if (ms < 0) {
2333                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
2334                                         res = -1;
2335                                         break;
2336                                 }
2337                                 if (ms == 0) {
2338                                         ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
2339                                         break;
2340                                 }
2341                                 cur = ast_read(chan);
2342                                 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2343                                              (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2344                                         if (cur) {
2345                                                 ast_frfree(cur);
2346                                         }
2347                                         res = -1;
2348                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
2349                                         break;
2350                                 }
2351
2352                                 if ((new = ast_frisolate(cur)) != cur) {
2353                                         ast_frfree(cur);
2354                                 }
2355
2356                                 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2357
2358                                 /* if a specific delay period was requested, continue
2359                                  * until that delay has passed. don't stop just because
2360                                  * incoming media has arrived.
2361                                  */
2362                                 if (delay) {
2363                                         continue;
2364                                 }
2365
2366                                 switch (new->frametype) {
2367                                         /* all of these frametypes qualify as 'media' */
2368                                 case AST_FRAME_VOICE:
2369                                 case AST_FRAME_VIDEO:
2370                                 case AST_FRAME_TEXT:
2371                                 case AST_FRAME_DTMF_BEGIN:
2372                                 case AST_FRAME_DTMF_END:
2373                                 case AST_FRAME_IMAGE:
2374                                 case AST_FRAME_HTML:
2375                                 case AST_FRAME_MODEM:
2376                                         done = 1;
2377                                         break;
2378                                 case AST_FRAME_CONTROL:
2379                                 case AST_FRAME_IAX:
2380                                 case AST_FRAME_NULL:
2381                                 case AST_FRAME_CNG:
2382                                         break;
2383                                 }
2384
2385                                 if (done) {
2386                                         break;
2387                                 }
2388                         }
2389
2390                         if (res == 0) {
2391                                 ast_channel_lock(chan);
2392                                 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2393                                         ast_queue_frame_head(chan, cur);
2394                                         ast_frfree(cur);
2395                                 }
2396                                 ast_channel_unlock(chan);
2397                         }
2398                 } while (0);
2399                 break;
2400         default:
2401                 break;
2402         }
2403
2404         return res;
2405 }
2406
2407 int ast_answer(struct ast_channel *chan)
2408 {
2409         return __ast_answer(chan, 0, 1);
2410 }
2411
2412 void ast_deactivate_generator(struct ast_channel *chan)
2413 {
2414         ast_channel_lock(chan);
2415         if (chan->generatordata) {
2416                 if (chan->generator && chan->generator->release)
2417                         chan->generator->release(chan, chan->generatordata);
2418                 chan->generatordata = NULL;
2419                 chan->generator = NULL;
2420                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2421                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2422                 ast_settimeout(chan, 0, NULL, NULL);
2423         }
2424         ast_channel_unlock(chan);
2425 }
2426
2427 static int generator_force(const void *data)
2428 {
2429         /* Called if generator doesn't have data */
2430         void *tmp;
2431         int res;
2432         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2433         struct ast_channel *chan = (struct ast_channel *)data;
2434
2435         ast_channel_lock(chan);
2436         tmp = chan->generatordata;
2437         chan->generatordata = NULL;
2438         if (chan->generator)
2439                 generate = chan->generator->generate;
2440         ast_channel_unlock(chan);
2441
2442         if (!tmp || !generate)
2443                 return 0;
2444
2445         res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
2446
2447         chan->generatordata = tmp;
2448
2449         if (res) {
2450                 ast_debug(1, "Auto-deactivating generator\n");
2451                 ast_deactivate_generator(chan);
2452         }
2453
2454         return 0;
2455 }
2456
2457 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2458 {
2459         int res = 0;
2460
2461         ast_channel_lock(chan);
2462
2463         if (chan->generatordata) {
2464                 if (chan->generator && chan->generator->release)
2465                         chan->generator->release(chan, chan->generatordata);
2466                 chan->generatordata = NULL;
2467         }
2468
2469         ast_prod(chan);
2470         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2471                 res = -1;
2472         }
2473         
2474         if (!res) {
2475                 ast_settimeout(chan, 50, generator_force, chan);
2476                 chan->generator = gen;
2477         }
2478
2479         ast_channel_unlock(chan);
2480
2481         return res;
2482 }
2483
2484 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
2485 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2486 {
2487         int winner = -1;
2488         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2489         return winner;
2490 }
2491
2492 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
2493 #ifdef HAVE_EPOLL
2494 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2495                                         int *exception, int *outfd, int *ms)
2496 #else
2497 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2498                                         int *exception, int *outfd, int *ms)
2499 #endif
2500 {
2501         struct timeval start = { 0 , 0 };
2502         struct pollfd *pfds = NULL;
2503         int res;
2504         long rms;
2505         int x, y, max;
2506         int sz;
2507         struct timeval now = { 0, 0 };
2508         struct timeval whentohangup = { 0, 0 }, diff;
2509         struct ast_channel *winner = NULL;
2510         struct fdmap {
2511                 int chan;
2512                 int fdno;
2513         } *fdmap = NULL;
2514
2515         if ((sz = n * AST_MAX_FDS + nfds)) {
2516                 pfds = alloca(sizeof(*pfds) * sz);
2517                 fdmap = alloca(sizeof(*fdmap) * sz);
2518         }
2519
2520         if (outfd)
2521                 *outfd = -99999;
2522         if (exception)
2523                 *exception = 0;
2524         
2525         /* Perform any pending masquerades */
2526         for (x = 0; x < n; x++) {
2527                 if (c[x]->masq && ast_do_masquerade(c[x])) {
2528                         ast_log(LOG_WARNING, "Masquerade failed\n");
2529                         *ms = -1;
2530                         return NULL;
2531                 }
2532
2533                 ast_channel_lock(c[x]);
2534                 if (!ast_tvzero(c[x]->whentohangup)) {
2535                         if (ast_tvzero(whentohangup))
2536                                 now = ast_tvnow();
2537                         diff = ast_tvsub(c[x]->whentohangup, now);
2538                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
2539                                 /* Should already be hungup */
2540                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2541                                 ast_channel_unlock(c[x]);
2542                                 return c[x];
2543                         }
2544                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
2545                                 whentohangup = diff;
2546                 }
2547                 ast_channel_unlock(c[x]);
2548         }
2549         /* Wait full interval */
2550         rms = *ms;
2551         if (!ast_tvzero(whentohangup)) {
2552                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
2553                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
2554                         rms =  *ms;
2555         }
2556         /*
2557          * Build the pollfd array, putting the channels' fds first,
2558          * followed by individual fds. Order is important because
2559          * individual fd's must have priority over channel fds.
2560          */
2561         max = 0;
2562         for (x = 0; x < n; x++) {
2563                 for (y = 0; y < AST_MAX_FDS; y++) {
2564                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
2565                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
2566                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
2567                 }
2568                 CHECK_BLOCKING(c[x]);
2569         }
2570         /* Add the individual fds */
2571         for (x = 0; x < nfds; x++) {
2572                 fdmap[max].chan = -1;
2573                 max += ast_add_fd(&pfds[max], fds[x]);
2574         }
2575
2576         if (*ms > 0)
2577                 start = ast_tvnow();
2578         
2579         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
2580                 do {
2581                         int kbrms = rms;
2582                         if (kbrms > 600000)
2583                                 kbrms = 600000;
2584                         res = ast_poll(pfds, max, kbrms);
2585                         if (!res)
2586                                 rms -= kbrms;
2587                 } while (!res && (rms > 0));
2588         } else {
2589                 res = ast_poll(pfds, max, rms);
2590         }
2591         for (x = 0; x < n; x++)
2592                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
2593         if (res < 0) { /* Simulate a timeout if we were interrupted */
2594                 if (errno != EINTR)
2595                         *ms = -1;
2596                 return NULL;
2597         }
2598         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
2599                 now = ast_tvnow();
2600                 for (x = 0; x < n; x++) {
2601                         if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
2602                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2603                                 if (winner == NULL)
2604                                         winner = c[x];
2605                         }
2606                 }
2607         }
2608         if (res == 0) { /* no fd ready, reset timeout and done */
2609                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
2610                 return winner;
2611         }
2612         /*
2613          * Then check if any channel or fd has a pending event.
2614          * Remember to check channels first and fds last, as they
2615          * must have priority on setting 'winner'
2616          */
2617         for (x = 0; x < max; x++) {
2618                 res = pfds[x].revents;
2619                 if (res == 0)
2620                         continue;
2621                 if (fdmap[x].chan >= 0) {       /* this is a channel */
2622                         winner = c[fdmap[x].chan];      /* override previous winners */
2623                         if (res & POLLPRI)
2624                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
2625                         else
2626                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2627                         winner->fdno = fdmap[x].fdno;
2628                 } else {                        /* this is an fd */
2629                         if (outfd)
2630                                 *outfd = pfds[x].fd;
2631                         if (exception)
2632                                 *exception = (res & POLLPRI) ? -1 : 0;
2633                         winner = NULL;
2634                 }
2635         }
2636         if (*ms > 0) {
2637                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2638                 if (*ms < 0)
2639                         *ms = 0;
2640         }
2641         return winner;
2642 }
2643
2644 #ifdef HAVE_EPOLL
2645 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
2646 {
2647         struct timeval start = { 0 , 0 };
2648         int res = 0;
2649         struct epoll_event ev[1];
2650         long diff, rms = *ms;
2651         struct ast_channel *winner = NULL;
2652         struct ast_epoll_data *aed = NULL;
2653
2654
2655         /* See if this channel needs to be masqueraded */
2656         if (chan->masq && ast_do_masquerade(chan)) {
2657                 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
2658                 *ms = -1;
2659                 return NULL;
2660         }
2661
2662         ast_channel_lock(chan);
2663         /* Figure out their timeout */
2664         if (!ast_tvzero(chan->whentohangup)) {
2665                 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
2666                         /* They should already be hungup! */
2667                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2668                         ast_channel_unlock(chan);
2669                         return NULL;
2670                 }
2671                 /* If this value is smaller then the current one... make it priority */
2672                 if (rms > diff)
2673                         rms = diff;
2674         }
2675
2676         ast_channel_unlock(chan);
2677
2678         /* Time to make this channel block... */
2679         CHECK_BLOCKING(chan);
2680
2681         if (*ms > 0)
2682                 start = ast_tvnow();
2683
2684         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
2685         res = epoll_wait(chan->epfd, ev, 1, rms);
2686
2687         /* Stop blocking */
2688         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2689
2690         /* Simulate a timeout if we were interrupted */
2691         if (res < 0) {
2692                 if (errno != EINTR)
2693                         *ms = -1;
2694                 return NULL;
2695         }
2696
2697         /* If this channel has a timeout see if it expired */
2698         if (!ast_tvzero(chan->whentohangup)) {
2699                 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
2700                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2701                         winner = chan;
2702                 }
2703         }
2704
2705         /* No fd ready, reset timeout and be done for now */
2706         if (!res) {
2707                 *ms = 0;
2708                 return winner;
2709         }
2710
2711         /* See what events are pending */
2712         aed = ev[0].data.ptr;
2713         chan->fdno = aed->which;
2714         if (ev[0].events & EPOLLPRI)
2715                 ast_set_flag(chan, AST_FLAG_EXCEPTION);
2716         else
2717                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2718
2719         if (*ms > 0) {
2720                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2721                 if (*ms < 0)
2722                         *ms = 0;
2723         }
2724
2725         return chan;
2726 }
2727
2728 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2729 {
2730         struct timeval start = { 0 , 0 };
2731         int res = 0, i;
2732         struct epoll_event ev[25] = { { 0, } };
2733         struct timeval now = { 0, 0 };
2734         long whentohangup = 0, diff = 0, rms = *ms;
2735         struct ast_channel *winner = NULL;
2736
2737         for (i = 0; i < n; i++) {
2738                 if (c[i]->masq && ast_do_masquerade(c[i])) {
2739                         ast_log(LOG_WARNING, "Masquerade failed\n");
2740                         *ms = -1;
2741                         return NULL;
2742                 }
2743
2744                 ast_channel_lock(c[i]);
2745                 if (!ast_tvzero(c[i]->whentohangup)) {
2746                         if (whentohangup == 0)
2747                                 now = ast_tvnow();
2748                         if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
2749                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2750                                 ast_channel_unlock(c[i]);
2751                                 return c[i];
2752                         }
2753                         if (!whentohangup || whentohangup > diff)
2754                                 whentohangup = diff;
2755                 }
2756                 ast_channel_unlock(c[i]);
2757                 CHECK_BLOCKING(c[i]);
2758         }
2759
2760         rms = *ms;
2761         if (whentohangup) {
2762                 rms = whentohangup;
2763                 if (*ms >= 0 && *ms < rms)
2764                         rms = *ms;
2765         }
2766
2767         if (*ms > 0)
2768                 start = ast_tvnow();
2769
2770         res = epoll_wait(c[0]->epfd, ev, 25, rms);
2771
2772         for (i = 0; i < n; i++)
2773                 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2774
2775         if (res < 0) {
2776                 if (errno != EINTR)
2777                         *ms = -1;
2778                 return NULL;
2779         }
2780
2781         if (whentohangup) {
2782                 now = ast_tvnow();
2783                 for (i = 0; i < n; i++) {
2784                         if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
2785                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2786                                 if (!winner)
2787                                         winner = c[i];
2788                         }
2789                 }
2790         }
2791
2792         if (!res) {
2793                 *ms = 0;
2794                 return winner;
2795         }
2796
2797         for (i = 0; i < res; i++) {
2798                 struct ast_epoll_data *aed = ev[i].data.ptr;
2799
2800                 if (!ev[i].events || !aed)
2801                         continue;
2802
2803                 winner = aed->chan;
2804                 if (ev[i].events & EPOLLPRI)
2805                         ast_set_flag(winner, AST_FLAG_EXCEPTION);
2806                 else
2807                         ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2808                 winner->fdno = aed->which;
2809         }
2810
2811         if (*ms > 0) {
2812                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2813                 if (*ms < 0)
2814                         *ms = 0;
2815         }
2816
2817         return winner;
2818 }
2819
2820 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2821                                         int *exception, int *outfd, int *ms)
2822 {
2823         /* Clear all provided values in one place. */
2824         if (outfd)
2825                 *outfd = -99999;
2826         if (exception)
2827                 *exception = 0;
2828
2829         /* If no epoll file descriptor is available resort to classic nandfds */
2830         if (!n || nfds || c[0]->epfd == -1)
2831                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2832         else if (!nfds && n == 1)
2833                 return ast_waitfor_nandfds_simple(c[0], ms);
2834         else
2835                 return ast_waitfor_nandfds_complex(c, n, ms);
2836 }
2837 #endif
2838
2839 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2840 {
2841         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2842 }
2843
2844 int ast_waitfor(struct ast_channel *c, int ms)
2845 {
2846         int oldms = ms; /* -1 if no timeout */
2847
2848         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2849         if ((ms < 0) && (oldms < 0))
2850                 ms = 0;
2851         return ms;
2852 }
2853
2854 /* XXX never to be called with ms = -1 */
2855 int ast_waitfordigit(struct ast_channel *c, int ms)
2856 {
2857         return ast_waitfordigit_full(c, ms, -1, -1);
2858 }
2859
2860 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
2861 {
2862         int res;
2863         unsigned int real_rate = rate, max_rate;
2864
2865         ast_channel_lock(c);
2866
2867         if (c->timingfd == -1) {
2868                 ast_channel_unlock(c);
2869                 return -1;
2870         }
2871
2872         if (!func) {
2873                 rate = 0;
2874                 data = NULL;
2875         }
2876
2877         if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
2878                 real_rate = max_rate;
2879         }
2880
2881         ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
2882
2883         res = ast_timer_set_rate(c->timer, real_rate);
2884
2885         c->timingfunc = func;
2886         c->timingdata = data;
2887
2888         ast_channel_unlock(c);
2889
2890         return res;
2891 }
2892
2893 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2894 {
2895         /* Stop if we're a zombie or need a soft hangup */
2896         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2897                 return -1;
2898
2899         /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2900         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2901
2902         /* Wait for a digit, no more than ms milliseconds total. */
2903         
2904         while (ms) {
2905                 struct ast_channel *rchan;
2906                 int outfd=-1;
2907
2908                 errno = 0;
2909                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2910                 
2911                 if (!rchan && outfd < 0 && ms) {
2912                         if (errno == 0 || errno == EINTR)
2913                                 continue;
2914                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2915                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2916                         return -1;
2917                 } else if (outfd > -1) {
2918                         /* The FD we were watching has something waiting */
2919                         ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2920                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2921                         return 1;
2922                 } else if (rchan) {
2923                         int res;
2924                         struct ast_frame *f = ast_read(c);
2925                         if (!f)
2926                                 return -1;
2927
2928                         switch (f->frametype) {
2929                         case AST_FRAME_DTMF_BEGIN:
2930                                 break;
2931                         case AST_FRAME_DTMF_END:
2932                                 res = f->subclass.integer;
2933                                 ast_frfree(f);
2934                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2935                                 return res;
2936                         case AST_FRAME_CONTROL:
2937                                 switch (f->subclass.integer) {
2938                                 case AST_CONTROL_HANGUP:
2939                                         ast_frfree(f);
2940                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2941                                         return -1;
2942                                 case AST_CONTROL_RINGING:
2943                                 case AST_CONTROL_ANSWER:
2944                                 case AST_CONTROL_SRCUPDATE:
2945                                 case AST_CONTROL_CONNECTED_LINE:
2946                                 case AST_CONTROL_REDIRECTING:
2947                                         /* Unimportant */
2948                                         break;
2949                                 default:
2950                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
2951                                         break;
2952                                 }
2953                                 break;
2954                         case AST_FRAME_VOICE:
2955                                 /* Write audio if appropriate */
2956                                 if (audiofd > -1) {
2957                                         if (write(audiofd, f->data.ptr, f->datalen) < 0) {
2958                                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
2959                                         }
2960                                 }
2961                         default:
2962                                 /* Ignore */
2963                                 break;
2964                         }
2965                         ast_frfree(f);
2966                 }
2967         }
2968
2969         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2970
2971         return 0; /* Time is up */
2972 }
2973
2974 static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2975 {
2976         ast_manager_event(chan, EVENT_FLAG_DTMF,
2977                         "DTMF",
2978                         "Channel: %s\r\n"
2979                         "Uniqueid: %s\r\n"
2980                         "Digit: %c\r\n"
2981                         "Direction: %s\r\n"
2982                         "Begin: %s\r\n"
2983                         "End: %s\r\n",
2984                         chan->name, chan->uniqueid, digit, direction, begin, end);
2985 }
2986
2987 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2988 {
2989         if (chan->generator && chan->generator->generate && chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2990                 void *tmp = chan->generatordata;
2991                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = chan->generator->generate;
2992                 int res;
2993                 int samples;
2994
2995                 if (chan->timingfunc) {
2996                         ast_debug(1, "Generator got voice, switching to phase locked mode\n");
2997                         ast_settimeout(chan, 0, NULL, NULL);
2998                 }
2999
3000                 chan->generatordata = NULL;     /* reset, to let writes go through */
3001
3002                 if (f->subclass.codec != chan->writeformat) {
3003                         float factor;
3004                         factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass.codec));
3005                         samples = (int) ( ((float) f->samples) * factor );
3006                 } else {
3007                         samples = f->samples;
3008                 }
3009                 
3010                 /* This unlock is here based on two assumptions that hold true at this point in the
3011                  * code. 1) this function is only called from within __ast_read() and 2) all generators
3012                  * call ast_write() in their generate callback.
3013                  *
3014                  * The reason this is added is so that when ast_write is called, the lock that occurs 
3015                  * there will not recursively lock the channel. Doing this will cause intended deadlock 
3016                  * avoidance not to work in deeper functions
3017                  */
3018                 ast_channel_unlock(chan);
3019                 res = generate(chan, tmp, f->datalen, samples);
3020                 ast_channel_lock(chan);
3021                 chan->generatordata = tmp;
3022                 if (res) {
3023                         ast_debug(1, "Auto-deactivating generator\n");
3024                         ast_deactivate_generator(chan);
3025                 }
3026
3027         } else if (f->frametype == AST_FRAME_CNG) {
3028                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
3029                         ast_debug(1, "Generator got CNG, switching to timed mode\n");
3030                         ast_settimeout(chan, 50, generator_force, chan);
3031                 }
3032         }
3033 }
3034
3035 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3036 {
3037         struct ast_frame *fr = &chan->dtmff;
3038
3039         fr->frametype = AST_FRAME_DTMF_END;
3040         fr->subclass.integer = f->subclass.integer;
3041         fr->len = f->len;
3042
3043         /* The only time this function will be called is for a frame that just came
3044          * out of the channel driver.  So, we want to stick it on the tail of the
3045          * readq. */
3046
3047         ast_queue_frame(chan, fr);
3048 }
3049
3050 /*!
3051  * \brief Determine whether or not we should ignore DTMF in the readq
3052  */
3053 static inline int should_skip_dtmf(struct ast_channel *chan)
3054 {
3055         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
3056                 /* We're in the middle of emulating a digit, or DTMF has been
3057                  * explicitly deferred.  Skip this digit, then. */
3058                 return 1;
3059         }
3060                         
3061         if (!ast_tvzero(chan->dtmf_tv) && 
3062                         ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3063                 /* We're not in the middle of a digit, but it hasn't been long enough
3064                  * since the last digit, so we'll have to skip DTMF for now. */
3065                 return 1;
3066         }
3067
3068         return 0;
3069 }
3070
3071 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
3072 {
3073         struct ast_frame *f = NULL;     /* the return value */
3074         int blah;
3075         int prestate;
3076         int cause = 0;
3077
3078         /* this function is very long so make sure there is only one return
3079          * point at the end (there are only two exceptions to this).
3080          */
3081
3082         if (chan->masq) {
3083                 if (ast_do_masquerade(chan))
3084                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
3085                 else
3086                         f =  &ast_null_frame;
3087                 return f;
3088         }
3089
3090         /* if here, no masq has happened, lock the channel and proceed */
3091         ast_channel_lock(chan);
3092
3093         /* Stop if we're a zombie or need a soft hangup */
3094         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
3095                 if (chan->generator)
3096                         ast_deactivate_generator(chan);
3097                 goto done;
3098         }
3099
3100 #ifdef AST_DEVMODE
3101         /* 
3102          * The ast_waitfor() code records which of the channel's file descriptors reported that
3103          * data is available.  In theory, ast_read() should only be called after ast_waitfor()
3104          * reports that a channel has data available for reading.  However, there still may be
3105          * some edge cases throughout the code where ast_read() is called improperly.  This can
3106          * potentially cause problems, so if this is a developer build, make a lot of noise if
3107          * this happens so that it can be addressed. 
3108          */
3109         if (chan->fdno == -1) {
3110                 ast_log(LOG_ERROR, "ast_read() called with no recorded file descriptor.\n");
3111         }
3112 #endif
3113
3114         prestate = chan->_state;
3115
3116         /* Read and ignore anything on the alertpipe, but read only
3117            one sizeof(blah) per frame that we send from it */
3118         if (chan->alertpipe[0] > -1) {
3119                 int flags = fcntl(chan->alertpipe[0], F_GETFL);
3120                 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
3121                  * which immediately causes a deadlock scenario.  Detect and prevent this. */
3122                 if ((flags & O_NONBLOCK) == 0) {
3123                         ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
3124                         if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
3125                                 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
3126                                 f = &ast_null_frame;
3127                                 goto done;
3128                         }
3129                 }
3130                 if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
3131                         if (errno != EINTR && errno != EAGAIN)
3132                                 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
3133                 }
3134         }
3135
3136         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
3137                 enum ast_timer_event res;
3138
3139                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3140
3141                 res = ast_timer_get_event(chan->timer);
3142
3143                 switch (res) {
3144                 case AST_TIMING_EVENT_EXPIRED:
3145                         ast_timer_ack(chan->timer, 1);
3146
3147                         if (chan->timingfunc) {
3148                                 /* save a copy of func/data before unlocking the channel */
3149                                 int (*func)(const void *) = chan->timingfunc;
3150                                 void *data = chan->timingdata;
3151                                 chan->fdno = -1;
3152                                 ast_channel_unlock(chan);
3153                                 func(data);
3154                         } else {
3155                                 ast_timer_set_rate(chan->timer, 0);
3156                                 chan->fdno = -1;
3157                                 ast_channel_unlock(chan);
3158                         }
3159
3160                         /* cannot 'goto done' because the channel is already unlocked */
3161                         return &ast_null_frame;
3162
3163                 case AST_TIMING_EVENT_CONTINUOUS:
3164                         if (AST_LIST_EMPTY(&chan->readq) || 
3165                                 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
3166                                 ast_timer_disable_continuous(chan->timer);
3167                         }
3168                         break;
3169                 }
3170
3171         } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
3172                 /* if the AST_GENERATOR_FD is set, call the generator with args
3173                  * set to -1 so it can do whatever it needs to.
3174                  */
3175                 void *tmp = chan->generatordata;
3176                 chan->generatordata = NULL;     /* reset to let ast_write get through */
3177                 chan->generator->generate(chan, tmp, -1, -1);
3178                 chan->generatordata = tmp;
3179                 f = &ast_null_frame;
3180                 chan->fdno = -1;
3181                 goto done;
3182         }
3183
3184         /* Check for pending read queue */
3185         if (!AST_LIST_EMPTY(&chan->readq)) {
3186                 int skip_dtmf = should_skip_dtmf(chan);
3187
3188                 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
3189                         /* We have to be picky about which frame we pull off of the readq because
3190                          * there are cases where we want to leave DTMF frames on the queue until
3191                          * some later time. */
3192
3193                         if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
3194                                 continue;
3195                         }
3196
3197                         AST_LIST_REMOVE_CURRENT(frame_list);
3198                         break;
3199                 }
3200                 AST_LIST_TRAVERSE_SAFE_END;
3201                 
3202                 if (!f) {
3203                         /* There were no acceptable frames on the readq. */
3204                         f = &ast_null_frame;
3205                         if (chan->alertpipe[0] > -1) {
3206                                 int poke = 0;
3207                                 /* Restore the state of the alertpipe since we aren't ready for any
3208                                  * of the frames in the readq. */
3209                                 if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
3210                                         ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
3211                                 }
3212                         }
3213                 }
3214
3215                 /* Interpret hangup and return NULL */
3216                 /* XXX why not the same for frames from the channel ? */
3217                 if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
3218                         cause = f->data.uint32;
3219                         ast_frfree(f);
3220                         f = NULL;
3221                 }
3222         } else {
3223                 chan->blocker = pthread_self();
3224                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
3225                         if (chan->tech->exception)
3226                                 f = chan->tech->exception(chan);
3227                         else {
3228                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
3229                                 f = &ast_null_frame;
3230                         }
3231                         /* Clear the exception flag */
3232                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3233                 } else if (chan->tech->read)
3234                         f = chan->tech->read(chan);
3235                 else
3236                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
3237         }
3238
3239         /*
3240          * Reset the recorded file descriptor that triggered this read so that we can
3241          * easily detect when ast_read() is called without properly using ast_waitfor().
3242          */
3243         chan->fdno = -1;
3244
3245         if (f) {
3246                 struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
3247
3248                 /* if the channel driver returned more than one frame, stuff the excess
3249                    into the readq for the next ast_read call
3250                 */
3251                 if (AST_LIST_NEXT(f, frame_list)) {
3252                         ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
3253                         ast_frfree(AST_LIST_NEXT(f, frame_list));
3254                         AST_LIST_NEXT(f, frame_list) = NULL;
3255                 }
3256
3257                 switch (f->frametype) {
3258                 case AST_FRAME_CONTROL:
3259                         if (f->subclass.integer == AST_CONTROL_ANSWER) {
3260                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
3261                                         ast_debug(1, "Ignoring answer on an inbound call!\n");
3262                                         ast_frfree(f);
3263                                         f = &ast_null_frame;
3264                                 } else if (prestate == AST_STATE_UP) {
3265                                         ast_debug(1, "Dropping duplicate answer!\n");
3266                                         ast_frfree(f);
3267                                         f = &ast_null_frame;
3268                                 } else {
3269                                         /* Answer the CDR */
3270                                         ast_setstate(chan, AST_STATE_UP);
3271                                         /* removed a call to ast_cdr_answer(chan->cdr) from here. */
3272                                         ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
3273                                 }
3274                         }
3275                         break;
3276                 case AST_FRAME_DTMF_END:
3277                         send_dtmf_event(chan, "Received", f->subclass.integer, "No", "Yes");
3278                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass.integer, chan->name, f->len);
3279                         /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
3280                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
3281                                 queue_dtmf_readq(chan, f);
3282                                 ast_frfree(f);
3283                                 f = &ast_null_frame;
3284                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
3285                      &nbs