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