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