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