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