Add red-black tree container type to astobj2.
[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 timeout_ms, int (*cond)(void*), void *data)
1673 {
1674         struct ast_frame *f;
1675         struct ast_silence_generator *silgen = NULL;
1676         int res = 0;
1677         struct timeval start;
1678         int ms;
1679         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1680
1681         AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1682
1683         /* If no other generator is present, start silencegen while waiting */
1684         if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1685                 silgen = ast_channel_start_silence_generator(chan);
1686         }
1687
1688         start = ast_tvnow();
1689         while ((ms = ast_remaining_ms(start, timeout_ms))) {
1690                 struct ast_frame *dup_f = NULL;
1691
1692                 if (cond && ((*cond)(data) == 0)) {
1693                         break;
1694                 }
1695                 ms = ast_waitfor(chan, ms);
1696                 if (ms < 0) {
1697                         res = -1;
1698                         break;
1699                 }
1700                 if (ms > 0) {
1701                         f = ast_read(chan);
1702                         if (!f) {
1703                                 res = -1;
1704                                 break;
1705                         }
1706
1707                         if (!ast_is_deferrable_frame(f)) {
1708                                 ast_frfree(f);
1709                                 continue;
1710                         }
1711
1712                         if ((dup_f = ast_frisolate(f))) {
1713                                 if (dup_f != f) {
1714                                         ast_frfree(f);
1715                                 }
1716                                 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1717                         }
1718                 }
1719         }
1720
1721         /* stop silgen if present */
1722         if (silgen) {
1723                 ast_channel_stop_silence_generator(chan, silgen);
1724         }
1725
1726         /* We need to free all the deferred frames, but we only need to
1727          * queue the deferred frames if there was no error and no
1728          * hangup was received
1729          */
1730         ast_channel_lock(chan);
1731         while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1732                 if (!res) {
1733                         ast_queue_frame_head(chan, f);
1734                 }
1735                 ast_frfree(f);
1736         }
1737         ast_channel_unlock(chan);
1738
1739         return res;
1740 }
1741
1742 /*! \brief Wait, look for hangups */
1743 int ast_safe_sleep(struct ast_channel *chan, int ms)
1744 {
1745         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1746 }
1747
1748 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1749 {
1750         /* Safe, even if already unlinked. */
1751         ao2_unlink(channels, chan);
1752         return ast_channel_unref(chan);
1753 }
1754
1755 void ast_party_name_init(struct ast_party_name *init)
1756 {
1757         init->str = NULL;
1758         init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1759         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1760         init->valid = 0;
1761 }
1762
1763 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1764 {
1765         if (dest == src) {
1766                 /* Don't copy to self */
1767                 return;
1768         }
1769
1770         ast_free(dest->str);
1771         dest->str = ast_strdup(src->str);
1772         dest->char_set = src->char_set;
1773         dest->presentation = src->presentation;
1774         dest->valid = src->valid;
1775 }
1776
1777 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1778 {
1779         init->str = NULL;
1780         init->char_set = guide->char_set;
1781         init->presentation = guide->presentation;
1782         init->valid = guide->valid;
1783 }
1784
1785 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1786 {
1787         if (dest == src) {
1788                 /* Don't set to self */
1789                 return;
1790         }
1791
1792         if (src->str && src->str != dest->str) {
1793                 ast_free(dest->str);
1794                 dest->str = ast_strdup(src->str);
1795         }
1796
1797         dest->char_set = src->char_set;
1798         dest->presentation = src->presentation;
1799         dest->valid = src->valid;
1800 }
1801
1802 void ast_party_name_free(struct ast_party_name *doomed)
1803 {
1804         ast_free(doomed->str);
1805         doomed->str = NULL;
1806 }
1807
1808 void ast_party_number_init(struct ast_party_number *init)
1809 {
1810         init->str = NULL;
1811         init->plan = 0;/* Unknown */
1812         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1813         init->valid = 0;
1814 }
1815
1816 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1817 {
1818         if (dest == src) {
1819                 /* Don't copy to self */
1820                 return;
1821         }
1822
1823         ast_free(dest->str);
1824         dest->str = ast_strdup(src->str);
1825         dest->plan = src->plan;
1826         dest->presentation = src->presentation;
1827         dest->valid = src->valid;
1828 }
1829
1830 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1831 {
1832         init->str = NULL;
1833         init->plan = guide->plan;
1834         init->presentation = guide->presentation;
1835         init->valid = guide->valid;
1836 }
1837
1838 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1839 {
1840         if (dest == src) {
1841                 /* Don't set to self */
1842                 return;
1843         }
1844
1845         if (src->str && src->str != dest->str) {
1846                 ast_free(dest->str);
1847                 dest->str = ast_strdup(src->str);
1848         }
1849
1850         dest->plan = src->plan;
1851         dest->presentation = src->presentation;
1852         dest->valid = src->valid;
1853 }
1854
1855 void ast_party_number_free(struct ast_party_number *doomed)
1856 {
1857         ast_free(doomed->str);
1858         doomed->str = NULL;
1859 }
1860
1861 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1862 {
1863         init->str = NULL;
1864         init->type = 0;
1865         init->odd_even_indicator = 0;
1866         init->valid = 0;
1867 }
1868
1869 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1870 {
1871         if (dest == src) {
1872                 /* Don't copy to self */
1873                 return;
1874         }
1875
1876         ast_free(dest->str);
1877         dest->str = ast_strdup(src->str);
1878         dest->type = src->type;
1879         dest->odd_even_indicator = src->odd_even_indicator;
1880         dest->valid = src->valid;
1881 }
1882
1883 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1884 {
1885         init->str = NULL;
1886         init->type = guide->type;
1887         init->odd_even_indicator = guide->odd_even_indicator;
1888         init->valid = guide->valid;
1889 }
1890
1891 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1892 {
1893         if (dest == src) {
1894                 /* Don't set to self */
1895                 return;
1896         }
1897
1898         if (src->str && src->str != dest->str) {
1899                 ast_free(dest->str);
1900                 dest->str = ast_strdup(src->str);
1901         }
1902
1903         dest->type = src->type;
1904         dest->odd_even_indicator = src->odd_even_indicator;
1905         dest->valid = src->valid;
1906 }
1907
1908 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1909 {
1910         ast_free(doomed->str);
1911         doomed->str = NULL;
1912 }
1913
1914 void ast_set_party_id_all(struct ast_set_party_id *update_id)
1915 {
1916         update_id->name = 1;
1917         update_id->number = 1;
1918         update_id->subaddress = 1;
1919 }
1920
1921 void ast_party_id_init(struct ast_party_id *init)
1922 {
1923         ast_party_name_init(&init->name);
1924         ast_party_number_init(&init->number);
1925         ast_party_subaddress_init(&init->subaddress);
1926         init->tag = NULL;
1927 }
1928
1929 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1930 {
1931         if (dest == src) {
1932                 /* Don't copy to self */
1933                 return;
1934         }
1935
1936         ast_party_name_copy(&dest->name, &src->name);
1937         ast_party_number_copy(&dest->number, &src->number);
1938         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1939
1940         ast_free(dest->tag);
1941         dest->tag = ast_strdup(src->tag);
1942 }
1943
1944 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1945 {
1946         ast_party_name_set_init(&init->name, &guide->name);
1947         ast_party_number_set_init(&init->number, &guide->number);
1948         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1949         init->tag = NULL;
1950 }
1951
1952 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1953 {
1954         if (dest == src) {
1955                 /* Don't set to self */
1956                 return;
1957         }
1958
1959         if (!update || update->name) {
1960                 ast_party_name_set(&dest->name, &src->name);
1961         }
1962         if (!update || update->number) {
1963                 ast_party_number_set(&dest->number, &src->number);
1964         }
1965         if (!update || update->subaddress) {
1966                 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1967         }
1968
1969         if (src->tag && src->tag != dest->tag) {
1970                 ast_free(dest->tag);
1971                 dest->tag = ast_strdup(src->tag);
1972         }
1973 }
1974
1975 void ast_party_id_free(struct ast_party_id *doomed)
1976 {
1977         ast_party_name_free(&doomed->name);
1978         ast_party_number_free(&doomed->number);
1979         ast_party_subaddress_free(&doomed->subaddress);
1980
1981         ast_free(doomed->tag);
1982         doomed->tag = NULL;
1983 }
1984
1985 int ast_party_id_presentation(const struct ast_party_id *id)
1986 {
1987         int number_priority;
1988         int number_value;
1989         int number_screening;
1990         int name_priority;
1991         int name_value;
1992
1993         /* Determine name presentation priority. */
1994         if (!id->name.valid) {
1995                 name_value = AST_PRES_UNAVAILABLE;
1996                 name_priority = 3;
1997         } else {
1998                 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1999                 switch (name_value) {
2000                 case AST_PRES_RESTRICTED:
2001                         name_priority = 0;
2002                         break;
2003                 case AST_PRES_ALLOWED:
2004                         name_priority = 1;
2005                         break;
2006                 case AST_PRES_UNAVAILABLE:
2007                         name_priority = 2;
2008                         break;
2009                 default:
2010                         name_value = AST_PRES_UNAVAILABLE;
2011                         name_priority = 3;
2012                         break;
2013                 }
2014         }
2015
2016         /* Determine number presentation priority. */
2017         if (!id->number.valid) {
2018                 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2019                 number_value = AST_PRES_UNAVAILABLE;
2020                 number_priority = 3;
2021         } else {
2022                 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
2023                 number_value = id->number.presentation & AST_PRES_RESTRICTION;
2024                 switch (number_value) {
2025                 case AST_PRES_RESTRICTED:
2026                         number_priority = 0;
2027                         break;
2028                 case AST_PRES_ALLOWED:
2029                         number_priority = 1;
2030                         break;
2031                 case AST_PRES_UNAVAILABLE:
2032                         number_priority = 2;
2033                         break;
2034                 default:
2035                         number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2036                         number_value = AST_PRES_UNAVAILABLE;
2037                         number_priority = 3;
2038                         break;
2039                 }
2040         }
2041
2042         /* Select the wining presentation value. */
2043         if (name_priority < number_priority) {
2044                 number_value = name_value;
2045         }
2046         if (number_value == AST_PRES_UNAVAILABLE) {
2047                 return AST_PRES_NUMBER_NOT_AVAILABLE;
2048         }
2049
2050         return number_value | number_screening;
2051 }
2052
2053 void ast_party_id_invalidate(struct ast_party_id *id)
2054 {
2055         id->name.valid = 0;
2056         id->number.valid = 0;
2057         id->subaddress.valid = 0;
2058 }
2059
2060 void ast_party_id_reset(struct ast_party_id *id)
2061 {
2062         ast_party_id_free(id);
2063         ast_party_id_init(id);
2064 }
2065
2066 struct ast_party_id ast_party_id_merge(struct ast_party_id *base, struct ast_party_id *overlay)
2067 {
2068         struct ast_party_id merged;
2069
2070         merged = *base;
2071         if (overlay->name.valid) {
2072                 merged.name = overlay->name;
2073         }
2074         if (overlay->number.valid) {
2075                 merged.number = overlay->number;
2076         }
2077         if (overlay->subaddress.valid) {
2078                 merged.subaddress = overlay->subaddress;
2079         }
2080         /* Note the actual structure is returned and not a pointer to it! */
2081         return merged;
2082 }
2083
2084 void ast_party_id_merge_copy(struct ast_party_id *dest, struct ast_party_id *base, struct ast_party_id *overlay)
2085 {
2086         struct ast_party_id merged;
2087
2088         merged = ast_party_id_merge(base, overlay);
2089         ast_party_id_copy(dest, &merged);
2090 }
2091
2092 void ast_party_dialed_init(struct ast_party_dialed *init)
2093 {
2094         init->number.str = NULL;
2095         init->number.plan = 0;/* Unknown */
2096         ast_party_subaddress_init(&init->subaddress);
2097         init->transit_network_select = 0;
2098 }
2099
2100 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2101 {
2102         if (dest == src) {
2103                 /* Don't copy to self */
2104                 return;
2105         }
2106
2107         ast_free(dest->number.str);
2108         dest->number.str = ast_strdup(src->number.str);
2109         dest->number.plan = src->number.plan;
2110         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2111         dest->transit_network_select = src->transit_network_select;
2112 }
2113
2114 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2115 {
2116         init->number.str = NULL;
2117         init->number.plan = guide->number.plan;
2118         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2119         init->transit_network_select = guide->transit_network_select;
2120 }
2121
2122 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2123 {
2124         if (src->number.str && src->number.str != dest->number.str) {
2125                 ast_free(dest->number.str);
2126                 dest->number.str = ast_strdup(src->number.str);
2127         }
2128         dest->number.plan = src->number.plan;
2129
2130         ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2131
2132         dest->transit_network_select = src->transit_network_select;
2133 }
2134
2135 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2136 {
2137         ast_free(doomed->number.str);
2138         doomed->number.str = NULL;
2139         ast_party_subaddress_free(&doomed->subaddress);
2140 }
2141
2142 void ast_party_caller_init(struct ast_party_caller *init)
2143 {
2144         ast_party_id_init(&init->id);
2145         ast_party_id_init(&init->ani);
2146         ast_party_id_init(&init->priv);
2147         init->ani2 = 0;
2148 }
2149
2150 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2151 {
2152         if (dest == src) {
2153                 /* Don't copy to self */
2154                 return;
2155         }
2156
2157         ast_party_id_copy(&dest->id, &src->id);
2158         ast_party_id_copy(&dest->ani, &src->ani);
2159         ast_party_id_copy(&dest->priv, &src->priv);
2160         dest->ani2 = src->ani2;
2161 }
2162
2163 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2164 {
2165         ast_party_id_set_init(&init->id, &guide->id);
2166         ast_party_id_set_init(&init->ani, &guide->ani);
2167         ast_party_id_set_init(&init->priv, &guide->priv);
2168         init->ani2 = guide->ani2;
2169 }
2170
2171 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2172 {
2173         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2174         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2175         ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2176         dest->ani2 = src->ani2;
2177 }
2178
2179 void ast_party_caller_free(struct ast_party_caller *doomed)
2180 {
2181         ast_party_id_free(&doomed->id);
2182         ast_party_id_free(&doomed->ani);
2183         ast_party_id_free(&doomed->priv);
2184 }
2185
2186 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2187 {
2188         ast_party_id_init(&init->id);
2189         ast_party_id_init(&init->ani);
2190         ast_party_id_init(&init->priv);
2191         init->ani2 = 0;
2192         init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2193 }
2194
2195 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2196 {
2197         if (dest == src) {
2198                 /* Don't copy to self */
2199                 return;
2200         }
2201
2202         ast_party_id_copy(&dest->id, &src->id);
2203         ast_party_id_copy(&dest->ani, &src->ani);
2204         ast_party_id_copy(&dest->priv, &src->priv);
2205         dest->ani2 = src->ani2;
2206         dest->source = src->source;
2207 }
2208
2209 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2210 {
2211         ast_party_id_set_init(&init->id, &guide->id);
2212         ast_party_id_set_init(&init->ani, &guide->ani);
2213         ast_party_id_set_init(&init->priv, &guide->priv);
2214         init->ani2 = guide->ani2;
2215         init->source = guide->source;
2216 }
2217
2218 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)
2219 {
2220         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2221         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2222         ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2223         dest->ani2 = src->ani2;
2224         dest->source = src->source;
2225 }
2226
2227 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2228 {
2229         connected->id = caller->id;
2230         connected->ani = caller->ani;
2231         connected->priv = caller->priv;
2232         connected->ani2 = caller->ani2;
2233         connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2234 }
2235
2236 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2237 {
2238         ast_party_id_free(&doomed->id);
2239         ast_party_id_free(&doomed->ani);
2240         ast_party_id_free(&doomed->priv);
2241 }
2242
2243 void ast_party_redirecting_reason_init(struct ast_party_redirecting_reason *init)
2244 {
2245         init->str = NULL;
2246         init->code = AST_REDIRECTING_REASON_UNKNOWN;
2247 }
2248
2249 void ast_party_redirecting_reason_copy(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2250 {
2251         if (dest == src) {
2252                 return;
2253         }
2254
2255         ast_free(dest->str);
2256         dest->str = ast_strdup(src->str);
2257         dest->code = src->code;
2258 }
2259
2260 void ast_party_redirecting_reason_set_init(struct ast_party_redirecting_reason *init, const struct ast_party_redirecting_reason *guide)
2261 {
2262         init->str = NULL;
2263         init->code = guide->code;
2264 }
2265
2266 void ast_party_redirecting_reason_set(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2267 {
2268         if (dest == src) {
2269                 return;
2270         }
2271
2272         if (src->str && src->str != dest->str) {
2273                 ast_free(dest->str);
2274                 dest->str = ast_strdup(src->str);
2275         }
2276
2277         dest->code = src->code;
2278 }
2279
2280 void ast_party_redirecting_reason_free(struct ast_party_redirecting_reason *doomed)
2281 {
2282         ast_free(doomed->str);
2283 }
2284
2285
2286 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2287 {
2288         ast_party_id_init(&init->orig);
2289         ast_party_id_init(&init->from);
2290         ast_party_id_init(&init->to);
2291         ast_party_id_init(&init->priv_orig);
2292         ast_party_id_init(&init->priv_from);
2293         ast_party_id_init(&init->priv_to);
2294         ast_party_redirecting_reason_init(&init->reason);
2295         ast_party_redirecting_reason_init(&init->orig_reason);
2296         init->count = 0;
2297 }
2298
2299 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2300 {
2301         if (dest == src) {
2302                 /* Don't copy to self */
2303                 return;
2304         }
2305
2306         ast_party_id_copy(&dest->orig, &src->orig);
2307         ast_party_id_copy(&dest->from, &src->from);
2308         ast_party_id_copy(&dest->to, &src->to);
2309         ast_party_id_copy(&dest->priv_orig, &src->priv_orig);
2310         ast_party_id_copy(&dest->priv_from, &src->priv_from);
2311         ast_party_id_copy(&dest->priv_to, &src->priv_to);
2312         ast_party_redirecting_reason_copy(&dest->reason, &src->reason);
2313         ast_party_redirecting_reason_copy(&dest->orig_reason, &src->orig_reason);
2314         dest->count = src->count;
2315 }
2316
2317 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2318 {
2319         ast_party_id_set_init(&init->orig, &guide->orig);
2320         ast_party_id_set_init(&init->from, &guide->from);
2321         ast_party_id_set_init(&init->to, &guide->to);
2322         ast_party_id_set_init(&init->priv_orig, &guide->priv_orig);
2323         ast_party_id_set_init(&init->priv_from, &guide->priv_from);
2324         ast_party_id_set_init(&init->priv_to, &guide->priv_to);
2325         ast_party_redirecting_reason_set_init(&init->reason, &guide->reason);
2326         ast_party_redirecting_reason_set_init(&init->orig_reason, &guide->orig_reason);
2327         init->count = guide->count;
2328 }
2329
2330 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2331 {
2332         ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2333         ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2334         ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2335         ast_party_id_set(&dest->priv_orig, &src->priv_orig, update ? &update->priv_orig : NULL);
2336         ast_party_id_set(&dest->priv_from, &src->priv_from, update ? &update->priv_from : NULL);
2337         ast_party_id_set(&dest->priv_to, &src->priv_to, update ? &update->priv_to : NULL);
2338         ast_party_redirecting_reason_set(&dest->reason, &src->reason);
2339         ast_party_redirecting_reason_set(&dest->orig_reason, &src->orig_reason);
2340         dest->count = src->count;
2341 }
2342
2343 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2344 {
2345         ast_party_id_free(&doomed->orig);
2346         ast_party_id_free(&doomed->from);
2347         ast_party_id_free(&doomed->to);
2348         ast_party_id_free(&doomed->priv_orig);
2349         ast_party_id_free(&doomed->priv_from);
2350         ast_party_id_free(&doomed->priv_to);
2351         ast_party_redirecting_reason_free(&doomed->reason);
2352         ast_party_redirecting_reason_free(&doomed->orig_reason);
2353 }
2354
2355 /*! \brief Free a channel structure */
2356 static void ast_channel_destructor(void *obj)
2357 {
2358         struct ast_channel *chan = obj;
2359 #ifdef HAVE_EPOLL
2360         int i;
2361 #endif
2362         struct ast_var_t *vardata;
2363         struct ast_frame *f;
2364         struct varshead *headp;
2365         struct ast_datastore *datastore;
2366         char device_name[AST_CHANNEL_NAME];
2367         struct ast_callid *callid;
2368
2369         if (ast_channel_internal_is_finalized(chan)) {
2370                 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2371                 ast_cel_check_retire_linkedid(chan);
2372         }
2373
2374         ast_pbx_hangup_handler_destroy(chan);
2375
2376         ast_channel_lock(chan);
2377
2378         /* Get rid of each of the data stores on the channel */
2379         while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2380                 /* Free the data store */
2381                 ast_datastore_free(datastore);
2382
2383         /* While the channel is locked, take the reference to its callid while we tear down the call. */
2384         callid = ast_channel_callid(chan);
2385         ast_channel_callid_cleanup(chan);
2386
2387         ast_channel_unlock(chan);
2388
2389         /* Lock and unlock the channel just to be sure nobody has it locked still
2390            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2391         ast_channel_lock(chan);
2392         ast_channel_unlock(chan);
2393
2394         if (ast_channel_tech_pvt(chan)) {
2395                 ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2396                 ast_free(ast_channel_tech_pvt(chan));
2397         }
2398
2399         if (ast_channel_sched(chan)) {
2400                 ast_sched_context_destroy(ast_channel_sched(chan));
2401         }
2402
2403         if (ast_channel_internal_is_finalized(chan)) {
2404                 char *dashptr;
2405
2406                 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2407                 if ((dashptr = strrchr(device_name, '-'))) {
2408                         *dashptr = '\0';
2409                 }
2410         } else {
2411                 device_name[0] = '\0';
2412         }
2413
2414         /* Stop monitoring */
2415         if (ast_channel_monitor(chan))
2416                 ast_channel_monitor(chan)->stop( chan, 0 );
2417
2418         /* If there is native format music-on-hold state, free it */
2419         if (ast_channel_music_state(chan))
2420                 ast_moh_cleanup(chan);
2421
2422         /* Free translators */
2423         if (ast_channel_readtrans(chan))
2424                 ast_translator_free_path(ast_channel_readtrans(chan));
2425         if (ast_channel_writetrans(chan))
2426                 ast_translator_free_path(ast_channel_writetrans(chan));
2427         if (ast_channel_pbx(chan))
2428                 ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2429
2430         ast_party_dialed_free(ast_channel_dialed(chan));
2431         ast_party_caller_free(ast_channel_caller(chan));
2432         ast_party_connected_line_free(ast_channel_connected(chan));
2433         ast_party_redirecting_free(ast_channel_redirecting(chan));
2434
2435         /* Close pipes if appropriate */
2436         ast_channel_internal_alertpipe_close(chan);
2437         if (ast_channel_timer(chan)) {
2438                 ast_timer_close(ast_channel_timer(chan));
2439                 ast_channel_timer_set(chan, NULL);
2440         }
2441 #ifdef HAVE_EPOLL
2442         for (i = 0; i < AST_MAX_FDS; i++) {
2443                 if (ast_channel_internal_epfd_data(chan, i)) {
2444                         ast_free(ast_channel_internal_epfd_data(chan, i));
2445                 }
2446         }
2447         close(ast_channel_epfd(chan));
2448 #endif
2449         while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2450                 ast_frfree(f);
2451
2452         /* loop over the variables list, freeing all data and deleting list items */
2453         /* no need to lock the list, as the channel is already locked */
2454         headp = ast_channel_varshead(chan);
2455         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2456                 ast_var_delete(vardata);
2457
2458         ast_app_group_discard(chan);
2459
2460         /* Destroy the jitterbuffer */
2461         ast_jb_destroy(chan);
2462
2463         if (ast_channel_cdr(chan)) {
2464                 ast_cdr_discard(ast_channel_cdr(chan));
2465                 ast_channel_cdr_set(chan, NULL);
2466         }
2467
2468         if (ast_channel_zone(chan)) {
2469                 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2470         }
2471
2472         ast_channel_internal_cleanup(chan);
2473
2474         if (device_name[0]) {
2475                 /*
2476                  * We have a device name to notify of a new state.
2477                  *
2478                  * Queue an unknown state, because, while we know that this particular
2479                  * instance is dead, we don't know the state of all other possible
2480                  * instances.
2481                  */
2482                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2483         }
2484
2485         ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2486         if (callid) {
2487                 ast_callid_unref(callid);
2488         }
2489
2490         ast_channel_named_callgroups_set(chan, NULL);
2491         ast_channel_named_pickupgroups_set(chan, NULL);
2492
2493         ast_atomic_fetchadd_int(&chancount, -1);
2494 }
2495
2496 /*! \brief Free a dummy channel structure */
2497 static void ast_dummy_channel_destructor(void *obj)
2498 {
2499         struct ast_channel *chan = obj;
2500         struct ast_datastore *datastore;
2501         struct ast_var_t *vardata;
2502         struct varshead *headp;
2503
2504         ast_pbx_hangup_handler_destroy(chan);
2505
2506         /* Get rid of each of the data stores on the channel */
2507         while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
2508                 /* Free the data store */
2509                 ast_datastore_free(datastore);
2510         }
2511
2512         ast_party_dialed_free(ast_channel_dialed(chan));
2513         ast_party_caller_free(ast_channel_caller(chan));
2514         ast_party_connected_line_free(ast_channel_connected(chan));
2515         ast_party_redirecting_free(ast_channel_redirecting(chan));
2516
2517         /* loop over the variables list, freeing all data and deleting list items */
2518         /* no need to lock the list, as the channel is already locked */
2519         headp = ast_channel_varshead(chan);
2520         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2521                 ast_var_delete(vardata);
2522
2523         if (ast_channel_cdr(chan)) {
2524                 ast_cdr_discard(ast_channel_cdr(chan));
2525                 ast_channel_cdr_set(chan, NULL);
2526         }
2527
2528         ast_channel_internal_cleanup(chan);
2529 }
2530
2531 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2532 {
2533         return ast_datastore_alloc(info, uid);
2534 }
2535
2536 int ast_channel_datastore_free(struct ast_datastore *datastore)
2537 {
2538         return ast_datastore_free(datastore);
2539 }
2540
2541 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2542 {
2543         struct ast_datastore *datastore = NULL, *datastore2;
2544
2545         AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2546                 if (datastore->inheritance > 0) {
2547                         datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2548                         if (datastore2) {
2549                                 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2550                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2551                                 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2552                         }
2553                 }
2554         }
2555         return 0;
2556 }
2557
2558 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2559 {
2560         int res = 0;
2561
2562         AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2563
2564         return res;
2565 }
2566
2567 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2568 {
2569         return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2570 }
2571
2572 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2573 {
2574         struct ast_datastore *datastore = NULL;
2575
2576         if (info == NULL)
2577                 return NULL;
2578
2579         AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2580                 if (datastore->info != info) {
2581                         continue;
2582                 }
2583
2584                 if (uid == NULL) {
2585                         /* matched by type only */
2586                         break;
2587                 }
2588
2589                 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2590                         /* Matched by type AND uid */
2591                         break;
2592                 }
2593         }
2594
2595         return datastore;
2596 }
2597
2598 /*! Set the file descriptor on the channel */
2599 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2600 {
2601 #ifdef HAVE_EPOLL
2602         struct epoll_event ev;
2603         struct ast_epoll_data *aed = NULL;
2604
2605         if (ast_channel_fd_isset(chan, which)) {
2606                 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2607                 aed = ast_channel_internal_epfd_data(chan, which);
2608         }
2609
2610         /* If this new fd is valid, add it to the epoll */
2611         if (fd > -1) {
2612                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2613                         return;
2614
2615                 ast_channel_internal_epfd_data_set(chan, which, aed);
2616                 aed->chan = chan;
2617                 aed->which = which;
2618
2619                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2620                 ev.data.ptr = aed;
2621                 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2622         } else if (aed) {
2623                 /* We don't have to keep around this epoll data structure now */
2624                 ast_free(aed);
2625                 ast_channel_epfd_data_set(chan, which, NULL);
2626         }
2627 #endif
2628         ast_channel_internal_fd_set(chan, which, fd);
2629         return;
2630 }
2631
2632 /*! Add a channel to an optimized waitfor */
2633 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2634 {
2635 #ifdef HAVE_EPOLL
2636         struct epoll_event ev;
2637         int i = 0;
2638
2639         if (ast_channel_epfd(chan0) == -1)
2640                 return;
2641
2642         /* Iterate through the file descriptors on chan1, adding them to chan0 */
2643         for (i = 0; i < AST_MAX_FDS; i++) {
2644                 if (!ast_channel_fd_isset(chan1, i)) {
2645                         continue;
2646                 }
2647                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2648                 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2649                 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2650         }
2651
2652 #endif
2653         return;
2654 }
2655
2656 /*! Delete a channel from an optimized waitfor */
2657 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2658 {
2659 #ifdef HAVE_EPOLL
2660         struct epoll_event ev;
2661         int i = 0;
2662
2663         if (ast_channel_epfd(chan0) == -1)
2664                 return;
2665
2666         for (i = 0; i < AST_MAX_FDS; i++) {
2667                 if (!ast_channel_fd_isset(chan1, i)) {
2668                         continue;
2669                 }
2670                 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2671         }
2672
2673 #endif
2674         return;
2675 }
2676
2677 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2678 {
2679         ast_channel_lock(chan);
2680
2681         ast_channel_softhangup_internal_flag_clear(chan, flag);
2682
2683         if (!ast_channel_softhangup_internal_flag(chan)) {
2684                 struct ast_frame *fr;
2685
2686                 /* If we have completely cleared the softhangup flag,
2687                  * then we need to fully abort the hangup process.  This requires
2688                  * pulling the END_OF_Q frame out of the channel frame queue if it
2689                  * still happens to be there. */
2690
2691                 fr = AST_LIST_LAST(ast_channel_readq(chan));
2692                 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2693                                 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2694                         AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2695                         ast_frfree(fr);
2696                 }
2697         }
2698
2699         ast_channel_unlock(chan);
2700 }
2701
2702 /*! \brief Softly hangup a channel, don't lock */
2703 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2704 {
2705         ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2706         /* Inform channel driver that we need to be hung up, if it cares */
2707         ast_channel_softhangup_internal_flag_add(chan, cause);
2708         ast_queue_frame(chan, &ast_null_frame);
2709         /* Interrupt any poll call or such */
2710         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2711                 pthread_kill(ast_channel_blocker(chan), SIGURG);
2712         return 0;
2713 }
2714
2715 /*! \brief Softly hangup a channel, lock */
2716 int ast_softhangup(struct ast_channel *chan, int cause)
2717 {
2718         int res;
2719
2720         ast_channel_lock(chan);
2721         res = ast_softhangup_nolock(chan, cause);
2722         /*** DOCUMENTATION
2723                 <managerEventInstance>
2724                         <synopsis>Raised when a soft hangup is requested with a specific cause code.</synopsis>
2725                                 <syntax>
2726                                         <xi:include xpointer="xpointer(/docs/managerEvent[@name='Hangup']/managerEventInstance/syntax/parameter[@name='Cause'])" />
2727                                 </syntax>
2728                 </managerEventInstance>
2729         ***/
2730         manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2731                 "Channel: %s\r\n"
2732                 "Uniqueid: %s\r\n"
2733                 "Cause: %d\r\n",
2734                 ast_channel_name(chan),
2735                 ast_channel_uniqueid(chan),
2736                 cause);
2737         ast_channel_unlock(chan);
2738
2739         return res;
2740 }
2741
2742 static void free_translation(struct ast_channel *clonechan)
2743 {
2744         if (ast_channel_writetrans(clonechan))
2745                 ast_translator_free_path(ast_channel_writetrans(clonechan));
2746         if (ast_channel_readtrans(clonechan))
2747                 ast_translator_free_path(ast_channel_readtrans(clonechan));
2748         ast_channel_writetrans_set(clonechan, NULL);
2749         ast_channel_readtrans_set(clonechan, NULL);
2750         if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2751                 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2752                 ast_format_clear(ast_channel_rawreadformat(clonechan));
2753         } else {
2754                 struct ast_format tmpfmt;
2755                 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2756                 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2757                 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2758         }
2759 }
2760
2761 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2762 {
2763         struct ast_channel *bridge;
2764
2765         ast_channel_lock(chan);
2766         if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2767                 ast_channel_hangupsource_set(chan, source);
2768         }
2769         bridge = ast_bridged_channel(chan);
2770         if (bridge) {
2771                 ast_channel_ref(bridge);
2772         }
2773         ast_channel_unlock(chan);
2774
2775         if (bridge) {
2776                 ast_channel_lock(bridge);
2777                 if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
2778                         ast_channel_hangupsource_set(bridge, source);
2779                 }
2780                 ast_channel_unlock(bridge);
2781                 ast_channel_unref(bridge);
2782         }
2783 }
2784
2785 static void destroy_hooks(struct ast_channel *chan)
2786 {
2787         if (ast_channel_audiohooks(chan)) {
2788                 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2789                 ast_channel_audiohooks_set(chan, NULL);
2790         }
2791
2792         ast_framehook_list_destroy(chan);
2793 }
2794
2795 /*! \brief Hangup a channel */
2796 int ast_hangup(struct ast_channel *chan)
2797 {
2798         char extra_str[64]; /* used for cel logging below */
2799
2800         ast_autoservice_stop(chan);
2801
2802         ast_channel_lock(chan);
2803
2804         /*
2805          * Do the masquerade if someone is setup to masquerade into us.
2806          *
2807          * NOTE: We must hold the channel lock after testing for a
2808          * pending masquerade and setting the channel as a zombie to
2809          * prevent __ast_channel_masquerade() from setting up a
2810          * masquerade with a dead channel.
2811          */
2812         while (ast_channel_masq(chan)) {
2813                 ast_channel_unlock(chan);
2814                 ast_do_masquerade(chan);
2815                 ast_channel_lock(chan);
2816         }
2817
2818         if (ast_channel_masqr(chan)) {
2819                 /*
2820                  * This channel is one which will be masqueraded into something.
2821                  * Mark it as a zombie already so ast_do_masquerade() will know
2822                  * to free it later.
2823                  */
2824                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2825                 destroy_hooks(chan);
2826                 ast_channel_unlock(chan);
2827                 return 0;
2828         }
2829
2830         /* Mark as a zombie so a masquerade cannot be setup on this channel. */
2831         ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2832
2833         ast_channel_unlock(chan);
2834
2835         /*
2836          * XXX if running the hangup handlers here causes problems
2837          * because the handlers take too long to execute, we could move
2838          * the meat of this function into another thread.  A thread
2839          * where channels go to die.
2840          *
2841          * If this is done, ast_autoservice_chan_hangup_peer() will no
2842          * longer be needed.
2843          */
2844         ast_pbx_hangup_handler_run(chan);
2845         ao2_unlink(channels, chan);
2846         ast_channel_lock(chan);
2847
2848         destroy_hooks(chan);
2849
2850         free_translation(chan);
2851         /* Close audio stream */
2852         if (ast_channel_stream(chan)) {
2853                 ast_closestream(ast_channel_stream(chan));
2854                 ast_channel_stream_set(chan, NULL);
2855         }
2856         /* Close video stream */
2857         if (ast_channel_vstream(chan)) {
2858                 ast_closestream(ast_channel_vstream(chan));
2859                 ast_channel_vstream_set(chan, NULL);
2860         }
2861         if (ast_channel_sched(chan)) {
2862                 ast_sched_context_destroy(ast_channel_sched(chan));
2863                 ast_channel_sched_set(chan, NULL);
2864         }
2865
2866         if (ast_channel_generatordata(chan)) {  /* Clear any tone stuff remaining */
2867                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2868                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2869                 }
2870         }
2871         ast_channel_generatordata_set(chan, NULL);
2872         ast_channel_generator_set(chan, NULL);
2873
2874         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"), ""));
2875         ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2876
2877         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2878                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2879                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
2880                         (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2881                 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2882         }
2883
2884         ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2885         if (ast_channel_tech(chan)->hangup) {
2886                 ast_channel_tech(chan)->hangup(chan);
2887         }
2888
2889         ast_channel_unlock(chan);
2890
2891         ast_cc_offer(chan);
2892         /*** DOCUMENTATION
2893                 <managerEventInstance>
2894                         <synopsis>Raised when a channel is hung up.</synopsis>
2895                                 <syntax>
2896                                         <parameter name="Cause">
2897                                                 <para>A numeric cause code for why the channel was hung up.</para>
2898                                         </parameter>
2899                                         <parameter name="Cause-txt">
2900                                                 <para>A description of why the channel was hung up.</para>
2901                                         </parameter>
2902                                 </syntax>
2903                 </managerEventInstance>
2904         ***/
2905         ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2906                 "Channel: %s\r\n"
2907                 "Uniqueid: %s\r\n"
2908                 "CallerIDNum: %s\r\n"
2909                 "CallerIDName: %s\r\n"
2910                 "ConnectedLineNum: %s\r\n"
2911                 "ConnectedLineName: %s\r\n"
2912                 "AccountCode: %s\r\n"
2913                 "Cause: %d\r\n"
2914                 "Cause-txt: %s\r\n",
2915                 ast_channel_name(chan),
2916                 ast_channel_uniqueid(chan),
2917                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
2918                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
2919                 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
2920                 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
2921                 ast_channel_accountcode(chan),
2922                 ast_channel_hangupcause(chan),
2923                 ast_cause2str(ast_channel_hangupcause(chan))
2924                 );
2925
2926         if (ast_channel_cdr(chan) && !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_BRIDGED) &&
2927                 !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_POST_DISABLED) &&
2928                 (ast_channel_cdr(chan)->disposition != AST_CDR_NULL || ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_DIALED))) {
2929                 ast_channel_lock(chan);
2930                 ast_cdr_end(ast_channel_cdr(chan));
2931                 ast_cdr_detach(ast_channel_cdr(chan));
2932                 ast_channel_cdr_set(chan, NULL);
2933                 ast_channel_unlock(chan);
2934         }
2935
2936         ast_channel_unref(chan);
2937
2938         return 0;
2939 }
2940
2941 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2942 {
2943         int res = 0;
2944
2945         ast_channel_lock(chan);
2946
2947         /* You can't answer an outbound call */
2948         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2949                 ast_channel_unlock(chan);
2950                 return 0;
2951         }
2952
2953         /* Stop if we're a zombie or need a soft hangup */
2954         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2955                 ast_channel_unlock(chan);
2956                 return -1;
2957         }
2958
2959         ast_channel_unlock(chan);
2960
2961         switch (ast_channel_state(chan)) {
2962         case AST_STATE_RINGING:
2963         case AST_STATE_RING:
2964                 ast_channel_lock(chan);
2965                 if (ast_channel_tech(chan)->answer) {
2966                         res = ast_channel_tech(chan)->answer(chan);
2967                 }
2968                 ast_setstate(chan, AST_STATE_UP);
2969                 if (cdr_answer) {
2970                         ast_cdr_answer(ast_channel_cdr(chan));
2971                 }
2972                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2973                 ast_channel_unlock(chan);
2974                 break;
2975         case AST_STATE_UP:
2976                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2977                 /* Calling ast_cdr_answer when it it has previously been called
2978                  * is essentially a no-op, so it is safe.
2979                  */
2980                 if (cdr_answer) {
2981                         ast_cdr_answer(ast_channel_cdr(chan));
2982                 }
2983                 break;
2984         default:
2985                 break;
2986         }
2987
2988         ast_indicate(chan, -1);
2989
2990         return res;
2991 }
2992
2993 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2994 {
2995         int res = 0;
2996         enum ast_channel_state old_state;
2997
2998         old_state = ast_channel_state(chan);
2999         if ((res = ast_raw_answer(chan, cdr_answer))) {
3000                 return res;
3001         }
3002
3003         switch (old_state) {
3004         case AST_STATE_RINGING:
3005         case AST_STATE_RING:
3006                 /* wait for media to start flowing, but don't wait any longer
3007                  * than 'delay' or 500 milliseconds, whichever is longer
3008                  */
3009                 do {
3010                         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
3011                         struct ast_frame *cur, *new;
3012                         int timeout_ms = MAX(delay, 500);
3013                         unsigned int done = 0;
3014                         struct timeval start;
3015
3016                         AST_LIST_HEAD_INIT_NOLOCK(&frames);
3017
3018                         start = ast_tvnow();
3019                         for (;;) {
3020                                 int ms = ast_remaining_ms(start, timeout_ms);
3021                                 ms = ast_waitfor(chan, ms);
3022                                 if (ms < 0) {
3023                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
3024                                         res = -1;
3025                                         break;
3026                                 }
3027                                 if (ms == 0) {
3028                                         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));
3029                                         break;
3030                                 }
3031                                 cur = ast_read(chan);
3032                                 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
3033                                              (cur->subclass.integer == AST_CONTROL_HANGUP))) {
3034                                         if (cur) {
3035                                                 ast_frfree(cur);
3036                                         }
3037                                         res = -1;
3038                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
3039                                         break;
3040                                 }
3041
3042                                 if ((new = ast_frisolate(cur)) != cur) {
3043                                         ast_frfree(cur);
3044                                 }
3045
3046                                 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
3047
3048                                 /* if a specific delay period was requested, continue
3049                                  * until that delay has passed. don't stop just because
3050                                  * incoming media has arrived.
3051                                  */
3052                                 if (delay) {
3053                                         continue;
3054                                 }
3055
3056                                 switch (new->frametype) {
3057                                         /* all of these frametypes qualify as 'media' */
3058                                 case AST_FRAME_VOICE:
3059                                 case AST_FRAME_VIDEO:
3060                                 case AST_FRAME_TEXT:
3061                                 case AST_FRAME_DTMF_BEGIN:
3062                                 case AST_FRAME_DTMF_END:
3063                                 case AST_FRAME_IMAGE:
3064                                 case AST_FRAME_HTML:
3065                                 case AST_FRAME_MODEM:
3066                                         done = 1;
3067                                         break;
3068                                 case AST_FRAME_CONTROL:
3069                                 case AST_FRAME_IAX:
3070                                 case AST_FRAME_NULL:
3071                                 case AST_FRAME_CNG:
3072                                         break;
3073                                 }
3074
3075                                 if (done) {
3076                                         break;
3077                                 }
3078                         }
3079
3080                         if (res == 0) {
3081                                 ast_channel_lock(chan);
3082                                 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
3083                                         ast_queue_frame_head(chan, cur);
3084                                         ast_frfree(cur);
3085                                 }
3086                                 ast_channel_unlock(chan);
3087                         }
3088                 } while (0);
3089                 break;
3090         default:
3091                 break;
3092         }
3093
3094         return res;
3095 }
3096
3097 int ast_answer(struct ast_channel *chan)
3098 {
3099         return __ast_answer(chan, 0, 1);
3100 }
3101
3102 void ast_deactivate_generator(struct ast_channel *chan)
3103 {
3104         ast_channel_lock(chan);
3105         if (ast_channel_generatordata(chan)) {
3106                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3107                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3108                 }
3109                 ast_channel_generatordata_set(chan, NULL);
3110                 ast_channel_generator_set(chan, NULL);
3111                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
3112                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
3113                 ast_settimeout(chan, 0, NULL, NULL);
3114         }
3115         ast_channel_unlock(chan);
3116 }
3117
3118 static void generator_write_format_change(struct ast_channel *chan)
3119 {
3120         ast_channel_lock(chan);
3121         if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
3122                 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
3123         }
3124         ast_channel_unlock(chan);
3125 }
3126
3127 static int generator_force(const void *data)
3128 {
3129         /* Called if generator doesn't have data */
3130         void *tmp;
3131         int res;
3132         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
3133         struct ast_channel *chan = (struct ast_channel *)data;
3134
3135         ast_channel_lock(chan);
3136         tmp = ast_channel_generatordata(chan);
3137         ast_channel_generatordata_set(chan, NULL);
3138         if (ast_channel_generator(chan))
3139                 generate = ast_channel_generator(chan)->generate;
3140         ast_channel_unlock(chan);
3141
3142         if (!tmp || !generate)
3143                 return 0;
3144
3145         res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
3146
3147         ast_channel_lock(chan);
3148         if (ast_channel_generator(chan) && generate == ast_channel_generator(chan)->generate) {
3149                 ast_channel_generatordata_set(chan, tmp);
3150         }
3151         ast_channel_unlock(chan);
3152
3153         if (res) {
3154                 ast_debug(1, "Auto-deactivating generator\n");
3155                 ast_deactivate_generator(chan);
3156         }
3157
3158         return 0;
3159 }
3160
3161 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
3162 {
3163         int res = 0;
3164         void *generatordata = NULL;
3165
3166         ast_channel_lock(chan);
3167         if (ast_channel_generatordata(chan)) {
3168                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3169                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3170                 }
3171         }
3172         if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
3173                 res = -1;
3174         }
3175         ast_channel_generatordata_set(chan, generatordata);
3176         if (!res) {
3177                 ast_settimeout(chan, 50, generator_force, chan);
3178                 ast_channel_generator_set(chan, gen);
3179         }
3180         ast_channel_unlock(chan);
3181
3182         ast_prod(chan);
3183
3184         return res;
3185 }
3186
3187 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
3188 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
3189 {
3190         int winner = -1;
3191         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
3192         return winner;
3193 }
3194
3195 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
3196 #ifdef HAVE_EPOLL
3197 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
3198                                         int *exception, int *outfd, int *ms)
3199 #else
3200 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3201                                         int *exception, int *outfd, int *ms)
3202 #endif
3203 {
3204         struct timeval start = { 0 , 0 };
3205         struct pollfd *pfds = NULL;
3206         int res;
3207         long rms;
3208         int x, y, max;
3209         int sz;
3210         struct timeval now = { 0, 0 };
3211         struct timeval whentohangup = { 0, 0 }, diff;
3212         struct ast_channel *winner = NULL;
3213         struct fdmap {
3214                 int chan;
3215                 int fdno;
3216         } *fdmap = NULL;
3217
3218         if (outfd) {
3219                 *outfd = -99999;
3220         }
3221         if (exception) {
3222                 *exception = 0;
3223         }
3224
3225         if ((sz = n * AST_MAX_FDS + nfds)) {
3226                 pfds = ast_alloca(sizeof(*pfds) * sz);
3227                 fdmap = ast_alloca(sizeof(*fdmap) * sz);
3228         } else {
3229                 /* nothing to allocate and no FDs to check */
3230                 return NULL;
3231         }
3232
3233         /* Perform any pending masquerades */
3234         for (x = 0; x < n; x++) {
3235                 while (ast_channel_masq(c[x])) {
3236                         ast_do_masquerade(c[x]);
3237                 }
3238
3239                 ast_channel_lock(c[x]);
3240                 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
3241                         if (ast_tvzero(whentohangup))
3242                                 now = ast_tvnow();
3243                         diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
3244                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3245                                 /* Should already be hungup */
3246                                 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3247                                 ast_channel_unlock(c[x]);
3248                                 return c[x];
3249                         }
3250                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3251                                 whentohangup = diff;
3252                 }
3253                 ast_channel_unlock(c[x]);
3254         }
3255         /* Wait full interval */
3256         rms = *ms;
3257         /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3258         if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3259                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
3260                 if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
3261                         rms =  *ms;
3262                 }
3263         } else if (!ast_tvzero(whentohangup) && rms < 0) {
3264                 /* Tiny corner case... call would need to last >24 days */
3265                 rms = INT_MAX;
3266         }
3267         /*
3268          * Build the pollfd array, putting the channels' fds first,
3269          * followed by individual fds. Order is important because
3270          * individual fd's must have priority over channel fds.
3271          */
3272         max = 0;
3273         for (x = 0; x < n; x++) {
3274                 for (y = 0; y < AST_MAX_FDS; y++) {
3275                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
3276                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
3277                         max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3278                 }
3279                 CHECK_BLOCKING(c[x]);
3280         }
3281         /* Add the individual fds */
3282         for (x = 0; x < nfds; x++) {
3283                 fdmap[max].chan = -1;
3284                 max += ast_add_fd(&pfds[max], fds[x]);
3285         }
3286
3287         if (*ms > 0) {
3288                 start = ast_tvnow();
3289         }
3290
3291         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3292                 do {
3293                         int kbrms = rms;
3294                         if (kbrms > 600000) {
3295                                 kbrms = 600000;
3296                         }
3297                         res = ast_poll(pfds, max, kbrms);
3298                         if (!res) {
3299                                 rms -= kbrms;
3300                         }
3301                 } while (!res && (rms > 0));
3302         } else {
3303                 res = ast_poll(pfds, max, rms);
3304         }
3305         for (x = 0; x < n; x++) {
3306                 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3307         }
3308         if (res < 0) { /* Simulate a timeout if we were interrupted */
3309                 if (errno != EINTR) {
3310                         *ms = -1;
3311                 }
3312                 return NULL;
3313         }
3314         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
3315                 now = ast_tvnow();
3316                 for (x = 0; x < n; x++) {
3317                         if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3318                                 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3319                                 if (winner == NULL) {
3320                                         winner = c[x];
3321                                 }
3322                         }
3323                 }
3324         }
3325         if (res == 0) { /* no fd ready, reset timeout and done */
3326                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
3327                 return winner;
3328         }
3329         /*
3330          * Then check if any channel or fd has a pending event.
3331          * Remember to check channels first and fds last, as they
3332          * must have priority on setting 'winner'
3333          */
3334         for (x = 0; x < max; x++) {
3335                 res = pfds[x].revents;
3336                 if (res == 0) {
3337                         continue;
3338                 }
3339                 if (fdmap[x].chan >= 0) {       /* this is a channel */
3340                         winner = c[fdmap[x].chan];      /* override previous winners */
3341                         if (res & POLLPRI) {
3342                                 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3343                         } else {
3344                                 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3345                         }
3346                         ast_channel_fdno_set(winner, fdmap[x].fdno);
3347                 } else {                        /* this is an fd */
3348                         if (outfd) {
3349                                 *outfd = pfds[x].fd;
3350                         }
3351                         if (exception) {
3352                                 *exception = (res & POLLPRI) ? -1 : 0;
3353                         }
3354                         winner = NULL;
3355                 }
3356         }
3357         if (*ms > 0) {
3358                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);