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