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