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