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