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