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