8d6262521bba170eff15a08f8c83c4720772f1be
[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         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1370         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1371         int res;
1372
1373         /* Yeah, let's not change a lock-critical value without locking */
1374         ast_channel_lock(chan);
1375         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1376         publish_channel_blob(chan, ast_channel_hangup_request_type(), NULL);
1377
1378         res = ast_queue_frame(chan, &f);
1379         ast_channel_unlock(chan);
1380         return res;
1381 }
1382
1383 /*! \brief Queue a hangup frame for channel */
1384 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1385 {
1386         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
1387         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1388         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1389         int res;
1390
1391         if (cause >= 0) {
1392                 f.data.uint32 = cause;
1393         }
1394
1395         /* Yeah, let's not change a lock-critical value without locking */
1396         ast_channel_lock(chan);
1397         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1398         if (cause < 0) {
1399                 f.data.uint32 = ast_channel_hangupcause(chan);
1400         }
1401         blob = ast_json_pack("{s: i}",
1402                              "cause", cause);
1403         publish_channel_blob(chan, ast_channel_hangup_request_type(), blob);
1404
1405         res = ast_queue_frame(chan, &f);
1406         ast_channel_unlock(chan);
1407         return res;
1408 }
1409
1410 int ast_queue_hold(struct ast_channel *chan, const char *musicclass)
1411 {
1412         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
1413         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1414         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HOLD };
1415         int res;
1416
1417         if (!ast_strlen_zero(musicclass)) {
1418                 f.data.ptr = (void *) musicclass;
1419                 f.datalen = strlen(musicclass) + 1;
1420
1421                 blob = ast_json_pack("{s: s}",
1422                                      "musicclass", musicclass);
1423         }
1424
1425         publish_channel_blob(chan, ast_channel_hold_type(), blob);
1426
1427         res = ast_queue_frame(chan, &f);
1428         return res;
1429 }
1430
1431 int ast_queue_unhold(struct ast_channel *chan)
1432 {
1433         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1434         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_UNHOLD };
1435         int res;
1436
1437         publish_channel_blob(chan, ast_channel_unhold_type(), NULL);
1438
1439         res = ast_queue_frame(chan, &f);
1440         return res;
1441 }
1442
1443 /*! \brief Queue a control frame */
1444 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1445 {
1446         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1447         return ast_queue_frame(chan, &f);
1448 }
1449
1450 /*! \brief Queue a control frame with payload */
1451 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1452                            const void *data, size_t datalen)
1453 {
1454         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1455         return ast_queue_frame(chan, &f);
1456 }
1457
1458 /*! \brief Set defer DTMF flag on channel */
1459 int ast_channel_defer_dtmf(struct ast_channel *chan)
1460 {
1461         int pre = 0;
1462
1463         if (chan) {
1464                 pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1465                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1466         }
1467         return pre;
1468 }
1469
1470 /*! \brief Unset defer DTMF flag on channel */
1471 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1472 {
1473         if (chan)
1474                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1475 }
1476
1477 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1478                 void *data, int ao2_flags)
1479 {
1480         return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1481 }
1482
1483 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1484 {
1485         struct ast_channel *chan = obj;
1486         const char *name = arg;
1487         size_t name_len = *(size_t *) data;
1488         int ret = CMP_MATCH;
1489
1490         if (ast_strlen_zero(name)) {
1491                 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1492                 return CMP_STOP;
1493         }
1494
1495         ast_channel_lock(chan);
1496         if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1497                 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1498                 ret = 0; /* name match failed, keep looking */
1499         }
1500         ast_channel_unlock(chan);
1501
1502         return ret;
1503 }
1504
1505 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1506 {
1507         struct ast_channel *chan = obj;
1508         char *context = arg;
1509         char *exten = data;
1510         int ret = CMP_MATCH;
1511
1512         if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1513                 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1514                 return CMP_STOP;
1515         }
1516
1517         ast_channel_lock(chan);
1518         if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1519                 ret = 0; /* Context match failed, continue */
1520         } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1521                 ret = 0; /* Extension match failed, continue */
1522         }
1523         ast_channel_unlock(chan);
1524
1525         return ret;
1526 }
1527
1528 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1529 {
1530         struct ast_channel *chan = obj;
1531         char *uniqueid = arg;
1532         size_t id_len = *(size_t *) data;
1533         int ret = CMP_MATCH;
1534
1535         if (ast_strlen_zero(uniqueid)) {
1536                 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1537                 return CMP_STOP;
1538         }
1539
1540         ast_channel_lock(chan);
1541         if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1542                 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1543                 ret = 0; /* uniqueid match failed, keep looking */
1544         }
1545         ast_channel_unlock(chan);
1546
1547         return ret;
1548 }
1549
1550 struct ast_channel_iterator {
1551         /* storage for non-dynamically allocated iterator */
1552         struct ao2_iterator simple_iterator;
1553         /* pointer to the actual iterator (simple_iterator or a dynamically
1554          * allocated iterator)
1555          */
1556         struct ao2_iterator *active_iterator;
1557 };
1558
1559 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1560 {
1561         ao2_iterator_destroy(i->active_iterator);
1562         ast_free(i);
1563
1564         return NULL;
1565 }
1566
1567 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1568 {
1569         struct ast_channel_iterator *i;
1570         char *l_exten = (char *) exten;
1571         char *l_context = (char *) context;
1572
1573         if (!(i = ast_calloc(1, sizeof(*i)))) {
1574                 return NULL;
1575         }
1576
1577         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1578                 l_context, l_exten, OBJ_MULTIPLE);
1579         if (!i->active_iterator) {
1580                 ast_free(i);
1581                 return NULL;
1582         }
1583
1584         return i;
1585 }
1586
1587 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1588 {
1589         struct ast_channel_iterator *i;
1590         char *l_name = (char *) name;
1591
1592         if (!(i = ast_calloc(1, sizeof(*i)))) {
1593                 return NULL;
1594         }
1595
1596         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1597                 l_name, &name_len,
1598                 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1599         if (!i->active_iterator) {
1600                 ast_free(i);
1601                 return NULL;
1602         }
1603
1604         return i;
1605 }
1606
1607 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1608 {
1609         struct ast_channel_iterator *i;
1610
1611         if (!(i = ast_calloc(1, sizeof(*i)))) {
1612                 return NULL;
1613         }
1614
1615         i->simple_iterator = ao2_iterator_init(channels, 0);
1616         i->active_iterator = &i->simple_iterator;
1617
1618         return i;
1619 }
1620
1621 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1622 {
1623         return ao2_iterator_next(i->active_iterator);
1624 }
1625
1626 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1627 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1628 {
1629         ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1630         return CMP_STOP;
1631 }
1632
1633 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1634 {
1635         struct ast_channel *chan;
1636         char *l_name = (char *) name;
1637
1638         chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1639                 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1640         if (chan) {
1641                 return chan;
1642         }
1643
1644         if (ast_strlen_zero(l_name)) {
1645                 /* We didn't have a name to search for so quit. */
1646                 return NULL;
1647         }
1648
1649         /* Now try a search for uniqueid. */
1650         return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1651 }
1652
1653 struct ast_channel *ast_channel_get_by_name(const char *name)
1654 {
1655         return ast_channel_get_by_name_prefix(name, 0);
1656 }
1657
1658 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1659 {
1660         char *l_exten = (char *) exten;
1661         char *l_context = (char *) context;
1662
1663         return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1664 }
1665
1666 int ast_is_deferrable_frame(const struct ast_frame *frame)
1667 {
1668         /* Do not add a default entry in this switch statement.  Each new
1669          * frame type should be addressed directly as to whether it should
1670          * be queued up or not.
1671          */
1672         switch (frame->frametype) {
1673         case AST_FRAME_BRIDGE_ACTION:
1674         case AST_FRAME_CONTROL:
1675         case AST_FRAME_TEXT:
1676         case AST_FRAME_IMAGE:
1677         case AST_FRAME_HTML:
1678                 return 1;
1679
1680         case AST_FRAME_DTMF_END:
1681         case AST_FRAME_DTMF_BEGIN:
1682         case AST_FRAME_VOICE:
1683         case AST_FRAME_VIDEO:
1684         case AST_FRAME_NULL:
1685         case AST_FRAME_IAX:
1686         case AST_FRAME_CNG:
1687         case AST_FRAME_MODEM:
1688                 return 0;
1689         }
1690         return 0;
1691 }
1692
1693 /*! \brief Wait, look for hangups and condition arg */
1694 int ast_safe_sleep_conditional(struct ast_channel *chan, int timeout_ms, int (*cond)(void*), void *data)
1695 {
1696         struct ast_frame *f;
1697         struct ast_silence_generator *silgen = NULL;
1698         int res = 0;
1699         struct timeval start;
1700         int ms;
1701         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1702
1703         AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1704
1705         /* If no other generator is present, start silencegen while waiting */
1706         if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1707                 silgen = ast_channel_start_silence_generator(chan);
1708         }
1709
1710         start = ast_tvnow();
1711         while ((ms = ast_remaining_ms(start, timeout_ms))) {
1712                 struct ast_frame *dup_f = NULL;
1713
1714                 if (cond && ((*cond)(data) == 0)) {
1715                         break;
1716                 }
1717                 ms = ast_waitfor(chan, ms);
1718                 if (ms < 0) {
1719                         res = -1;
1720                         break;
1721                 }
1722                 if (ms > 0) {
1723                         f = ast_read(chan);
1724                         if (!f) {
1725                                 res = -1;
1726                                 break;
1727                         }
1728
1729                         if (!ast_is_deferrable_frame(f)) {
1730                                 ast_frfree(f);
1731                                 continue;
1732                         }
1733
1734                         if ((dup_f = ast_frisolate(f))) {
1735                                 if (dup_f != f) {
1736                                         ast_frfree(f);
1737                                 }
1738                                 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1739                         }
1740                 }
1741         }
1742
1743         /* stop silgen if present */
1744         if (silgen) {
1745                 ast_channel_stop_silence_generator(chan, silgen);
1746         }
1747
1748         /* We need to free all the deferred frames, but we only need to
1749          * queue the deferred frames if there was no error and no
1750          * hangup was received
1751          */
1752         ast_channel_lock(chan);
1753         while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1754                 if (!res) {
1755                         ast_queue_frame_head(chan, f);
1756                 }
1757                 ast_frfree(f);
1758         }
1759         ast_channel_unlock(chan);
1760
1761         return res;
1762 }
1763
1764 /*! \brief Wait, look for hangups */
1765 int ast_safe_sleep(struct ast_channel *chan, int ms)
1766 {
1767         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1768 }
1769
1770 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1771 {
1772         /* Safe, even if already unlinked. */
1773         ao2_unlink(channels, chan);
1774         return ast_channel_unref(chan);
1775 }
1776
1777 void ast_party_name_init(struct ast_party_name *init)
1778 {
1779         init->str = NULL;
1780         init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1781         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1782         init->valid = 0;
1783 }
1784
1785 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1786 {
1787         if (dest == src) {
1788                 /* Don't copy to self */
1789                 return;
1790         }
1791
1792         ast_free(dest->str);
1793         dest->str = ast_strdup(src->str);
1794         dest->char_set = src->char_set;
1795         dest->presentation = src->presentation;
1796         dest->valid = src->valid;
1797 }
1798
1799 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1800 {
1801         init->str = NULL;
1802         init->char_set = guide->char_set;
1803         init->presentation = guide->presentation;
1804         init->valid = guide->valid;
1805 }
1806
1807 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1808 {
1809         if (dest == src) {
1810                 /* Don't set to self */
1811                 return;
1812         }
1813
1814         if (src->str && src->str != dest->str) {
1815                 ast_free(dest->str);
1816                 dest->str = ast_strdup(src->str);
1817         }
1818
1819         dest->char_set = src->char_set;
1820         dest->presentation = src->presentation;
1821         dest->valid = src->valid;
1822 }
1823
1824 void ast_party_name_free(struct ast_party_name *doomed)
1825 {
1826         ast_free(doomed->str);
1827         doomed->str = NULL;
1828 }
1829
1830 void ast_party_number_init(struct ast_party_number *init)
1831 {
1832         init->str = NULL;
1833         init->plan = 0;/* Unknown */
1834         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1835         init->valid = 0;
1836 }
1837
1838 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1839 {
1840         if (dest == src) {
1841                 /* Don't copy to self */
1842                 return;
1843         }
1844
1845         ast_free(dest->str);
1846         dest->str = ast_strdup(src->str);
1847         dest->plan = src->plan;
1848         dest->presentation = src->presentation;
1849         dest->valid = src->valid;
1850 }
1851
1852 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1853 {
1854         init->str = NULL;
1855         init->plan = guide->plan;
1856         init->presentation = guide->presentation;
1857         init->valid = guide->valid;
1858 }
1859
1860 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1861 {
1862         if (dest == src) {
1863                 /* Don't set to self */
1864                 return;
1865         }
1866
1867         if (src->str && src->str != dest->str) {
1868                 ast_free(dest->str);
1869                 dest->str = ast_strdup(src->str);
1870         }
1871
1872         dest->plan = src->plan;
1873         dest->presentation = src->presentation;
1874         dest->valid = src->valid;
1875 }
1876
1877 void ast_party_number_free(struct ast_party_number *doomed)
1878 {
1879         ast_free(doomed->str);
1880         doomed->str = NULL;
1881 }
1882
1883 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1884 {
1885         init->str = NULL;
1886         init->type = 0;
1887         init->odd_even_indicator = 0;
1888         init->valid = 0;
1889 }
1890
1891 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1892 {
1893         if (dest == src) {
1894                 /* Don't copy to self */
1895                 return;
1896         }
1897
1898         ast_free(dest->str);
1899         dest->str = ast_strdup(src->str);
1900         dest->type = src->type;
1901         dest->odd_even_indicator = src->odd_even_indicator;
1902         dest->valid = src->valid;
1903 }
1904
1905 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1906 {
1907         init->str = NULL;
1908         init->type = guide->type;
1909         init->odd_even_indicator = guide->odd_even_indicator;
1910         init->valid = guide->valid;
1911 }
1912
1913 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1914 {
1915         if (dest == src) {
1916                 /* Don't set to self */
1917                 return;
1918         }
1919
1920         if (src->str && src->str != dest->str) {
1921                 ast_free(dest->str);
1922                 dest->str = ast_strdup(src->str);
1923         }
1924
1925         dest->type = src->type;
1926         dest->odd_even_indicator = src->odd_even_indicator;
1927         dest->valid = src->valid;
1928 }
1929
1930 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1931 {
1932         ast_free(doomed->str);
1933         doomed->str = NULL;
1934 }
1935
1936 void ast_set_party_id_all(struct ast_set_party_id *update_id)
1937 {
1938         update_id->name = 1;
1939         update_id->number = 1;
1940         update_id->subaddress = 1;
1941 }
1942
1943 void ast_party_id_init(struct ast_party_id *init)
1944 {
1945         ast_party_name_init(&init->name);
1946         ast_party_number_init(&init->number);
1947         ast_party_subaddress_init(&init->subaddress);
1948         init->tag = NULL;
1949 }
1950
1951 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1952 {
1953         if (dest == src) {
1954                 /* Don't copy to self */
1955                 return;
1956         }
1957
1958         ast_party_name_copy(&dest->name, &src->name);
1959         ast_party_number_copy(&dest->number, &src->number);
1960         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1961
1962         ast_free(dest->tag);
1963         dest->tag = ast_strdup(src->tag);
1964 }
1965
1966 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1967 {
1968         ast_party_name_set_init(&init->name, &guide->name);
1969         ast_party_number_set_init(&init->number, &guide->number);
1970         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1971         init->tag = NULL;
1972 }
1973
1974 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1975 {
1976         if (dest == src) {
1977                 /* Don't set to self */
1978                 return;
1979         }
1980
1981         if (!update || update->name) {
1982                 ast_party_name_set(&dest->name, &src->name);
1983         }
1984         if (!update || update->number) {
1985                 ast_party_number_set(&dest->number, &src->number);
1986         }
1987         if (!update || update->subaddress) {
1988                 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1989         }
1990
1991         if (src->tag && src->tag != dest->tag) {
1992                 ast_free(dest->tag);
1993                 dest->tag = ast_strdup(src->tag);
1994         }
1995 }
1996
1997 void ast_party_id_free(struct ast_party_id *doomed)
1998 {
1999         ast_party_name_free(&doomed->name);
2000         ast_party_number_free(&doomed->number);
2001         ast_party_subaddress_free(&doomed->subaddress);
2002
2003         ast_free(doomed->tag);
2004         doomed->tag = NULL;
2005 }
2006
2007 int ast_party_id_presentation(const struct ast_party_id *id)
2008 {
2009         int number_priority;
2010         int number_value;
2011         int number_screening;
2012         int name_priority;
2013         int name_value;
2014
2015         /* Determine name presentation priority. */
2016         if (!id->name.valid) {
2017                 name_value = AST_PRES_UNAVAILABLE;
2018                 name_priority = 3;
2019         } else {
2020                 name_value = id->name.presentation & AST_PRES_RESTRICTION;
2021                 switch (name_value) {
2022                 case AST_PRES_RESTRICTED:
2023                         name_priority = 0;
2024                         break;
2025                 case AST_PRES_ALLOWED:
2026                         name_priority = 1;
2027                         break;
2028                 case AST_PRES_UNAVAILABLE:
2029                         name_priority = 2;
2030                         break;
2031                 default:
2032                         name_value = AST_PRES_UNAVAILABLE;
2033                         name_priority = 3;
2034                         break;
2035                 }
2036         }
2037
2038         /* Determine number presentation priority. */
2039         if (!id->number.valid) {
2040                 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2041                 number_value = AST_PRES_UNAVAILABLE;
2042                 number_priority = 3;
2043         } else {
2044                 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
2045                 number_value = id->number.presentation & AST_PRES_RESTRICTION;
2046                 switch (number_value) {
2047                 case AST_PRES_RESTRICTED:
2048                         number_priority = 0;
2049                         break;
2050                 case AST_PRES_ALLOWED:
2051                         number_priority = 1;
2052                         break;
2053                 case AST_PRES_UNAVAILABLE:
2054                         number_priority = 2;
2055                         break;
2056                 default:
2057                         number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2058                         number_value = AST_PRES_UNAVAILABLE;
2059                         number_priority = 3;
2060                         break;
2061                 }
2062         }
2063
2064         /* Select the wining presentation value. */
2065         if (name_priority < number_priority) {
2066                 number_value = name_value;
2067         }
2068         if (number_value == AST_PRES_UNAVAILABLE) {
2069                 return AST_PRES_NUMBER_NOT_AVAILABLE;
2070         }
2071
2072         return number_value | number_screening;
2073 }
2074
2075 void ast_party_id_invalidate(struct ast_party_id *id)
2076 {
2077         id->name.valid = 0;
2078         id->number.valid = 0;
2079         id->subaddress.valid = 0;
2080 }
2081
2082 void ast_party_id_reset(struct ast_party_id *id)
2083 {
2084         ast_party_id_free(id);
2085         ast_party_id_init(id);
2086 }
2087
2088 struct ast_party_id ast_party_id_merge(struct ast_party_id *base, struct ast_party_id *overlay)
2089 {
2090         struct ast_party_id merged;
2091
2092         merged = *base;
2093         if (overlay->name.valid) {
2094                 merged.name = overlay->name;
2095         }
2096         if (overlay->number.valid) {
2097                 merged.number = overlay->number;
2098         }
2099         if (overlay->subaddress.valid) {
2100                 merged.subaddress = overlay->subaddress;
2101         }
2102         /* Note the actual structure is returned and not a pointer to it! */
2103         return merged;
2104 }
2105
2106 void ast_party_id_merge_copy(struct ast_party_id *dest, struct ast_party_id *base, struct ast_party_id *overlay)
2107 {
2108         struct ast_party_id merged;
2109
2110         merged = ast_party_id_merge(base, overlay);
2111         ast_party_id_copy(dest, &merged);
2112 }
2113
2114 void ast_party_dialed_init(struct ast_party_dialed *init)
2115 {
2116         init->number.str = NULL;
2117         init->number.plan = 0;/* Unknown */
2118         ast_party_subaddress_init(&init->subaddress);
2119         init->transit_network_select = 0;
2120 }
2121
2122 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2123 {
2124         if (dest == src) {
2125                 /* Don't copy to self */
2126                 return;
2127         }
2128
2129         ast_free(dest->number.str);
2130         dest->number.str = ast_strdup(src->number.str);
2131         dest->number.plan = src->number.plan;
2132         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2133         dest->transit_network_select = src->transit_network_select;
2134 }
2135
2136 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2137 {
2138         init->number.str = NULL;
2139         init->number.plan = guide->number.plan;
2140         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2141         init->transit_network_select = guide->transit_network_select;
2142 }
2143
2144 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2145 {
2146         if (src->number.str && src->number.str != dest->number.str) {
2147                 ast_free(dest->number.str);
2148                 dest->number.str = ast_strdup(src->number.str);
2149         }
2150         dest->number.plan = src->number.plan;
2151
2152         ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2153
2154         dest->transit_network_select = src->transit_network_select;
2155 }
2156
2157 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2158 {
2159         ast_free(doomed->number.str);
2160         doomed->number.str = NULL;
2161         ast_party_subaddress_free(&doomed->subaddress);
2162 }
2163
2164 void ast_party_caller_init(struct ast_party_caller *init)
2165 {
2166         ast_party_id_init(&init->id);
2167         ast_party_id_init(&init->ani);
2168         ast_party_id_init(&init->priv);
2169         init->ani2 = 0;
2170 }
2171
2172 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2173 {
2174         if (dest == src) {
2175                 /* Don't copy to self */
2176                 return;
2177         }
2178
2179         ast_party_id_copy(&dest->id, &src->id);
2180         ast_party_id_copy(&dest->ani, &src->ani);
2181         ast_party_id_copy(&dest->priv, &src->priv);
2182         dest->ani2 = src->ani2;
2183 }
2184
2185 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2186 {
2187         ast_party_id_set_init(&init->id, &guide->id);
2188         ast_party_id_set_init(&init->ani, &guide->ani);
2189         ast_party_id_set_init(&init->priv, &guide->priv);
2190         init->ani2 = guide->ani2;
2191 }
2192
2193 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2194 {
2195         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2196         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2197         ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2198         dest->ani2 = src->ani2;
2199 }
2200
2201 void ast_party_caller_free(struct ast_party_caller *doomed)
2202 {
2203         ast_party_id_free(&doomed->id);
2204         ast_party_id_free(&doomed->ani);
2205         ast_party_id_free(&doomed->priv);
2206 }
2207
2208 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2209 {
2210         ast_party_id_init(&init->id);
2211         ast_party_id_init(&init->ani);
2212         ast_party_id_init(&init->priv);
2213         init->ani2 = 0;
2214         init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2215 }
2216
2217 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2218 {
2219         if (dest == src) {
2220                 /* Don't copy to self */
2221                 return;
2222         }
2223
2224         ast_party_id_copy(&dest->id, &src->id);
2225         ast_party_id_copy(&dest->ani, &src->ani);
2226         ast_party_id_copy(&dest->priv, &src->priv);
2227         dest->ani2 = src->ani2;
2228         dest->source = src->source;
2229 }
2230
2231 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2232 {
2233         ast_party_id_set_init(&init->id, &guide->id);
2234         ast_party_id_set_init(&init->ani, &guide->ani);
2235         ast_party_id_set_init(&init->priv, &guide->priv);
2236         init->ani2 = guide->ani2;
2237         init->source = guide->source;
2238 }
2239
2240 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)
2241 {
2242         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2243         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2244         ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2245         dest->ani2 = src->ani2;
2246         dest->source = src->source;
2247 }
2248
2249 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2250 {
2251         connected->id = caller->id;
2252         connected->ani = caller->ani;
2253         connected->priv = caller->priv;
2254         connected->ani2 = caller->ani2;
2255         connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2256 }
2257
2258 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2259 {
2260         ast_party_id_free(&doomed->id);
2261         ast_party_id_free(&doomed->ani);
2262         ast_party_id_free(&doomed->priv);
2263 }
2264
2265 void ast_party_redirecting_reason_init(struct ast_party_redirecting_reason *init)
2266 {
2267         init->str = NULL;
2268         init->code = AST_REDIRECTING_REASON_UNKNOWN;
2269 }
2270
2271 void ast_party_redirecting_reason_copy(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2272 {
2273         if (dest == src) {
2274                 return;
2275         }
2276
2277         ast_free(dest->str);
2278         dest->str = ast_strdup(src->str);
2279         dest->code = src->code;
2280 }
2281
2282 void ast_party_redirecting_reason_set_init(struct ast_party_redirecting_reason *init, const struct ast_party_redirecting_reason *guide)
2283 {
2284         init->str = NULL;
2285         init->code = guide->code;
2286 }
2287
2288 void ast_party_redirecting_reason_set(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2289 {
2290         if (dest == src) {
2291                 return;
2292         }
2293
2294         if (src->str && src->str != dest->str) {
2295                 ast_free(dest->str);
2296                 dest->str = ast_strdup(src->str);
2297         }
2298
2299         dest->code = src->code;
2300 }
2301
2302 void ast_party_redirecting_reason_free(struct ast_party_redirecting_reason *doomed)
2303 {
2304         ast_free(doomed->str);
2305 }
2306
2307
2308 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2309 {
2310         ast_party_id_init(&init->orig);
2311         ast_party_id_init(&init->from);
2312         ast_party_id_init(&init->to);
2313         ast_party_id_init(&init->priv_orig);
2314         ast_party_id_init(&init->priv_from);
2315         ast_party_id_init(&init->priv_to);
2316         ast_party_redirecting_reason_init(&init->reason);
2317         ast_party_redirecting_reason_init(&init->orig_reason);
2318         init->count = 0;
2319 }
2320
2321 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2322 {
2323         if (dest == src) {
2324                 /* Don't copy to self */
2325                 return;
2326         }
2327
2328         ast_party_id_copy(&dest->orig, &src->orig);
2329         ast_party_id_copy(&dest->from, &src->from);
2330         ast_party_id_copy(&dest->to, &src->to);
2331         ast_party_id_copy(&dest->priv_orig, &src->priv_orig);
2332         ast_party_id_copy(&dest->priv_from, &src->priv_from);
2333         ast_party_id_copy(&dest->priv_to, &src->priv_to);
2334         ast_party_redirecting_reason_copy(&dest->reason, &src->reason);
2335         ast_party_redirecting_reason_copy(&dest->orig_reason, &src->orig_reason);
2336         dest->count = src->count;
2337 }
2338
2339 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2340 {
2341         ast_party_id_set_init(&init->orig, &guide->orig);
2342         ast_party_id_set_init(&init->from, &guide->from);
2343         ast_party_id_set_init(&init->to, &guide->to);
2344         ast_party_id_set_init(&init->priv_orig, &guide->priv_orig);
2345         ast_party_id_set_init(&init->priv_from, &guide->priv_from);
2346         ast_party_id_set_init(&init->priv_to, &guide->priv_to);
2347         ast_party_redirecting_reason_set_init(&init->reason, &guide->reason);
2348         ast_party_redirecting_reason_set_init(&init->orig_reason, &guide->orig_reason);
2349         init->count = guide->count;
2350 }
2351
2352 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2353 {
2354         ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2355         ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2356         ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2357         ast_party_id_set(&dest->priv_orig, &src->priv_orig, update ? &update->priv_orig : NULL);
2358         ast_party_id_set(&dest->priv_from, &src->priv_from, update ? &update->priv_from : NULL);
2359         ast_party_id_set(&dest->priv_to, &src->priv_to, update ? &update->priv_to : NULL);
2360         ast_party_redirecting_reason_set(&dest->reason, &src->reason);
2361         ast_party_redirecting_reason_set(&dest->orig_reason, &src->orig_reason);
2362         dest->count = src->count;
2363 }
2364
2365 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2366 {
2367         ast_party_id_free(&doomed->orig);
2368         ast_party_id_free(&doomed->from);
2369         ast_party_id_free(&doomed->to);
2370         ast_party_id_free(&doomed->priv_orig);
2371         ast_party_id_free(&doomed->priv_from);
2372         ast_party_id_free(&doomed->priv_to);
2373         ast_party_redirecting_reason_free(&doomed->reason);
2374         ast_party_redirecting_reason_free(&doomed->orig_reason);
2375 }
2376
2377 /*! \brief Free a channel structure */
2378 static void ast_channel_destructor(void *obj)
2379 {
2380         struct ast_channel *chan = obj;
2381 #ifdef HAVE_EPOLL
2382         int i;
2383 #endif
2384         struct ast_var_t *vardata;
2385         struct ast_frame *f;
2386         struct varshead *headp;
2387         struct ast_datastore *datastore;
2388         char device_name[AST_CHANNEL_NAME];
2389         struct ast_callid *callid;
2390
2391         if (ast_channel_internal_is_finalized(chan)) {
2392                 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2393                 ast_cel_check_retire_linkedid(chan);
2394         }
2395
2396         ast_pbx_hangup_handler_destroy(chan);
2397
2398         ast_channel_lock(chan);
2399
2400         /* Get rid of each of the data stores on the channel */
2401         while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2402                 /* Free the data store */
2403                 ast_datastore_free(datastore);
2404
2405         /* While the channel is locked, take the reference to its callid while we tear down the call. */
2406         callid = ast_channel_callid(chan);
2407         ast_channel_callid_cleanup(chan);
2408
2409         ast_channel_unlock(chan);
2410
2411         /* Lock and unlock the channel just to be sure nobody has it locked still
2412            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2413         ast_channel_lock(chan);
2414         ast_channel_unlock(chan);
2415
2416         if (ast_channel_tech_pvt(chan)) {
2417                 ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2418                 ast_free(ast_channel_tech_pvt(chan));
2419         }
2420
2421         if (ast_channel_sched(chan)) {
2422                 ast_sched_context_destroy(ast_channel_sched(chan));
2423         }
2424
2425         if (ast_channel_internal_is_finalized(chan)) {
2426                 char *dashptr;
2427
2428                 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2429                 if ((dashptr = strrchr(device_name, '-'))) {
2430                         *dashptr = '\0';
2431                 }
2432         } else {
2433                 device_name[0] = '\0';
2434         }
2435
2436         /* Stop monitoring */
2437         if (ast_channel_monitor(chan))
2438                 ast_channel_monitor(chan)->stop( chan, 0 );
2439
2440         /* If there is native format music-on-hold state, free it */
2441         if (ast_channel_music_state(chan))
2442                 ast_moh_cleanup(chan);
2443
2444         /* Free translators */
2445         if (ast_channel_readtrans(chan))
2446                 ast_translator_free_path(ast_channel_readtrans(chan));
2447         if (ast_channel_writetrans(chan))
2448                 ast_translator_free_path(ast_channel_writetrans(chan));
2449         if (ast_channel_pbx(chan))
2450                 ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2451
2452         ast_party_dialed_free(ast_channel_dialed(chan));
2453         ast_party_caller_free(ast_channel_caller(chan));
2454         ast_party_connected_line_free(ast_channel_connected(chan));
2455         ast_party_redirecting_free(ast_channel_redirecting(chan));
2456
2457         /* Close pipes if appropriate */
2458         ast_channel_internal_alertpipe_close(chan);
2459         if (ast_channel_timer(chan)) {
2460                 ast_timer_close(ast_channel_timer(chan));
2461                 ast_channel_timer_set(chan, NULL);
2462         }
2463 #ifdef HAVE_EPOLL
2464         for (i = 0; i < AST_MAX_FDS; i++) {
2465                 if (ast_channel_internal_epfd_data(chan, i)) {
2466                         ast_free(ast_channel_internal_epfd_data(chan, i));
2467                 }
2468         }
2469         close(ast_channel_epfd(chan));
2470 #endif
2471         while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2472                 ast_frfree(f);
2473
2474         /* loop over the variables list, freeing all data and deleting list items */
2475         /* no need to lock the list, as the channel is already locked */
2476         headp = ast_channel_varshead(chan);
2477         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2478                 ast_var_delete(vardata);
2479
2480         ast_app_group_discard(chan);
2481
2482         /* Destroy the jitterbuffer */
2483         ast_jb_destroy(chan);
2484
2485         if (ast_channel_cdr(chan)) {
2486                 ast_cdr_discard(ast_channel_cdr(chan));
2487                 ast_channel_cdr_set(chan, NULL);
2488         }
2489
2490         if (ast_channel_zone(chan)) {
2491                 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2492         }
2493
2494         ast_channel_internal_cleanup(chan);
2495
2496         if (device_name[0]) {
2497                 /*
2498                  * We have a device name to notify of a new state.
2499                  *
2500                  * Queue an unknown state, because, while we know that this particular
2501                  * instance is dead, we don't know the state of all other possible
2502                  * instances.
2503                  */
2504                 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);
2505         }
2506
2507         ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2508         if (callid) {
2509                 ast_callid_unref(callid);
2510         }
2511
2512         ast_channel_named_callgroups_set(chan, NULL);
2513         ast_channel_named_pickupgroups_set(chan, NULL);
2514
2515         ast_atomic_fetchadd_int(&chancount, -1);
2516 }
2517
2518 /*! \brief Free a dummy channel structure */
2519 static void ast_dummy_channel_destructor(void *obj)
2520 {
2521         struct ast_channel *chan = obj;
2522         struct ast_datastore *datastore;
2523         struct ast_var_t *vardata;
2524         struct varshead *headp;
2525
2526         ast_pbx_hangup_handler_destroy(chan);
2527
2528         /* Get rid of each of the data stores on the channel */
2529         while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
2530                 /* Free the data store */
2531                 ast_datastore_free(datastore);
2532         }
2533
2534         ast_party_dialed_free(ast_channel_dialed(chan));
2535         ast_party_caller_free(ast_channel_caller(chan));
2536         ast_party_connected_line_free(ast_channel_connected(chan));
2537         ast_party_redirecting_free(ast_channel_redirecting(chan));
2538
2539         /* loop over the variables list, freeing all data and deleting list items */
2540         /* no need to lock the list, as the channel is already locked */
2541         headp = ast_channel_varshead(chan);
2542         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2543                 ast_var_delete(vardata);
2544
2545         if (ast_channel_cdr(chan)) {
2546                 ast_cdr_discard(ast_channel_cdr(chan));
2547                 ast_channel_cdr_set(chan, NULL);
2548         }
2549
2550         ast_channel_internal_cleanup(chan);
2551 }
2552
2553 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2554 {
2555         return ast_datastore_alloc(info, uid);
2556 }
2557
2558 int ast_channel_datastore_free(struct ast_datastore *datastore)
2559 {
2560         return ast_datastore_free(datastore);
2561 }
2562
2563 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2564 {
2565         struct ast_datastore *datastore = NULL, *datastore2;
2566
2567         AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2568                 if (datastore->inheritance > 0) {
2569                         datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2570                         if (datastore2) {
2571                                 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2572                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2573                                 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2574                         }
2575                 }
2576         }
2577         return 0;
2578 }
2579
2580 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2581 {
2582         int res = 0;
2583
2584         AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2585
2586         return res;
2587 }
2588
2589 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2590 {
2591         return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2592 }
2593
2594 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2595 {
2596         struct ast_datastore *datastore = NULL;
2597
2598         if (info == NULL)
2599                 return NULL;
2600
2601         AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2602                 if (datastore->info != info) {
2603                         continue;
2604                 }
2605
2606                 if (uid == NULL) {
2607                         /* matched by type only */
2608                         break;
2609                 }
2610
2611                 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2612                         /* Matched by type AND uid */
2613                         break;
2614                 }
2615         }
2616
2617         return datastore;
2618 }
2619
2620 /*! Set the file descriptor on the channel */
2621 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2622 {
2623 #ifdef HAVE_EPOLL
2624         struct epoll_event ev;
2625         struct ast_epoll_data *aed = NULL;
2626
2627         if (ast_channel_fd_isset(chan, which)) {
2628                 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2629                 aed = ast_channel_internal_epfd_data(chan, which);
2630         }
2631
2632         /* If this new fd is valid, add it to the epoll */
2633         if (fd > -1) {
2634                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2635                         return;
2636
2637                 ast_channel_internal_epfd_data_set(chan, which, aed);
2638                 aed->chan = chan;
2639                 aed->which = which;
2640
2641                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2642                 ev.data.ptr = aed;
2643                 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2644         } else if (aed) {
2645                 /* We don't have to keep around this epoll data structure now */
2646                 ast_free(aed);
2647                 ast_channel_epfd_data_set(chan, which, NULL);
2648         }
2649 #endif
2650         ast_channel_internal_fd_set(chan, which, fd);
2651         return;
2652 }
2653
2654 /*! Add a channel to an optimized waitfor */
2655 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2656 {
2657 #ifdef HAVE_EPOLL
2658         struct epoll_event ev;
2659         int i = 0;
2660
2661         if (ast_channel_epfd(chan0) == -1)
2662                 return;
2663
2664         /* Iterate through the file descriptors on chan1, adding them to chan0 */
2665         for (i = 0; i < AST_MAX_FDS; i++) {
2666                 if (!ast_channel_fd_isset(chan1, i)) {
2667                         continue;
2668                 }
2669                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2670                 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2671                 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2672         }
2673
2674 #endif
2675         return;
2676 }
2677
2678 /*! Delete a channel from an optimized waitfor */
2679 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2680 {
2681 #ifdef HAVE_EPOLL
2682         struct epoll_event ev;
2683         int i = 0;
2684
2685         if (ast_channel_epfd(chan0) == -1)
2686                 return;
2687
2688         for (i = 0; i < AST_MAX_FDS; i++) {
2689                 if (!ast_channel_fd_isset(chan1, i)) {
2690                         continue;
2691                 }
2692                 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2693         }
2694
2695 #endif
2696         return;
2697 }
2698
2699 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2700 {
2701         ast_channel_lock(chan);
2702
2703         ast_channel_softhangup_internal_flag_clear(chan, flag);
2704
2705         if (!ast_channel_softhangup_internal_flag(chan)) {
2706                 struct ast_frame *fr;
2707
2708                 /* If we have completely cleared the softhangup flag,
2709                  * then we need to fully abort the hangup process.  This requires
2710                  * pulling the END_OF_Q frame out of the channel frame queue if it
2711                  * still happens to be there. */
2712
2713                 fr = AST_LIST_LAST(ast_channel_readq(chan));
2714                 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2715                                 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2716                         AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2717                         ast_frfree(fr);
2718                 }
2719         }
2720
2721         ast_channel_unlock(chan);
2722 }
2723
2724 /*! \brief Softly hangup a channel, don't lock */
2725 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2726 {
2727         ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2728         /* Inform channel driver that we need to be hung up, if it cares */
2729         ast_channel_softhangup_internal_flag_add(chan, cause);
2730         ast_queue_frame(chan, &ast_null_frame);
2731         /* Interrupt any poll call or such */
2732         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2733                 pthread_kill(ast_channel_blocker(chan), SIGURG);
2734         return 0;
2735 }
2736
2737 /*! \brief Softly hangup a channel, lock */
2738 int ast_softhangup(struct ast_channel *chan, int cause)
2739 {
2740         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
2741         int res;
2742
2743         ast_channel_lock(chan);
2744         res = ast_softhangup_nolock(chan, cause);
2745         blob = ast_json_pack("{s: i, s: b}",
2746                              "cause", cause,
2747                              "soft", 1);
2748         publish_channel_blob(chan, ast_channel_hangup_request_type(), blob);
2749         ast_channel_unlock(chan);
2750
2751         return res;
2752 }
2753
2754 static void free_translation(struct ast_channel *clonechan)
2755 {
2756         if (ast_channel_writetrans(clonechan))
2757                 ast_translator_free_path(ast_channel_writetrans(clonechan));
2758         if (ast_channel_readtrans(clonechan))
2759                 ast_translator_free_path(ast_channel_readtrans(clonechan));
2760         ast_channel_writetrans_set(clonechan, NULL);
2761         ast_channel_readtrans_set(clonechan, NULL);
2762         if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2763                 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2764                 ast_format_clear(ast_channel_rawreadformat(clonechan));
2765         } else {
2766                 struct ast_format tmpfmt;
2767                 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2768                 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2769                 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2770         }
2771 }
2772
2773 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2774 {
2775         struct ast_channel *bridge;
2776
2777         ast_channel_lock(chan);
2778         if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2779                 ast_channel_hangupsource_set(chan, source);
2780         }
2781         bridge = ast_bridged_channel(chan);
2782         if (bridge) {
2783                 ast_channel_ref(bridge);
2784         }
2785         ast_channel_unlock(chan);
2786
2787         if (bridge) {
2788                 ast_channel_lock(bridge);
2789                 if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
2790                         ast_channel_hangupsource_set(bridge, source);
2791                 }
2792                 ast_channel_unlock(bridge);
2793                 ast_channel_unref(bridge);
2794         }
2795 }
2796
2797 static void destroy_hooks(struct ast_channel *chan)
2798 {
2799         if (ast_channel_audiohooks(chan)) {
2800                 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2801                 ast_channel_audiohooks_set(chan, NULL);
2802         }
2803
2804         ast_framehook_list_destroy(chan);
2805 }
2806
2807 /*! \brief Hangup a channel */
2808 int ast_hangup(struct ast_channel *chan)
2809 {
2810         char extra_str[64]; /* used for cel logging below */
2811
2812         ast_autoservice_stop(chan);
2813
2814         ast_channel_lock(chan);
2815
2816         /*
2817          * Do the masquerade if someone is setup to masquerade into us.
2818          *
2819          * NOTE: We must hold the channel lock after testing for a
2820          * pending masquerade and setting the channel as a zombie to
2821          * prevent __ast_channel_masquerade() from setting up a
2822          * masquerade with a dead channel.
2823          */
2824         while (ast_channel_masq(chan)) {
2825                 ast_channel_unlock(chan);
2826                 ast_do_masquerade(chan);
2827                 ast_channel_lock(chan);
2828         }
2829
2830         if (ast_channel_masqr(chan)) {
2831                 /*
2832                  * This channel is one which will be masqueraded into something.
2833                  * Mark it as a zombie already so ast_do_masquerade() will know
2834                  * to free it later.
2835                  */
2836                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2837                 destroy_hooks(chan);
2838                 ast_channel_unlock(chan);
2839                 return 0;
2840         }
2841
2842         /* Mark as a zombie so a masquerade cannot be setup on this channel. */
2843         ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2844
2845         ast_channel_unlock(chan);
2846
2847         /*
2848          * XXX if running the hangup handlers here causes problems
2849          * because the handlers take too long to execute, we could move
2850          * the meat of this function into another thread.  A thread
2851          * where channels go to die.
2852          *
2853          * If this is done, ast_autoservice_chan_hangup_peer() will no
2854          * longer be needed.
2855          */
2856         ast_pbx_hangup_handler_run(chan);
2857         ao2_unlink(channels, chan);
2858         ast_channel_lock(chan);
2859
2860         destroy_hooks(chan);
2861
2862         free_translation(chan);
2863         /* Close audio stream */
2864         if (ast_channel_stream(chan)) {
2865                 ast_closestream(ast_channel_stream(chan));
2866                 ast_channel_stream_set(chan, NULL);
2867         }
2868         /* Close video stream */
2869         if (ast_channel_vstream(chan)) {
2870                 ast_closestream(ast_channel_vstream(chan));
2871                 ast_channel_vstream_set(chan, NULL);
2872         }
2873         if (ast_channel_sched(chan)) {
2874                 ast_sched_context_destroy(ast_channel_sched(chan));
2875                 ast_channel_sched_set(chan, NULL);
2876         }
2877
2878         if (ast_channel_generatordata(chan)) {  /* Clear any tone stuff remaining */
2879                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2880                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2881                 }
2882         }
2883         ast_channel_generatordata_set(chan, NULL);
2884         ast_channel_generator_set(chan, NULL);
2885
2886         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"), ""));
2887         ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2888
2889         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2890                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2891                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
2892                         (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2893                 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2894         }
2895
2896         ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2897         if (ast_channel_tech(chan)->hangup) {
2898                 ast_channel_tech(chan)->hangup(chan);
2899         }
2900
2901         ast_channel_unlock(chan);
2902
2903         ast_cc_offer(chan);
2904
2905         ast_publish_channel_state(chan);
2906         publish_cache_clear(chan);
2907
2908         if (ast_channel_cdr(chan) && !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_BRIDGED) &&
2909                 !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_POST_DISABLED) &&
2910                 (ast_channel_cdr(chan)->disposition != AST_CDR_NULL || ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_DIALED))) {
2911                 ast_channel_lock(chan);
2912                 ast_cdr_end(ast_channel_cdr(chan));
2913                 ast_cdr_detach(ast_channel_cdr(chan));
2914                 ast_channel_cdr_set(chan, NULL);
2915                 ast_channel_unlock(chan);
2916         }
2917
2918         ast_channel_unref(chan);
2919
2920         return 0;
2921 }
2922
2923 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2924 {
2925         int res = 0;
2926
2927         ast_channel_lock(chan);
2928
2929         /* You can't answer an outbound call */
2930         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2931                 ast_channel_unlock(chan);
2932                 return 0;
2933         }
2934
2935         /* Stop if we're a zombie or need a soft hangup */
2936         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2937                 ast_channel_unlock(chan);
2938                 return -1;
2939         }
2940
2941         ast_channel_unlock(chan);
2942
2943         switch (ast_channel_state(chan)) {
2944         case AST_STATE_RINGING:
2945         case AST_STATE_RING:
2946                 ast_channel_lock(chan);
2947                 if (ast_channel_tech(chan)->answer) {
2948                         res = ast_channel_tech(chan)->answer(chan);
2949                 }
2950                 ast_setstate(chan, AST_STATE_UP);
2951                 if (cdr_answer) {
2952                         ast_cdr_answer(ast_channel_cdr(chan));
2953                 }
2954                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2955                 ast_channel_unlock(chan);
2956                 break;
2957         case AST_STATE_UP:
2958                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2959                 /* Calling ast_cdr_answer when it it has previously been called
2960                  * is essentially a no-op, so it is safe.
2961                  */
2962                 if (cdr_answer) {
2963                         ast_cdr_answer(ast_channel_cdr(chan));
2964                 }
2965                 break;
2966         default:
2967                 break;
2968         }
2969
2970         ast_indicate(chan, -1);
2971
2972         return res;
2973 }
2974
2975 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2976 {
2977         int res = 0;
2978         enum ast_channel_state old_state;
2979
2980         old_state = ast_channel_state(chan);
2981         if ((res = ast_raw_answer(chan, cdr_answer))) {
2982                 return res;
2983         }
2984
2985         switch (old_state) {
2986         case AST_STATE_RINGING:
2987         case AST_STATE_RING:
2988                 /* wait for media to start flowing, but don't wait any longer
2989                  * than 'delay' or 500 milliseconds, whichever is longer
2990                  */
2991                 do {
2992                         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2993                         struct ast_frame *cur;
2994                         struct ast_frame *new_frame;
2995                         int timeout_ms = MAX(delay, 500);
2996                         unsigned int done = 0;
2997                         struct timeval start;
2998
2999                         AST_LIST_HEAD_INIT_NOLOCK(&frames);
3000
3001                         start = ast_tvnow();
3002                         for (;;) {
3003                                 int ms = ast_remaining_ms(start, timeout_ms);
3004                                 ms = ast_waitfor(chan, ms);
3005                                 if (ms < 0) {
3006                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
3007                                         res = -1;
3008                                         break;
3009                                 }
3010                                 if (ms == 0) {
3011                                         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));
3012                                         break;
3013                                 }
3014                                 cur = ast_read(chan);
3015                                 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
3016                                              (cur->subclass.integer == AST_CONTROL_HANGUP))) {
3017                                         if (cur) {
3018                                                 ast_frfree(cur);
3019                                         }
3020                                         res = -1;
3021                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
3022                                         break;
3023                                 }
3024
3025                                 if ((new_frame = ast_frisolate(cur)) != cur) {
3026                                         ast_frfree(cur);
3027                                 }
3028
3029                                 AST_LIST_INSERT_HEAD(&frames, new_frame, frame_list);
3030
3031                                 /* if a specific delay period was requested, continue
3032                                  * until that delay has passed. don't stop just because
3033                                  * incoming media has arrived.
3034                                  */
3035                                 if (delay) {
3036                                         continue;
3037                                 }
3038
3039                                 switch (new_frame->frametype) {
3040                                         /* all of these frametypes qualify as 'media' */
3041                                 case AST_FRAME_VOICE:
3042                                 case AST_FRAME_VIDEO:
3043                                 case AST_FRAME_TEXT:
3044                                 case AST_FRAME_DTMF_BEGIN:
3045                                 case AST_FRAME_DTMF_END:
3046                                 case AST_FRAME_IMAGE:
3047                                 case AST_FRAME_HTML:
3048                                 case AST_FRAME_MODEM:
3049                                         done = 1;
3050                                         break;
3051                                 case AST_FRAME_CONTROL:
3052                                 case AST_FRAME_IAX:
3053                                 case AST_FRAME_BRIDGE_ACTION:
3054                                 case AST_FRAME_NULL:
3055                                 case AST_FRAME_CNG:
3056                                         break;
3057                                 }
3058
3059                                 if (done) {
3060                                         break;
3061                                 }
3062                         }
3063
3064                         if (res == 0) {
3065                                 ast_channel_lock(chan);
3066                                 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
3067                                         ast_queue_frame_head(chan, cur);
3068                                         ast_frfree(cur);
3069                                 }
3070                                 ast_channel_unlock(chan);
3071                         }
3072                 } while (0);
3073                 break;
3074         default:
3075                 break;
3076         }
3077
3078         return res;
3079 }
3080
3081 int ast_answer(struct ast_channel *chan)
3082 {
3083         return __ast_answer(chan, 0, 1);
3084 }
3085
3086 void ast_deactivate_generator(struct ast_channel *chan)
3087 {
3088         ast_channel_lock(chan);
3089         if (ast_channel_generatordata(chan)) {
3090                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3091                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3092                 }
3093                 ast_channel_generatordata_set(chan, NULL);
3094                 ast_channel_generator_set(chan, NULL);
3095                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
3096                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
3097                 ast_settimeout(chan, 0, NULL, NULL);
3098         }
3099         ast_channel_unlock(chan);
3100 }
3101
3102 static void generator_write_format_change(struct ast_channel *chan)
3103 {
3104         ast_channel_lock(chan);
3105         if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
3106                 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
3107         }
3108         ast_channel_unlock(chan);
3109 }
3110
3111 static int generator_force(const void *data)
3112 {
3113         /* Called if generator doesn't have data */
3114         void *tmp;
3115         int res;
3116         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
3117         struct ast_channel *chan = (struct ast_channel *)data;
3118
3119         ast_channel_lock(chan);
3120         tmp = ast_channel_generatordata(chan);
3121         ast_channel_generatordata_set(chan, NULL);
3122         if (ast_channel_generator(chan))
3123                 generate = ast_channel_generator(chan)->generate;
3124         ast_channel_unlock(chan);
3125
3126         if (!tmp || !generate)
3127                 return 0;
3128
3129         res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
3130
3131         ast_channel_lock(chan);
3132         if (ast_channel_generator(chan) && generate == ast_channel_generator(chan)->generate) {
3133                 ast_channel_generatordata_set(chan, tmp);
3134         }
3135         ast_channel_unlock(chan);
3136
3137         if (res) {
3138                 ast_debug(1, "Auto-deactivating generator\n");
3139                 ast_deactivate_generator(chan);
3140         }
3141
3142         return 0;
3143 }
3144
3145 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
3146 {
3147         int res = 0;
3148         void *generatordata = NULL;
3149
3150         ast_channel_lock(chan);
3151         if (ast_channel_generatordata(chan)) {
3152                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3153                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3154                 }
3155         }
3156         if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
3157                 res = -1;
3158         }
3159         ast_channel_generatordata_set(chan, generatordata);
3160         if (!res) {
3161                 ast_settimeout(chan, 50, generator_force, chan);
3162                 ast_channel_generator_set(chan, gen);
3163         }
3164         ast_channel_unlock(chan);
3165
3166         ast_prod(chan);
3167
3168         return res;
3169 }
3170
3171 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
3172 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
3173 {
3174         int winner = -1;
3175         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
3176         return winner;
3177 }
3178
3179 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
3180 #ifdef HAVE_EPOLL
3181 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
3182                                         int *exception, int *outfd, int *ms)
3183 #else
3184 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3185                                         int *exception, int *outfd, int *ms)
3186 #endif
3187 {
3188         struct timeval start = { 0 , 0 };
3189         struct pollfd *pfds = NULL;
3190         int res;
3191         long rms;
3192         int x, y, max;
3193         int sz;
3194         struct timeval now = { 0, 0 };
3195         struct timeval whentohangup = { 0, 0 }, diff;
3196         struct ast_channel *winner = NULL;
3197         struct fdmap {
3198                 int chan;
3199                 int fdno;
3200         } *fdmap = NULL;
3201
3202         if (outfd) {
3203                 *outfd = -99999;
3204         }
3205         if (exception) {
3206                 *exception = 0;
3207         }
3208
3209         if ((sz = n * AST_MAX_FDS + nfds)) {
3210                 pfds = ast_alloca(sizeof(*pfds) * sz);
3211                 fdmap = ast_alloca(sizeof(*fdmap) * sz);
3212         } else {
3213                 /* nothing to allocate and no FDs to check */
3214                 return NULL;
3215         }
3216
3217         /* Perform any pending masquerades */
3218         for (x = 0; x < n; x++) {
3219                 while (ast_channel_masq(c[x])) {
3220                         ast_do_masquerade(c[x]);
3221                 }
3222
3223                 ast_channel_lock(c[x]);
3224                 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
3225                         if (ast_tvzero(whentohangup))
3226                                 now = ast_tvnow();
3227                         diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
3228                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3229                                 ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3230                                 /* Should already be hungup */
3231                                 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3232                                 ast_channel_unlock(c[x]);
3233                                 return c[x];
3234                         }
3235                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3236                                 whentohangup = diff;
3237                 }
3238                 ast_channel_unlock(c[x]);
3239         }
3240         /* Wait full interval */
3241         rms = *ms;
3242         /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3243         if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3244                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
3245                 if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
3246                         rms =  *ms;
3247                 }
3248         } else if (!ast_tvzero(whentohangup) && rms < 0) {
3249                 /* Tiny corner case... call would need to last >24 days */
3250                 rms = INT_MAX;
3251         }
3252         /*
3253          * Build the pollfd array, putting the channels' fds first,
3254          * followed by individual fds. Order is important because
3255          * individual fd's must have priority over channel fds.
3256          */
3257         max = 0;
3258         for (x = 0; x < n; x++) {
3259                 for (y = 0; y < AST_MAX_FDS; y++) {
3260                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
3261                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
3262                         max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3263                 }
3264                 CHECK_BLOCKING(c[x]);
3265         }
3266         /* Add the individual fds */
3267         for (x = 0; x < nfds; x++) {
3268                 fdmap[max].chan = -1;
3269                 max += ast_add_fd(&pfds[max], fds[x]);
3270         }
3271
3272         if (*ms > 0) {
3273                 start = ast_tvnow();
3274         }
3275
3276         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3277                 do {
3278                         int kbrms = rms;
3279                         if (kbrms > 600000) {
3280                                 kbrms = 600000;
3281                         }
3282                         res = ast_poll(pfds, max, kbrms);
3283                         if (!res) {
3284                                 rms -= kbrms;
3285                         }
3286                 } while (!res && (rms > 0));
3287         } else {
3288                 res = ast_poll(pfds, max, rms);
3289         }
3290         for (x = 0; x < n; x++) {
3291                 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3292         }
3293         if (res < 0) { /* Simulate a timeout if we were interrupted */
3294                 if (errno != EINTR) {
3295                         *ms = -1;
3296                 }
3297                 return NULL;
3298         }
3299         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
3300                 now = ast_tvnow();
3301                 for (x = 0; x < n; x++) {
3302                         if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3303                                 ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3304                                 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3305                                 if (winner == NULL) {
3306                                         winner = c[x];
3307                                 }
3308                         }
3309                 }
3310         }
3311         if (res == 0) { /* no fd ready, reset timeout and done */
3312                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
3313                 return winner;
3314         }
3315         /*
3316          * Then check if any channel or fd has a pending event.
3317          * Remember to check channels first and fds last, as they
3318          * must have priority on setting 'winner'
3319          */
3320         for (x = 0; x < max; x++) {
3321                 res = pfds[x].revents;
3322                 if (res == 0) {
3323                         continue;
3324                 }
3325                 if (fdmap[x].chan >= 0) {       /* this is a channel */
3326                         winner = c[fdmap[x].chan];      /* override previous winners */
3327                         if (res & POLLPRI) {
3328                                 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3329                         } else {
3330                                 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3331                         }
3332                         ast_channel_fdno_set(winner, fdmap[x].fdno);
3333                 } else {                        /* this is an fd */
3334                         if (outfd) {
3335                                 *outfd = pfds[x].fd;
3336                         }
3337                         if (exception) {
3338                                 *exception = (res & POLLPRI) ? -1 : 0;
3339                         }
3340                         winner = NULL;
3341                 }
3342         }
3343         if (*ms > 0) {
3344                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3345                 if (*ms < 0) {
3346                         *ms = 0;
3347                 }
3348         }
3349         return winner;
3350 }
3351
3352 #ifdef HAVE_EPOLL
3353 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3354 {
3355         struct timeval start = { 0 , 0 };
3356         int res = 0;
3357         struct epoll_event ev[1];
3358         long diff, rms = *ms;
3359         struct ast_channel *winner = NULL;
3360         struct ast_epoll_data *aed = NULL;
3361
3362
3363         /* See if this channel needs to be masqueraded */
3364         while (ast_channel_masq(chan)) {
3365                 ast_do_masquerade(chan);
3366         }
3367
3368         ast_channel_lock(chan);
3369         /* Figure out their timeout */
3370         if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3371                 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow())) < 0) {
3372                         /* They should already be hungup! */
3373                         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3374                         ast_channel_unlock(chan);
3375                         return NULL;
3376                 }
3377                 /* If this value is smaller then the current one... make it priority */
3378                 if (rms > diff) {
3379                         rms = diff;
3380                 }
3381         }
3382
3383         ast_channel_unlock(chan);
3384
3385         /* Time to make this channel block... */
3386         CHECK_BLOCKING(chan);
3387
3388         if (*ms > 0) {
3389                 start = ast_tvnow();
3390         }
3391
3392         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3393         res = epoll_wait(ast_channel_epfd(chan), ev, 1, rms);
3394
3395         /* Stop blocking */
3396         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
3397
3398         /* Simulate a timeout if we were interrupted */
3399         if (res < 0) {
3400                 if (errno != EINTR) {
3401                         *ms = -1;
3402                 }
3403                 return NULL;
3404         }
3405
3406         /* If this channel has a timeout see if it expired */
3407         if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3408                 if (ast_tvdiff_ms(ast_tvnow(), *ast_channel_whentohangup(chan)) >= 0) {
3409                         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3410                         winner = chan;
3411                 }
3412         }
3413
3414         /* No fd ready, reset timeout and be done for now */
3415         if (!res) {
3416                 *ms = 0;
3417                 return winner;
3418         }
3419
3420         /* See what events are pending */
3421         aed = ev[0].data.ptr;
3422         ast_channel_fdno_set(chan, aed->which);
3423         if (ev[0].events & EPOLLPRI) {
3424                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3425         } else {
3426                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3427         }
3428
3429         if (*ms > 0) {
3430                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3431                 if (*ms < 0) {
3432                         *ms = 0;
3433                 }
3434         }
3435
3436         return chan;
3437 }
3438
3439 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3440 {
3441         struct timeval start = { 0 , 0 };
3442         int res = 0, i;
3443         struct epoll_event ev[25] = { { 0, } };
3444         struct timeval now = { 0, 0 };
3445         long whentohangup = 0, diff = 0, rms = *ms;
3446         struct ast_channel *winner = NULL;
3447
3448         for (i = 0; i < n; i++) {
3449                 while (ast_channel_masq(c[i])) {
3450                         ast_do_masquerade(c[i]);
3451                 }
3452
3453                 ast_channel_lock(c[i]);
3454                 if (!ast_tvzero(*ast_channel_whentohangup(c[i]))) {
3455                         if (whentohangup == 0) {
3456                                 now = ast_tvnow();
3457                         }
3458                         if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(c[i]), now)) < 0) {
3459                                 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3460                                 ast_channel_unlock(c[i]);
3461                                 return c[i];
3462                         }
3463                         if (!whentohangup || whentohangup > diff) {
3464                                 whentohangup = diff;
3465                         }
3466                 }
3467                 ast_channel_unlock(c[i]);
3468                 CHECK_BLOCKING(c[i]);
3469         }
3470
3471         rms = *ms;
3472         if (whentohangup) {
3473                 rms = whentohangup;
3474                 if (*ms >= 0 && *ms < rms) {
3475                         rms = *ms;
3476                 }
3477         }
3478
3479         if (*ms > 0) {
3480                 start = ast_tvnow();
3481         }
3482
3483         res = epoll_wait(ast_channel_epfd(c[0]), ev, 25, rms);
3484
3485         for (i = 0; i < n; i++) {
3486                 ast_clear_flag(ast_channel_flags(c[i]), AST_FLAG_BLOCKING);
3487         }
3488
3489         if (res < 0) {
3490                 if (errno != EINTR) {
3491                         *ms = -1;
3492                 }
3493                 return NULL;
3494         }
3495
3496         if (whentohangup) {
3497                 now = ast_tvnow();
3498                 for (i = 0; i < n; i++) {
3499                         if (!ast_tvzero(*ast_channel_whentohangup(c[i])) && ast_tvdiff_ms(now, *ast_channel_whentohangup(c[i])) >= 0) {
3500                                 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3501                                 if (!winner) {
3502                                         winner = c[i];
3503                                 }
3504                         }
3505                 }
3506         }
3507
3508         if (!res) {
3509                 *ms = 0;
3510                 return winner;
3511         }
3512
3513         for (i = 0; i < res; i++) {
3514                 struct ast_epoll_data *aed = ev[i].data.ptr;
3515
3516                 if (!ev[i].events || !aed) {
3517                         continue;
3518                 }
3519
3520                 winner = aed->chan;
3521                 if (ev[i].events & EPOLLPRI) {
3522                         ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3523                 } else {
3524                         ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3525                 }
3526                 ast_channel_fdno_set(winner, aed->which);
3527         }
3528
3529         if (*ms > 0) {
3530                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3531                 if (*ms < 0) {
3532                         *ms = 0;
3533                 }
3534         }
3535
3536         return winner;
3537 }
3538
3539 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3540                                         int *exception, int *outfd, int *ms)
3541 {
3542         /* Clear all provided values in one place. */
3543         if (outfd) {
3544                 *outfd = -99999;
3545         }
3546         if (exception) {
3547                 *exception = 0;
3548         }
3549
3550         /* If no epoll file descriptor is available resort to classic nandfds */
3551         if (!n || nfds || ast_channel_epfd(c[0]) == -1) {
3552                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3553         } else if (!nfds && n == 1) {
3554                 return ast_waitfor_nandfds_simple(c[0], ms);
3555         } else {
3556                 return ast_waitfor_nandfds_complex(c, n, ms);
3557         }
3558 }
3559 #endif
3560
3561 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3562 {
3563         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3564 }
3565
3566 int ast_waitfor(struct ast_channel *c, int ms)
3567 {
3568         if (ms < 0) {
3569                 do {
3570                         ms = 100000;
3571                         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3572                 } while (!ms);
3573         } else {
3574                 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3575         }
3576         return ms;
3577 }
3578
3579 int ast_waitfordigit(struct ast_channel *c, int ms)
3580 {
3581         return ast_waitfordigit_full(c, ms, -1, -1);
3582 }
3583
3584 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3585 {
3586         int res;
3587         unsigned int real_rate = rate, max_rate;
3588
3589         ast_channel_lock(c);
3590
3591         if (ast_channel_timingfd(c) == -1) {
3592                 ast_channel_unlock(c);
3593                 return -1;
3594         }
3595
3596         if (!func) {
3597                 rate = 0;
3598                 data = NULL;
3599         }
3600
3601         if (rate && rate > (max_rate = ast_timer_get_max_rate(ast_channel_timer(c)))) {
3602                 real_rate = max_rate;
3603         }
3604
3605         ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3606
3607         res = ast_timer_set_rate(ast_channel_timer(c), real_rate);
3608
3609         ast_channel_timingfunc_set(c, func);
3610         ast_channel_timingdata_set(c, data);
3611
3612         if (func == NULL && rate == 0 && ast_channel_fdno(c) == AST_TIMING_FD) {
3613                 /* Clearing the timing func and setting the rate to 0
3614                  * means that we don't want to be reading from the timingfd
3615                  * any more. Setting c->fdno to -1 means we won't have any
3616                  * errant reads from the timingfd, meaning we won't potentially
3617                  * miss any important frames.
3618                  */
3619                 ast_channel_fdno_set(c, -1);
3620         }
3621
3622         ast_channel_unlock(c);
3623
3624         return res;
3625 }
3626
3627 int ast_waitfordigit_full(struct ast_channel *c, int timeout_ms, int audiofd, int cmdfd)
3628 {
3629         struct timeval start = ast_tvnow();
3630         int ms;
3631
3632         /* Stop if we're a zombie or need a soft hangup */
3633         if (ast_test_flag(ast_channel_flags(c), AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3634                 return -1;
3635
3636         /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3637         ast_set_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3638
3639         /* Wait for a digit, no more than timeout_ms milliseconds total.
3640          * Or, wait indefinitely if timeout_ms is <0.
3641          */
3642         while ((ms = ast_remaining_ms(start, timeout_ms))) {
3643                 struct ast_channel *rchan;
3644                 int outfd = -1;
3645
3646                 errno = 0;
3647                 /* While ast_waitfor_nandfds tries to help by reducing the timeout by how much was waited,
3648                  * it is unhelpful if it waited less than a millisecond.
3649                  */
3650                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3651
3652                 if (!rchan && outfd < 0 && ms) {
3653                         if (errno == 0 || errno == EINTR)
3654                                 continue;
3655                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
3656                         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3657                         return -1;
3658                 } else if (outfd > -1) {
3659                         /* The FD we were watching has something waiting */
3660                         ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
3661                         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3662                         return 1;
3663                 } else if (rchan) {
3664                         int res;
3665                         struct ast_frame *f = ast_read(c);
3666                         if (!f)
3667                                 return -1;
3668
3669                         switch (f->frametype) {
3670                         case AST_FRAME_DTMF_BEGIN:
3671                                 break;
3672                         case AST_FRAME_DTMF_END:
3673                                 res = f->subclass.integer;
3674                                 ast_frfree(f);
3675                                 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3676                                 return res;
3677                         case AST_FRAME_CONTROL:
3678                                 switch (f->subclass.integer) {
3679                                 case AST_CONTROL_HANGUP:
3680                                         ast_frfree(f);
3681                                         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3682                                         return -1;
3683                                 case AST_CONTROL_STREAM_STOP:
3684                                 case AST_CONTROL_STREAM_SUSPEND:
3685                                 case AST_CONTROL_STREAM_RESTART:
3686                                 case AST_CONTROL_STREAM_REVERSE:
3687                                 case AST_CONTROL_STREAM_FORWARD:
3688                                         /* Fall-through and treat as if it were a DTMF signal. Items
3689                                          * that perform stream control will handle this. */
3690                                         res = f->subclass.integer;
3691                                         ast_frfree(f);
3692                                         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3693                                         return res;
3694                                 case AST_CONTROL_PVT_CAUSE_CODE:
3695                                 case AST_CONTROL_RINGING:
3696                                 case AST_CONTROL_ANSWER:
3697                                 case AST_CONTROL_SRCUPDATE:
3698                                 case AST_CONTROL_SRCCHANGE:
3699                                 case AST_CONTROL_CONNECTED_LINE:
3700                                 case AST_CONTROL_REDIRECTING:
3701                                 case AST_CONTROL_UPDATE_RTP_PEER:
3702                                 case AST_CONTROL_HOLD:
3703                                 case AST_CONTROL_UNHOLD:
3704                                 case -1:
3705                                         /* Unimportant */
3706                                         break;
3707                                 default:
3708                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
3709                                         break;
3710                                 }
3711                                 break;
3712                         case AST_FRAME_VOICE:
3713                                 /* Write audio if appropriate */
3714                                 if (audiofd > -1) {
3715                                         if (write(audiofd, f->data.ptr, f->datalen) < 0) {
3716                                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3717                                         }
3718                                 }
3719                         default:
3720                                 /* Ignore */
3721                                 break;
3722                         }
3723                         ast_frfree(f);
3724                 }
3725         }
3726
3727         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3728
3729         return 0; /* Time is up */
3730 }
3731
3732 enum DtmfDirection {
3733         DTMF_RECEIVED,
3734         DTMF_SENT
3735 };
3736
3737 static const char *dtmf_direction_to_string(enum DtmfDirection direction)
3738 {
3739         switch (direction) {
3740         case DTMF_RECEIVED:
3741                 return "Received";
3742         case DTMF_SENT:
3743                 return "Sent";
3744         }
3745
3746         return "?";
3747 }
3748
3749 static void send_dtmf_begin_event(struct ast_channel *chan,
3750         enum DtmfDirection direction, const char digit)
3751 {
3752         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
3753         char digit_str[] = { digit, '\0' };
3754
3755         blob = ast_json_pack("{ s: s, s: s }",
3756                 "digit", digit_str,
3757                 "direction", dtmf_direction_to_string(direction));
3758         if (!blob) {
3759                 return;
3760         }
3761
3762         publish_channel_blob(chan, ast_channel_dtmf_begin_type(), blob);
3763 }
3764
3765 static void send_dtmf_end_event(struct ast_channel *chan,
3766         enum DtmfDirection direction, const char digit, long duration_ms)
3767 {
3768         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
3769         char digit_str[] = { digit, '\0' };
3770
3771         blob = ast_json_pack("{ s: s, s: s, s: i }",
3772                 "digit", digit_str,
3773                 "direction", dtmf_direction_to_string(direction),
3774                 "duration_ms", duration_ms);
3775         if (!blob) {
3776                 return;
3777         }
3778
3779         publish_channel_blob(chan, ast_channel_dtmf_end_type(), blob);
3780 }
3781
3782 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
3783 {
3784         if (ast_channel_generator(chan) && ast_channel_generator(chan)->generate && ast_channel_generatordata(chan) &&  !ast_internal_timing_enabled(chan)) {
3785                 void *tmp = ast_channel_generatordata(chan);
3786                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = ast_channel_generator(chan)->generate;
3787                 int res;
3788                 int samples;
3789
3790                 if (ast_channel_timingfunc(chan)) {
3791                         ast_debug(1, "Generator got voice, switching to phase locked mode\n");
3792                         ast_settimeout(chan, 0, NULL, NULL);
3793                 }
3794
3795                 ast_channel_generatordata_set(chan, NULL);     /* reset, to let writes go through */
3796
3797                 if (ast_format_cmp(&f->subclass.format, ast_channel_writeformat(chan)) == AST_FORMAT_CMP_NOT_EQUAL) {
3798                         float factor;
3799                         factor = ((float) ast_format_rate(ast_channel_writeformat(chan))) / ((float) ast_format_rate(&f->subclass.format));
3800                         samples = (int) ( ((float) f->samples) * factor );
3801                 } else {
3802                         samples = f->samples;
3803                 }
3804
3805                 /* This unlock is here based on two assumptions that hold true at this point in the
3806                  * code. 1) this function is only called from within __ast_read() and 2) all generators
3807                  * call ast_write() in their generate callback.
3808                  *
3809                  * The reason this is added is so that when ast_write is called, the lock that occurs
3810                  * there will not recursively lock the channel. Doing this will cause intended deadlock
3811                  * avoidance not to work in deeper functions
3812                  */
3813                 ast_channel_unlock(chan);
3814                 res = generate(chan, tmp, f->datalen, samples);
3815                 ast_channel_lock(chan);
3816                 ast_channel_generatordata_set(chan, tmp);
3817                 if (res) {
3818                         ast_debug(1, "Auto-deactivating generator\n");
3819                         ast_deactivate_generator(chan);
3820                 }
3821
3822         } else if (f->frametype == AST_FRAME_CNG) {
3823                 if (ast_channel_generator(chan) && !ast_channel_timingfunc(chan) && (ast_channel_timingfd(chan) > -1)) {
3824                         ast_debug(1, "Generator got CNG, switching to timed mode\n");
3825                         ast_settimeout(chan, 50, generator_force, chan);
3826                 }
3827         }
3828 }
3829
3830 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3831 {
3832         struct ast_frame *fr = ast_channel_dtmff(chan);
3833
3834         fr->frametype = AST_FRAME_DTMF_END;
3835         fr->subclass.integer = f->subclass.integer;
3836         fr->len = f->len;
3837
3838         /* The only time this function will be called is for a frame that just came
3839          * out of the channel driver.  So, we want to stick it on the tail of the
3840          * readq. */
3841
3842         ast_queue_frame(chan, fr);
3843 }
3844
3845 /*!
3846  * \brief Determine whether or not we should ignore DTMF in the readq
3847  */
3848 static inline int should_skip_dtmf(struct ast_channel *chan)
3849 {
3850         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
3851                 /* We're in the middle of emulating a digit, or DTMF has been
3852                  * explicitly deferred.  Skip this digit, then. */
3853                 return 1;
3854         }
3855
3856         if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
3857                         ast_tvdiff_ms(ast_tvnow(), *ast_channel_dtmf_tv(chan)) < AST_MIN_DTMF_GAP) {
3858                 /* We're not in the middle of a digit, but it hasn't been long enough
3859                  * since the last digit, so we'll have to skip DTMF for now. */
3860                 return 1;
3861         }
3862
3863         return 0;
3864 }
3865
3866 /*!
3867  * \brief calculates the number of samples to jump forward with in a monitor stream.
3868
3869  * \note When using ast_seekstream() with the read and write streams of a monitor,
3870  * the number of samples to seek forward must be of the same sample rate as the stream
3871  * or else the jump will not be calculated correctly.
3872  *
3873  * \retval number of samples to seek forward after rate conversion.
3874  */
3875 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
3876 {
3877         int diff = sample_rate - seek_rate;
3878
3879         if (diff > 0) {
3880                 samples = samples / (float) (sample_rate / seek_rate);
3881         } else if (diff < 0) {
3882                 samples = samples * (float) (seek_rate / sample_rate);
3883         }
3884
3885         return samples;
3886 }
3887
3888 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
3889 {
3890         struct ast_frame *f = NULL;     /* the return value */
3891         int prestate;
3892         int cause = 0;
3893
3894         /* this function is very long so make sure there is only one return
3895          * point at the end (there are only two exceptions to this).
3896          */
3897
3898         if (ast_channel_masq(chan)) {
3899                 ast_do_masquerade(chan);
3900                 return &ast_null_frame;
3901         }
3902
3903         /* if here, no masq has happened, lock the channel and proceed */
3904         ast_channel_lock(chan);