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