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