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