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