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