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