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