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