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