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