b0622fa9c4c6d2ed427d606fe29c41a4186f8a2c
[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 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  *
815  * \note This function is not reentrant.
816  *
817  * \param state
818  */
819 const char *ast_state2str(enum ast_channel_state state)
820 {
821         char *buf;
822
823         switch (state) {
824         case AST_STATE_DOWN:
825                 return "Down";
826         case AST_STATE_RESERVED:
827                 return "Rsrvd";
828         case AST_STATE_OFFHOOK:
829                 return "OffHook";
830         case AST_STATE_DIALING:
831                 return "Dialing";
832         case AST_STATE_RING:
833                 return "Ring";
834         case AST_STATE_RINGING:
835                 return "Ringing";
836         case AST_STATE_UP:
837                 return "Up";
838         case AST_STATE_BUSY:
839                 return "Busy";
840         case AST_STATE_DIALING_OFFHOOK:
841                 return "Dialing Offhook";
842         case AST_STATE_PRERING:
843                 return "Pre-ring";
844         default:
845                 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
846                         return "Unknown";
847                 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
848                 return buf;
849         }
850 }
851
852 /*! \brief Gives the string form of a given transfer capability */
853 char *ast_transfercapability2str(int transfercapability)
854 {
855         switch (transfercapability) {
856         case AST_TRANS_CAP_SPEECH:
857                 return "SPEECH";
858         case AST_TRANS_CAP_DIGITAL:
859                 return "DIGITAL";
860         case AST_TRANS_CAP_RESTRICTED_DIGITAL:
861                 return "RESTRICTED_DIGITAL";
862         case AST_TRANS_CAP_3_1K_AUDIO:
863                 return "3K1AUDIO";
864         case AST_TRANS_CAP_DIGITAL_W_TONES:
865                 return "DIGITAL_W_TONES";
866         case AST_TRANS_CAP_VIDEO:
867                 return "VIDEO";
868         default:
869                 return "UNKNOWN";
870         }
871 }
872
873 /*! \brief Pick the best audio codec */
874 struct ast_format *ast_best_codec(struct ast_format_cap *cap, struct ast_format *result)
875 {
876         /* This just our opinion, expressed in code.  We are asked to choose
877            the best codec to use, given no information */
878         static const enum ast_format_id prefs[] =
879         {
880                 /*! Okay, ulaw is used by all telephony equipment, so start with it */
881                 AST_FORMAT_ULAW,
882                 /*! Unless of course, you're a silly European, so then prefer ALAW */
883                 AST_FORMAT_ALAW,
884                 AST_FORMAT_G719,
885                 AST_FORMAT_SIREN14,
886                 AST_FORMAT_SIREN7,
887                 AST_FORMAT_TESTLAW,
888                 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
889                 AST_FORMAT_G722,
890                 /*! Okay, well, signed linear is easy to translate into other stuff */
891                 AST_FORMAT_SLINEAR192,
892                 AST_FORMAT_SLINEAR96,
893                 AST_FORMAT_SLINEAR48,
894                 AST_FORMAT_SLINEAR44,
895                 AST_FORMAT_SLINEAR32,
896                 AST_FORMAT_SLINEAR24,
897                 AST_FORMAT_SLINEAR16,
898                 AST_FORMAT_SLINEAR12,
899                 AST_FORMAT_SLINEAR,
900                 /*! G.726 is standard ADPCM, in RFC3551 packing order */
901                 AST_FORMAT_G726,
902                 /*! G.726 is standard ADPCM, in AAL2 packing order */
903                 AST_FORMAT_G726_AAL2,
904                 /*! ADPCM has great sound quality and is still pretty easy to translate */
905                 AST_FORMAT_ADPCM,
906                 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
907                     translate and sounds pretty good */
908                 AST_FORMAT_GSM,
909                 /*! iLBC is not too bad */
910                 AST_FORMAT_ILBC,
911                 /*! Speex is free, but computationally more expensive than GSM */
912                 AST_FORMAT_SPEEX32,
913                 AST_FORMAT_SPEEX16,
914                 AST_FORMAT_SPEEX,
915                 /*! SILK is pretty awesome. */
916                 AST_FORMAT_SILK,
917                 /*! CELT supports crazy high sample rates */
918                 AST_FORMAT_CELT,
919                 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
920                     to use it */
921                 AST_FORMAT_LPC10,
922                 /*! G.729a is faster than 723 and slightly less expensive */
923                 AST_FORMAT_G729A,
924                 /*! Down to G.723.1 which is proprietary but at least designed for voice */
925                 AST_FORMAT_G723_1,
926         };
927         char buf[512];
928         int x;
929
930         /* Find the first preferred codec in the format given */
931         for (x = 0; x < ARRAY_LEN(prefs); x++) {
932                 if (ast_format_cap_best_byid(cap, prefs[x], result)) {
933                         return result;
934                 }
935         }
936
937         ast_format_clear(result);
938         ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
939
940         return NULL;
941 }
942
943 static const struct ast_channel_tech null_tech = {
944         .type = "NULL",
945         .description = "Null channel (should not see this)",
946 };
947
948 static void ast_channel_destructor(void *obj);
949 static void ast_dummy_channel_destructor(void *obj);
950
951 /*! \brief Create a new channel structure */
952 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
953 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
954                        const char *acctcode, const char *exten, const char *context,
955                        const char *linkedid, const int amaflag, const char *file, int line,
956                        const char *function, const char *name_fmt, va_list ap)
957 {
958         struct ast_channel *tmp;
959         struct varshead *headp;
960         char *tech = "", *tech2 = NULL;
961         struct ast_format_cap *nativeformats;
962         struct ast_sched_context *schedctx;
963         struct ast_timer *timer;
964         struct timeval now;
965
966         /* If shutting down, don't allocate any new channels */
967         if (ast_shutting_down()) {
968                 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
969                 return NULL;
970         }
971
972         if (!(tmp = ast_channel_internal_alloc(ast_channel_destructor))) {
973                 /* Channel structure allocation failure. */
974                 return NULL;
975         }
976         if (!(nativeformats = ast_format_cap_alloc())) {
977                 ao2_ref(tmp, -1);
978                 /* format capabilities structure allocation failure */
979                 return NULL;
980         }
981         ast_channel_nativeformats_set(tmp, nativeformats);
982
983         /*
984          * Init file descriptors to unopened state so
985          * the destructor can know not to close them.
986          */
987         ast_channel_timingfd_set(tmp, -1);
988         ast_channel_internal_alertpipe_clear(tmp);
989         ast_channel_internal_fd_clear_all(tmp);
990
991 #ifdef HAVE_EPOLL
992         ast_channel_epfd_set(tmp, epoll_create(25));
993 #endif
994
995         if (!(schedctx = ast_sched_context_create())) {
996                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
997                 return ast_channel_unref(tmp);
998         }
999         ast_channel_sched_set(tmp, schedctx);
1000
1001         ast_party_dialed_init(ast_channel_dialed(tmp));
1002         ast_party_caller_init(ast_channel_caller(tmp));
1003         ast_party_connected_line_init(ast_channel_connected(tmp));
1004         ast_party_redirecting_init(ast_channel_redirecting(tmp));
1005
1006         if (cid_name) {
1007                 ast_channel_caller(tmp)->id.name.valid = 1;
1008                 ast_channel_caller(tmp)->id.name.str = ast_strdup(cid_name);
1009                 if (!ast_channel_caller(tmp)->id.name.str) {
1010                         return ast_channel_unref(tmp);
1011                 }
1012         }
1013         if (cid_num) {
1014                 ast_channel_caller(tmp)->id.number.valid = 1;
1015                 ast_channel_caller(tmp)->id.number.str = ast_strdup(cid_num);
1016                 if (!ast_channel_caller(tmp)->id.number.str) {
1017                         return ast_channel_unref(tmp);
1018                 }
1019         }
1020
1021         if ((timer = ast_timer_open())) {
1022                 ast_channel_timer_set(tmp, timer);
1023                 if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
1024                         needqueue = 0;
1025                 }
1026                 ast_channel_timingfd_set(tmp, ast_timer_fd(ast_channel_timer(tmp)));
1027         }
1028
1029         /*
1030          * This is the last place the channel constructor can fail.
1031          *
1032          * The destructor takes advantage of this fact to ensure that the
1033          * AST_CEL_CHANNEL_END is not posted if we have not posted the
1034          * AST_CEL_CHANNEL_START yet.
1035          */
1036
1037         if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
1038                 return ast_channel_unref(tmp);
1039         }
1040
1041         /* Always watch the alertpipe */
1042         ast_channel_set_fd(tmp, AST_ALERT_FD, ast_channel_internal_alert_readfd(tmp));
1043         /* And timing pipe */
1044         ast_channel_set_fd(tmp, AST_TIMING_FD, ast_channel_timingfd(tmp));
1045
1046         /* Initial state */
1047         ast_channel_state_set(tmp, state);
1048
1049         ast_channel_streamid_set(tmp, -1);
1050
1051         ast_channel_fin_set(tmp, global_fin);
1052         ast_channel_fout_set(tmp, global_fout);
1053
1054         now = ast_tvnow();
1055         ast_channel_creationtime_set(tmp, &now);
1056
1057         if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1058                 ast_channel_uniqueid_build(tmp, "%li.%d", (long) time(NULL),
1059                         ast_atomic_fetchadd_int(&uniqueint, 1));
1060         } else {
1061                 ast_channel_uniqueid_build(tmp, "%s-%li.%d", ast_config_AST_SYSTEM_NAME,
1062                         (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1063         }
1064
1065         if (!ast_strlen_zero(linkedid)) {
1066                 ast_channel_linkedid_set(tmp, linkedid);
1067         } else {
1068                 ast_channel_linkedid_set(tmp, ast_channel_uniqueid(tmp));
1069         }
1070
1071         if (!ast_strlen_zero(name_fmt)) {
1072                 char *slash, *slash2;
1073                 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1074                  * And they all use slightly different formats for their name string.
1075                  * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1076                  * This means, that the stringfields must have a routine that takes the va_lists directly, and
1077                  * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1078                  * This new function was written so this can be accomplished.
1079                  */
1080                 ast_channel_name_build_va(tmp, name_fmt, ap);
1081                 tech = ast_strdupa(ast_channel_name(tmp));
1082                 if ((slash = strchr(tech, '/'))) {
1083                         if ((slash2 = strchr(slash + 1, '/'))) {
1084                                 tech2 = slash + 1;
1085                                 *slash2 = '\0';
1086                         }
1087                         *slash = '\0';
1088                 }
1089         } else {
1090                 /*
1091                  * Start the string with '-' so it becomes an empty string
1092                  * in the destructor.
1093                  */
1094                 ast_channel_name_set(tmp, "-**Unknown**");
1095         }
1096
1097         /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1098
1099         /* These 4 variables need to be set up for the cdr_init() to work right */
1100         if (amaflag) {
1101                 ast_channel_amaflags_set(tmp, amaflag);
1102         } else {
1103                 ast_channel_amaflags_set(tmp, ast_default_amaflags);
1104         }
1105
1106         if (!ast_strlen_zero(acctcode))
1107                 ast_channel_accountcode_set(tmp, acctcode);
1108         else
1109                 ast_channel_accountcode_set(tmp, ast_default_accountcode);
1110
1111         ast_channel_context_set(tmp, S_OR(context, "default"));
1112         ast_channel_exten_set(tmp, S_OR(exten, "s"));
1113         ast_channel_priority_set(tmp, 1);
1114
1115         ast_channel_cdr_set(tmp, ast_cdr_alloc());
1116         ast_cdr_init(ast_channel_cdr(tmp), tmp);
1117         ast_cdr_start(ast_channel_cdr(tmp));
1118
1119         ast_atomic_fetchadd_int(&chancount, +1);
1120         ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1121
1122         headp = ast_channel_varshead(tmp);
1123         AST_LIST_HEAD_INIT_NOLOCK(headp);
1124
1125         ast_pbx_hangup_handler_init(tmp);
1126         AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1127
1128         AST_LIST_HEAD_INIT_NOLOCK(ast_channel_autochans(tmp));
1129
1130         ast_channel_language_set(tmp, defaultlanguage);
1131
1132         ast_channel_tech_set(tmp, &null_tech);
1133
1134         ao2_link(channels, tmp);
1135
1136         /*
1137          * And now, since the channel structure is built, and has its name, let's
1138          * call the manager event generator with this Newchannel event. This is the
1139          * proper and correct place to make this call, but you sure do have to pass
1140          * a lot of data into this func to do it here!
1141          */
1142         if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1143                 /*** DOCUMENTATION
1144                         <managerEventInstance>
1145                                 <synopsis>Raised when a new channel is created.</synopsis>
1146                                 <syntax>
1147                                         <xi:include xpointer="xpointer(/docs/managerEvent[@name='Newstate']/managerEventInstance/syntax/parameter[@name='ChannelState'])" />
1148                                         <xi:include xpointer="xpointer(/docs/managerEvent[@name='Newstate']/managerEventInstance/syntax/parameter[@name='ChannelStateDesc'])" />
1149                                 </syntax>
1150                         </managerEventInstance>
1151                 ***/
1152                 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1153                         "Channel: %s\r\n"
1154                         "ChannelState: %d\r\n"
1155                         "ChannelStateDesc: %s\r\n"
1156                         "CallerIDNum: %s\r\n"
1157                         "CallerIDName: %s\r\n"
1158                         "AccountCode: %s\r\n"
1159                         "Exten: %s\r\n"
1160                         "Context: %s\r\n"
1161                         "Uniqueid: %s\r\n",
1162                         ast_channel_name(tmp),
1163                         state,
1164                         ast_state2str(state),
1165                         S_OR(cid_num, ""),
1166                         S_OR(cid_name, ""),
1167                         ast_channel_accountcode(tmp),
1168                         S_OR(exten, ""),
1169                         S_OR(context, ""),
1170                         ast_channel_uniqueid(tmp));
1171         }
1172
1173         ast_channel_internal_finalize(tmp);
1174         return tmp;
1175 }
1176
1177 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1178                                         const char *cid_name, const char *acctcode,
1179                                         const char *exten, const char *context,
1180                                         const char *linkedid, const int amaflag,
1181                                         const char *file, int line, const char *function,
1182                                         const char *name_fmt, ...)
1183 {
1184         va_list ap;
1185         struct ast_channel *result;
1186
1187         va_start(ap, name_fmt);
1188         result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1189                                         linkedid, amaflag, file, line, function, name_fmt, ap);
1190         va_end(ap);
1191
1192         return result;
1193 }
1194
1195 /* only do the minimum amount of work needed here to make a channel
1196  * structure that can be used to expand channel vars */
1197 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1198 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1199 #else
1200 struct ast_channel *ast_dummy_channel_alloc(void)
1201 #endif
1202 {
1203         struct ast_channel *tmp;
1204         struct varshead *headp;
1205
1206         if (!(tmp = ast_channel_internal_alloc(ast_dummy_channel_destructor))) {
1207                 /* Dummy channel structure allocation failure. */
1208                 return NULL;
1209         }
1210
1211         ast_pbx_hangup_handler_init(tmp);
1212         AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1213
1214         /*
1215          * Init file descriptors to unopened state just in case
1216          * autoservice is called on the channel or something tries to
1217          * read a frame from it.
1218          */
1219         ast_channel_timingfd_set(tmp, -1);
1220         ast_channel_internal_alertpipe_clear(tmp);
1221         ast_channel_internal_fd_clear_all(tmp);
1222 #ifdef HAVE_EPOLL
1223         ast_channel_epfd_set(tmp, -1);
1224 #endif
1225
1226         headp = ast_channel_varshead(tmp);
1227         AST_LIST_HEAD_INIT_NOLOCK(headp);
1228
1229         return tmp;
1230 }
1231
1232 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1233 {
1234         struct ast_frame *f;
1235         struct ast_frame *cur;
1236         unsigned int new_frames = 0;
1237         unsigned int new_voice_frames = 0;
1238         unsigned int queued_frames = 0;
1239         unsigned int queued_voice_frames = 0;
1240         AST_LIST_HEAD_NOLOCK(,ast_frame) frames;
1241
1242         ast_channel_lock(chan);
1243
1244         /*
1245          * Check the last frame on the queue if we are queuing the new
1246          * frames after it.
1247          */
1248         cur = AST_LIST_LAST(ast_channel_readq(chan));
1249         if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1250                 switch (cur->subclass.integer) {
1251                 case AST_CONTROL_END_OF_Q:
1252                         if (fin->frametype == AST_FRAME_CONTROL
1253                                 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1254                                 /*
1255                                  * Destroy the end-of-Q marker frame so we can queue the hangup
1256                                  * frame in its place.
1257                                  */
1258                                 AST_LIST_REMOVE(ast_channel_readq(chan), cur, frame_list);
1259                                 ast_frfree(cur);
1260
1261                                 /*
1262                                  * This has degenerated to a normal queue append anyway.  Since
1263                                  * we just destroyed the last frame in the queue we must make
1264                                  * sure that "after" is NULL or bad things will happen.
1265                                  */
1266                                 after = NULL;
1267                                 break;
1268                         }
1269                         /* Fall through */
1270                 case AST_CONTROL_HANGUP:
1271                         /* Don't queue anything. */
1272                         ast_channel_unlock(chan);
1273                         return 0;
1274                 default:
1275                         break;
1276                 }
1277         }
1278
1279         /* Build copies of all the new frames and count them */
1280         AST_LIST_HEAD_INIT_NOLOCK(&frames);
1281         for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1282                 if (!(f = ast_frdup(cur))) {
1283                         if (AST_LIST_FIRST(&frames)) {
1284                                 ast_frfree(AST_LIST_FIRST(&frames));
1285                         }
1286                         ast_channel_unlock(chan);
1287                         return -1;
1288                 }
1289
1290                 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1291                 new_frames++;
1292                 if (f->frametype == AST_FRAME_VOICE) {
1293                         new_voice_frames++;
1294                 }
1295         }
1296
1297         /* Count how many frames exist on the queue */
1298         AST_LIST_TRAVERSE(ast_channel_readq(chan), cur, frame_list) {
1299                 queued_frames++;
1300                 if (cur->frametype == AST_FRAME_VOICE) {
1301                         queued_voice_frames++;
1302                 }
1303         }
1304
1305         if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1306                 int count = 0;
1307                 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1308                 AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), cur, frame_list) {
1309                         /* Save the most recent frame */
1310                         if (!AST_LIST_NEXT(cur, frame_list)) {
1311                                 break;
1312                         } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1313                                 if (++count > 64) {
1314                                         break;
1315                                 }
1316                                 AST_LIST_REMOVE_CURRENT(frame_list);
1317                                 ast_frfree(cur);
1318                         }
1319                 }
1320                 AST_LIST_TRAVERSE_SAFE_END;
1321         }
1322
1323         if (after) {
1324                 AST_LIST_INSERT_LIST_AFTER(ast_channel_readq(chan), &frames, after, frame_list);
1325         } else {
1326                 if (head) {
1327                         AST_LIST_APPEND_LIST(&frames, ast_channel_readq(chan), frame_list);
1328                         AST_LIST_HEAD_INIT_NOLOCK(ast_channel_readq(chan));
1329                 }
1330                 AST_LIST_APPEND_LIST(ast_channel_readq(chan), &frames, frame_list);
1331         }
1332
1333         if (ast_channel_alert_writable(chan)) {
1334                 if (ast_channel_alert_write(chan)) {
1335                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1336                                 ast_channel_name(chan), queued_frames, strerror(errno));
1337                 }
1338         } else if (ast_channel_timingfd(chan) > -1) {
1339                 ast_timer_enable_continuous(ast_channel_timer(chan));
1340         } else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
1341                 pthread_kill(ast_channel_blocker(chan), SIGURG);
1342         }
1343
1344         ast_channel_unlock(chan);
1345
1346         return 0;
1347 }
1348
1349 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1350 {
1351         return __ast_queue_frame(chan, fin, 0, NULL);
1352 }
1353
1354 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1355 {
1356         return __ast_queue_frame(chan, fin, 1, NULL);
1357 }
1358
1359 /*! \brief Queue a hangup frame for channel */
1360 int ast_queue_hangup(struct ast_channel *chan)
1361 {
1362         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1363         int res;
1364
1365         /* Yeah, let's not change a lock-critical value without locking */
1366         ast_channel_lock(chan);
1367         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1368         /*** DOCUMENTATION
1369                 <managerEventInstance>
1370                         <synopsis>Raised when a hangup is requested with no set cause.</synopsis>
1371                 </managerEventInstance>
1372         ***/
1373         manager_event(EVENT_FLAG_CALL, "HangupRequest",
1374                 "Channel: %s\r\n"
1375                 "Uniqueid: %s\r\n",
1376                 ast_channel_name(chan),
1377                 ast_channel_uniqueid(chan));
1378
1379         res = ast_queue_frame(chan, &f);
1380         ast_channel_unlock(chan);
1381         return res;
1382 }
1383
1384 /*! \brief Queue a hangup frame for channel */
1385 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1386 {
1387         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1388         int res;
1389
1390         if (cause >= 0) {
1391                 f.data.uint32 = cause;
1392         }
1393
1394         /* Yeah, let's not change a lock-critical value without locking */
1395         ast_channel_lock(chan);
1396         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1397         if (cause < 0) {
1398                 f.data.uint32 = ast_channel_hangupcause(chan);
1399         }
1400         /*** DOCUMENTATION
1401                 <managerEventInstance>
1402                         <synopsis>Raised when a hangup is requested with a specific cause code.</synopsis>
1403                                 <syntax>
1404                                         <xi:include xpointer="xpointer(/docs/managerEvent[@name='Hangup']/managerEventInstance/syntax/parameter[@name='Cause'])" />
1405                                 </syntax>
1406                 </managerEventInstance>
1407         ***/
1408         manager_event(EVENT_FLAG_CALL, "HangupRequest",
1409                 "Channel: %s\r\n"
1410                 "Uniqueid: %s\r\n"
1411                 "Cause: %d\r\n",
1412                 ast_channel_name(chan),
1413                 ast_channel_uniqueid(chan),
1414                 cause);
1415
1416         res = ast_queue_frame(chan, &f);
1417         ast_channel_unlock(chan);
1418         return res;
1419 }
1420
1421 /*! \brief Queue a control frame */
1422 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1423 {
1424         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1425         return ast_queue_frame(chan, &f);
1426 }
1427
1428 /*! \brief Queue a control frame with payload */
1429 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1430                            const void *data, size_t datalen)
1431 {
1432         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1433         return ast_queue_frame(chan, &f);
1434 }
1435
1436 /*! \brief Set defer DTMF flag on channel */
1437 int ast_channel_defer_dtmf(struct ast_channel *chan)
1438 {
1439         int pre = 0;
1440
1441         if (chan) {
1442                 pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1443                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1444         }
1445         return pre;
1446 }
1447
1448 /*! \brief Unset defer DTMF flag on channel */
1449 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1450 {
1451         if (chan)
1452                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1453 }
1454
1455 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1456                 void *data, int ao2_flags)
1457 {
1458         return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1459 }
1460
1461 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1462 {
1463         struct ast_channel *chan = obj;
1464         const char *name = arg;
1465         size_t name_len = *(size_t *) data;
1466         int ret = CMP_MATCH;
1467
1468         if (ast_strlen_zero(name)) {
1469                 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1470                 return CMP_STOP;
1471         }
1472
1473         ast_channel_lock(chan);
1474         if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1475                 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1476                 ret = 0; /* name match failed, keep looking */
1477         }
1478         ast_channel_unlock(chan);
1479
1480         return ret;
1481 }
1482
1483 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1484 {
1485         struct ast_channel *chan = obj;
1486         char *context = arg;
1487         char *exten = data;
1488         int ret = CMP_MATCH;
1489
1490         if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1491                 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1492                 return CMP_STOP;
1493         }
1494
1495         ast_channel_lock(chan);
1496         if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1497                 ret = 0; /* Context match failed, continue */
1498         } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1499                 ret = 0; /* Extension match failed, continue */
1500         }
1501         ast_channel_unlock(chan);
1502
1503         return ret;
1504 }
1505
1506 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1507 {
1508         struct ast_channel *chan = obj;
1509         char *uniqueid = arg;
1510         size_t id_len = *(size_t *) data;
1511         int ret = CMP_MATCH;
1512
1513         if (ast_strlen_zero(uniqueid)) {
1514                 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1515                 return CMP_STOP;
1516         }
1517
1518         ast_channel_lock(chan);
1519         if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1520                 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1521                 ret = 0; /* uniqueid match failed, keep looking */
1522         }
1523         ast_channel_unlock(chan);
1524
1525         return ret;
1526 }
1527
1528 struct ast_channel_iterator {
1529         /* storage for non-dynamically allocated iterator */
1530         struct ao2_iterator simple_iterator;
1531         /* pointer to the actual iterator (simple_iterator or a dynamically
1532          * allocated iterator)
1533          */
1534         struct ao2_iterator *active_iterator;
1535 };
1536
1537 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1538 {
1539         ao2_iterator_destroy(i->active_iterator);
1540         ast_free(i);
1541
1542         return NULL;
1543 }
1544
1545 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1546 {
1547         struct ast_channel_iterator *i;
1548         char *l_exten = (char *) exten;
1549         char *l_context = (char *) context;
1550
1551         if (!(i = ast_calloc(1, sizeof(*i)))) {
1552                 return NULL;
1553         }
1554
1555         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1556                 l_context, l_exten, OBJ_MULTIPLE);
1557         if (!i->active_iterator) {
1558                 ast_free(i);
1559                 return NULL;
1560         }
1561
1562         return i;
1563 }
1564
1565 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1566 {
1567         struct ast_channel_iterator *i;
1568         char *l_name = (char *) name;
1569
1570         if (!(i = ast_calloc(1, sizeof(*i)))) {
1571                 return NULL;
1572         }
1573
1574         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1575                 l_name, &name_len,
1576                 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1577         if (!i->active_iterator) {
1578                 ast_free(i);
1579                 return NULL;
1580         }
1581
1582         return i;
1583 }
1584
1585 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1586 {
1587         struct ast_channel_iterator *i;
1588
1589         if (!(i = ast_calloc(1, sizeof(*i)))) {
1590                 return NULL;
1591         }
1592
1593         i->simple_iterator = ao2_iterator_init(channels, 0);
1594         i->active_iterator = &i->simple_iterator;
1595
1596         return i;
1597 }
1598
1599 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1600 {
1601         return ao2_iterator_next(i->active_iterator);
1602 }
1603
1604 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1605 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1606 {
1607         ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1608         return CMP_STOP;
1609 }
1610
1611 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1612 {
1613         struct ast_channel *chan;
1614         char *l_name = (char *) name;
1615
1616         chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1617                 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1618         if (chan) {
1619                 return chan;
1620         }
1621
1622         if (ast_strlen_zero(l_name)) {
1623                 /* We didn't have a name to search for so quit. */
1624                 return NULL;
1625         }
1626
1627         /* Now try a search for uniqueid. */
1628         return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1629 }
1630
1631 struct ast_channel *ast_channel_get_by_name(const char *name)
1632 {
1633         return ast_channel_get_by_name_prefix(name, 0);
1634 }
1635
1636 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1637 {
1638         char *l_exten = (char *) exten;
1639         char *l_context = (char *) context;
1640
1641         return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1642 }
1643
1644 int ast_is_deferrable_frame(const struct ast_frame *frame)
1645 {
1646         /* Do not add a default entry in this switch statement.  Each new
1647          * frame type should be addressed directly as to whether it should
1648          * be queued up or not.
1649          */
1650         switch (frame->frametype) {
1651         case AST_FRAME_CONTROL:
1652         case AST_FRAME_TEXT:
1653         case AST_FRAME_IMAGE:
1654         case AST_FRAME_HTML:
1655                 return 1;
1656
1657         case AST_FRAME_DTMF_END:
1658         case AST_FRAME_DTMF_BEGIN:
1659         case AST_FRAME_VOICE:
1660         case AST_FRAME_VIDEO:
1661         case AST_FRAME_NULL:
1662         case AST_FRAME_IAX:
1663         case AST_FRAME_CNG:
1664         case AST_FRAME_MODEM:
1665                 return 0;
1666         }
1667         return 0;
1668 }
1669
1670 /*! \brief Wait, look for hangups and condition arg */
1671 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1672 {
1673         struct ast_frame *f;
1674         struct ast_silence_generator *silgen = NULL;
1675         int res = 0;
1676         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1677
1678         AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1679
1680         /* If no other generator is present, start silencegen while waiting */
1681         if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1682                 silgen = ast_channel_start_silence_generator(chan);
1683         }
1684
1685         while (ms > 0) {
1686                 struct ast_frame *dup_f = NULL;
1687                 if (cond && ((*cond)(data) == 0)) {
1688                         break;
1689                 }
1690                 ms = ast_waitfor(chan, ms);
1691                 if (ms < 0) {
1692                         res = -1;
1693                         break;
1694                 }
1695                 if (ms > 0) {
1696                         f = ast_read(chan);
1697                         if (!f) {
1698                                 res = -1;
1699                                 break;
1700                         }
1701
1702                         if (!ast_is_deferrable_frame(f)) {
1703                                 ast_frfree(f);
1704                                 continue;
1705                         }
1706
1707                         if ((dup_f = ast_frisolate(f))) {
1708                                 if (dup_f != f) {
1709                                         ast_frfree(f);
1710                                 }
1711                                 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1712                         }
1713                 }
1714         }
1715
1716         /* stop silgen if present */
1717         if (silgen) {
1718                 ast_channel_stop_silence_generator(chan, silgen);
1719         }
1720
1721         /* We need to free all the deferred frames, but we only need to
1722          * queue the deferred frames if there was no error and no
1723          * hangup was received
1724          */
1725         ast_channel_lock(chan);
1726         while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1727                 if (!res) {
1728                         ast_queue_frame_head(chan, f);
1729                 }
1730                 ast_frfree(f);
1731         }
1732         ast_channel_unlock(chan);
1733
1734         return res;
1735 }
1736
1737 /*! \brief Wait, look for hangups */
1738 int ast_safe_sleep(struct ast_channel *chan, int ms)
1739 {
1740         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1741 }
1742
1743 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1744 {
1745         /* Safe, even if already unlinked. */
1746         ao2_unlink(channels, chan);
1747         return ast_channel_unref(chan);
1748 }
1749
1750 void ast_party_name_init(struct ast_party_name *init)
1751 {
1752         init->str = NULL;
1753         init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1754         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1755         init->valid = 0;
1756 }
1757
1758 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1759 {
1760         if (dest == src) {
1761                 /* Don't copy to self */
1762                 return;
1763         }
1764
1765         ast_free(dest->str);
1766         dest->str = ast_strdup(src->str);
1767         dest->char_set = src->char_set;
1768         dest->presentation = src->presentation;
1769         dest->valid = src->valid;
1770 }
1771
1772 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1773 {
1774         init->str = NULL;
1775         init->char_set = guide->char_set;
1776         init->presentation = guide->presentation;
1777         init->valid = guide->valid;
1778 }
1779
1780 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1781 {
1782         if (dest == src) {
1783                 /* Don't set to self */
1784                 return;
1785         }
1786
1787         if (src->str && src->str != dest->str) {
1788                 ast_free(dest->str);
1789                 dest->str = ast_strdup(src->str);
1790         }
1791
1792         dest->char_set = src->char_set;
1793         dest->presentation = src->presentation;
1794         dest->valid = src->valid;
1795 }
1796
1797 void ast_party_name_free(struct ast_party_name *doomed)
1798 {
1799         ast_free(doomed->str);
1800         doomed->str = NULL;
1801 }
1802
1803 void ast_party_number_init(struct ast_party_number *init)
1804 {
1805         init->str = NULL;
1806         init->plan = 0;/* Unknown */
1807         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1808         init->valid = 0;
1809 }
1810
1811 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1812 {
1813         if (dest == src) {
1814                 /* Don't copy to self */
1815                 return;
1816         }
1817
1818         ast_free(dest->str);
1819         dest->str = ast_strdup(src->str);
1820         dest->plan = src->plan;
1821         dest->presentation = src->presentation;
1822         dest->valid = src->valid;
1823 }
1824
1825 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1826 {
1827         init->str = NULL;
1828         init->plan = guide->plan;
1829         init->presentation = guide->presentation;
1830         init->valid = guide->valid;
1831 }
1832
1833 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1834 {
1835         if (dest == src) {
1836                 /* Don't set to self */
1837                 return;
1838         }
1839
1840         if (src->str && src->str != dest->str) {
1841                 ast_free(dest->str);
1842                 dest->str = ast_strdup(src->str);
1843         }
1844
1845         dest->plan = src->plan;
1846         dest->presentation = src->presentation;
1847         dest->valid = src->valid;
1848 }
1849
1850 void ast_party_number_free(struct ast_party_number *doomed)
1851 {
1852         ast_free(doomed->str);
1853         doomed->str = NULL;
1854 }
1855
1856 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1857 {
1858         init->str = NULL;
1859         init->type = 0;
1860         init->odd_even_indicator = 0;
1861         init->valid = 0;
1862 }
1863
1864 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1865 {
1866         if (dest == src) {
1867                 /* Don't copy to self */
1868                 return;
1869         }
1870
1871         ast_free(dest->str);
1872         dest->str = ast_strdup(src->str);
1873         dest->type = src->type;
1874         dest->odd_even_indicator = src->odd_even_indicator;
1875         dest->valid = src->valid;
1876 }
1877
1878 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1879 {
1880         init->str = NULL;
1881         init->type = guide->type;
1882         init->odd_even_indicator = guide->odd_even_indicator;
1883         init->valid = guide->valid;
1884 }
1885
1886 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1887 {
1888         if (dest == src) {
1889                 /* Don't set to self */
1890                 return;
1891         }
1892
1893         if (src->str && src->str != dest->str) {
1894                 ast_free(dest->str);
1895                 dest->str = ast_strdup(src->str);
1896         }
1897
1898         dest->type = src->type;
1899         dest->odd_even_indicator = src->odd_even_indicator;
1900         dest->valid = src->valid;
1901 }
1902
1903 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1904 {
1905         ast_free(doomed->str);
1906         doomed->str = NULL;
1907 }
1908
1909 void ast_set_party_id_all(struct ast_set_party_id *update_id)
1910 {
1911         update_id->name = 1;
1912         update_id->number = 1;
1913         update_id->subaddress = 1;
1914 }
1915
1916 void ast_party_id_init(struct ast_party_id *init)
1917 {
1918         ast_party_name_init(&init->name);
1919         ast_party_number_init(&init->number);
1920         ast_party_subaddress_init(&init->subaddress);
1921         init->tag = NULL;
1922 }
1923
1924 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1925 {
1926         if (dest == src) {
1927                 /* Don't copy to self */
1928                 return;
1929         }
1930
1931         ast_party_name_copy(&dest->name, &src->name);
1932         ast_party_number_copy(&dest->number, &src->number);
1933         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1934
1935         ast_free(dest->tag);
1936         dest->tag = ast_strdup(src->tag);
1937 }
1938
1939 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1940 {
1941         ast_party_name_set_init(&init->name, &guide->name);
1942         ast_party_number_set_init(&init->number, &guide->number);
1943         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1944         init->tag = NULL;
1945 }
1946
1947 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1948 {
1949         if (dest == src) {
1950                 /* Don't set to self */
1951                 return;
1952         }
1953
1954         if (!update || update->name) {
1955                 ast_party_name_set(&dest->name, &src->name);
1956         }
1957         if (!update || update->number) {
1958                 ast_party_number_set(&dest->number, &src->number);
1959         }
1960         if (!update || update->subaddress) {
1961                 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1962         }
1963
1964         if (src->tag && src->tag != dest->tag) {
1965                 ast_free(dest->tag);
1966                 dest->tag = ast_strdup(src->tag);
1967         }
1968 }
1969
1970 void ast_party_id_free(struct ast_party_id *doomed)
1971 {
1972         ast_party_name_free(&doomed->name);
1973         ast_party_number_free(&doomed->number);
1974         ast_party_subaddress_free(&doomed->subaddress);
1975
1976         ast_free(doomed->tag);
1977         doomed->tag = NULL;
1978 }
1979
1980 int ast_party_id_presentation(const struct ast_party_id *id)
1981 {
1982         int number_priority;
1983         int number_value;
1984         int number_screening;
1985         int name_priority;
1986         int name_value;
1987
1988         /* Determine name presentation priority. */
1989         if (!id->name.valid) {
1990                 name_value = AST_PRES_UNAVAILABLE;
1991                 name_priority = 3;
1992         } else {
1993                 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1994                 switch (name_value) {
1995                 case AST_PRES_RESTRICTED:
1996                         name_priority = 0;
1997                         break;
1998                 case AST_PRES_ALLOWED:
1999                         name_priority = 1;
2000                         break;
2001                 case AST_PRES_UNAVAILABLE:
2002                         name_priority = 2;
2003                         break;
2004                 default:
2005                         name_value = AST_PRES_UNAVAILABLE;
2006                         name_priority = 3;
2007                         break;
2008                 }
2009         }
2010
2011         /* Determine number presentation priority. */
2012         if (!id->number.valid) {
2013                 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2014                 number_value = AST_PRES_UNAVAILABLE;
2015                 number_priority = 3;
2016         } else {
2017                 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
2018                 number_value = id->number.presentation & AST_PRES_RESTRICTION;
2019                 switch (number_value) {
2020                 case AST_PRES_RESTRICTED:
2021                         number_priority = 0;
2022                         break;
2023                 case AST_PRES_ALLOWED:
2024                         number_priority = 1;
2025                         break;
2026                 case AST_PRES_UNAVAILABLE:
2027                         number_priority = 2;
2028                         break;
2029                 default:
2030                         number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2031                         number_value = AST_PRES_UNAVAILABLE;
2032                         number_priority = 3;
2033                         break;
2034                 }
2035         }
2036
2037         /* Select the wining presentation value. */
2038         if (name_priority < number_priority) {
2039                 number_value = name_value;
2040         }
2041         if (number_value == AST_PRES_UNAVAILABLE) {
2042                 return AST_PRES_NUMBER_NOT_AVAILABLE;
2043         }
2044
2045         return number_value | number_screening;
2046 }
2047
2048 void ast_party_id_invalidate(struct ast_party_id *id)
2049 {
2050         id->name.valid = 0;
2051         id->number.valid = 0;
2052         id->subaddress.valid = 0;
2053 }
2054
2055 void ast_party_id_reset(struct ast_party_id *id)
2056 {
2057         ast_party_id_free(id);
2058         ast_party_id_init(id);
2059 }
2060
2061 struct ast_party_id ast_party_id_merge(struct ast_party_id *base, struct ast_party_id *overlay)
2062 {
2063         struct ast_party_id merged;
2064
2065         merged = *base;
2066         if (overlay->name.valid) {
2067                 merged.name = overlay->name;
2068         }
2069         if (overlay->number.valid) {
2070                 merged.number = overlay->number;
2071         }
2072         if (overlay->subaddress.valid) {
2073                 merged.subaddress = overlay->subaddress;
2074         }
2075         /* Note the actual structure is returned and not a pointer to it! */
2076         return merged;
2077 }
2078
2079 void ast_party_id_merge_copy(struct ast_party_id *dest, struct ast_party_id *base, struct ast_party_id *overlay)
2080 {
2081         struct ast_party_id merged;
2082
2083         merged = ast_party_id_merge(base, overlay);
2084         ast_party_id_copy(dest, &merged);
2085 }
2086
2087 void ast_party_dialed_init(struct ast_party_dialed *init)
2088 {
2089         init->number.str = NULL;
2090         init->number.plan = 0;/* Unknown */
2091         ast_party_subaddress_init(&init->subaddress);
2092         init->transit_network_select = 0;
2093 }
2094
2095 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2096 {
2097         if (dest == src) {
2098                 /* Don't copy to self */
2099                 return;
2100         }
2101
2102         ast_free(dest->number.str);
2103         dest->number.str = ast_strdup(src->number.str);
2104         dest->number.plan = src->number.plan;
2105         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2106         dest->transit_network_select = src->transit_network_select;
2107 }
2108
2109 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2110 {
2111         init->number.str = NULL;
2112         init->number.plan = guide->number.plan;
2113         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2114         init->transit_network_select = guide->transit_network_select;
2115 }
2116
2117 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2118 {
2119         if (src->number.str && src->number.str != dest->number.str) {
2120                 ast_free(dest->number.str);
2121                 dest->number.str = ast_strdup(src->number.str);
2122         }
2123         dest->number.plan = src->number.plan;
2124
2125         ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2126
2127         dest->transit_network_select = src->transit_network_select;
2128 }
2129
2130 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2131 {
2132         ast_free(doomed->number.str);
2133         doomed->number.str = NULL;
2134         ast_party_subaddress_free(&doomed->subaddress);
2135 }
2136
2137 void ast_party_caller_init(struct ast_party_caller *init)
2138 {
2139         ast_party_id_init(&init->id);
2140         ast_party_id_init(&init->ani);
2141         ast_party_id_init(&init->priv);
2142         init->ani2 = 0;
2143 }
2144
2145 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2146 {
2147         if (dest == src) {
2148                 /* Don't copy to self */
2149                 return;
2150         }
2151
2152         ast_party_id_copy(&dest->id, &src->id);
2153         ast_party_id_copy(&dest->ani, &src->ani);
2154         ast_party_id_copy(&dest->priv, &src->priv);
2155         dest->ani2 = src->ani2;
2156 }
2157
2158 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2159 {
2160         ast_party_id_set_init(&init->id, &guide->id);
2161         ast_party_id_set_init(&init->ani, &guide->ani);
2162         ast_party_id_set_init(&init->priv, &guide->priv);
2163         init->ani2 = guide->ani2;
2164 }
2165
2166 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2167 {
2168         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2169         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2170         ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2171         dest->ani2 = src->ani2;
2172 }
2173
2174 void ast_party_caller_free(struct ast_party_caller *doomed)
2175 {
2176         ast_party_id_free(&doomed->id);
2177         ast_party_id_free(&doomed->ani);
2178         ast_party_id_free(&doomed->priv);
2179 }
2180
2181 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2182 {
2183         ast_party_id_init(&init->id);
2184         ast_party_id_init(&init->ani);
2185         ast_party_id_init(&init->priv);
2186         init->ani2 = 0;
2187         init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2188 }
2189
2190 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2191 {
2192         if (dest == src) {
2193                 /* Don't copy to self */
2194                 return;
2195         }
2196
2197         ast_party_id_copy(&dest->id, &src->id);
2198         ast_party_id_copy(&dest->ani, &src->ani);
2199         ast_party_id_copy(&dest->priv, &src->priv);
2200         dest->ani2 = src->ani2;
2201         dest->source = src->source;
2202 }
2203
2204 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2205 {
2206         ast_party_id_set_init(&init->id, &guide->id);
2207         ast_party_id_set_init(&init->ani, &guide->ani);
2208         ast_party_id_set_init(&init->priv, &guide->priv);
2209         init->ani2 = guide->ani2;
2210         init->source = guide->source;
2211 }
2212
2213 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)
2214 {
2215         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2216         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2217         ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2218         dest->ani2 = src->ani2;
2219         dest->source = src->source;
2220 }
2221
2222 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2223 {
2224         connected->id = caller->id;
2225         connected->ani = caller->ani;
2226         connected->priv = caller->priv;
2227         connected->ani2 = caller->ani2;
2228         connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2229 }
2230
2231 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2232 {
2233         ast_party_id_free(&doomed->id);
2234         ast_party_id_free(&doomed->ani);
2235         ast_party_id_free(&doomed->priv);
2236 }
2237
2238 void ast_party_redirecting_reason_init(struct ast_party_redirecting_reason *init)
2239 {
2240         init->str = NULL;
2241         init->code = AST_REDIRECTING_REASON_UNKNOWN;
2242 }
2243
2244 void ast_party_redirecting_reason_copy(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2245 {
2246         if (dest == src) {
2247                 return;
2248         }
2249
2250         ast_free(dest->str);
2251         dest->str = ast_strdup(src->str);
2252         dest->code = src->code;
2253 }
2254
2255 void ast_party_redirecting_reason_set_init(struct ast_party_redirecting_reason *init, const struct ast_party_redirecting_reason *guide)
2256 {
2257         init->str = NULL;
2258         init->code = guide->code;
2259 }
2260
2261 void ast_party_redirecting_reason_set(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2262 {
2263         if (dest == src) {
2264                 return;
2265         }
2266
2267         if (src->str && src->str != dest->str) {
2268                 ast_free(dest->str);
2269                 dest->str = ast_strdup(src->str);
2270         }
2271
2272         dest->code = src->code;
2273 }
2274
2275 void ast_party_redirecting_reason_free(struct ast_party_redirecting_reason *doomed)
2276 {
2277         ast_free(doomed->str);
2278 }
2279
2280
2281 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2282 {
2283         ast_party_id_init(&init->orig);
2284         ast_party_id_init(&init->from);
2285         ast_party_id_init(&init->to);
2286         ast_party_id_init(&init->priv_orig);
2287         ast_party_id_init(&init->priv_from);
2288         ast_party_id_init(&init->priv_to);
2289         ast_party_redirecting_reason_init(&init->reason);
2290         ast_party_redirecting_reason_init(&init->orig_reason);
2291         init->count = 0;
2292 }
2293
2294 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2295 {
2296         if (dest == src) {
2297                 /* Don't copy to self */
2298                 return;
2299         }
2300
2301         ast_party_id_copy(&dest->orig, &src->orig);
2302         ast_party_id_copy(&dest->from, &src->from);
2303         ast_party_id_copy(&dest->to, &src->to);
2304         ast_party_id_copy(&dest->priv_orig, &src->priv_orig);
2305         ast_party_id_copy(&dest->priv_from, &src->priv_from);
2306         ast_party_id_copy(&dest->priv_to, &src->priv_to);
2307         ast_party_redirecting_reason_copy(&dest->reason, &src->reason);
2308         ast_party_redirecting_reason_copy(&dest->orig_reason, &src->orig_reason);
2309         dest->count = src->count;
2310 }
2311
2312 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2313 {
2314         ast_party_id_set_init(&init->orig, &guide->orig);
2315         ast_party_id_set_init(&init->from, &guide->from);
2316         ast_party_id_set_init(&init->to, &guide->to);
2317         ast_party_id_set_init(&init->priv_orig, &guide->priv_orig);
2318         ast_party_id_set_init(&init->priv_from, &guide->priv_from);
2319         ast_party_id_set_init(&init->priv_to, &guide->priv_to);
2320         ast_party_redirecting_reason_set_init(&init->reason, &guide->reason);
2321         ast_party_redirecting_reason_set_init(&init->orig_reason, &guide->orig_reason);
2322         init->count = guide->count;
2323 }
2324
2325 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2326 {
2327         ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2328         ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2329         ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2330         ast_party_id_set(&dest->priv_orig, &src->priv_orig, update ? &update->priv_orig : NULL);
2331         ast_party_id_set(&dest->priv_from, &src->priv_from, update ? &update->priv_from : NULL);
2332         ast_party_id_set(&dest->priv_to, &src->priv_to, update ? &update->priv_to : NULL);
2333         ast_party_redirecting_reason_set(&dest->reason, &src->reason);
2334         ast_party_redirecting_reason_set(&dest->orig_reason, &src->orig_reason);
2335         dest->count = src->count;
2336 }
2337
2338 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2339 {
2340         ast_party_id_free(&doomed->orig);
2341         ast_party_id_free(&doomed->from);
2342         ast_party_id_free(&doomed->to);
2343         ast_party_id_free(&doomed->priv_orig);
2344         ast_party_id_free(&doomed->priv_from);
2345         ast_party_id_free(&doomed->priv_to);
2346         ast_party_redirecting_reason_free(&doomed->reason);
2347         ast_party_redirecting_reason_free(&doomed->orig_reason);
2348 }
2349
2350 /*! \brief Free a channel structure */
2351 static void ast_channel_destructor(void *obj)
2352 {
2353         struct ast_channel *chan = obj;
2354 #ifdef HAVE_EPOLL
2355         int i;
2356 #endif
2357         struct ast_var_t *vardata;
2358         struct ast_frame *f;
2359         struct varshead *headp;
2360         struct ast_datastore *datastore;
2361         char device_name[AST_CHANNEL_NAME];
2362         struct ast_callid *callid;
2363
2364         if (ast_channel_internal_is_finalized(chan)) {
2365                 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2366                 ast_cel_check_retire_linkedid(chan);
2367         }
2368
2369         ast_pbx_hangup_handler_destroy(chan);
2370
2371         ast_channel_lock(chan);
2372
2373         /* Get rid of each of the data stores on the channel */
2374         while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2375                 /* Free the data store */
2376                 ast_datastore_free(datastore);
2377
2378         /* While the channel is locked, take the reference to its callid while we tear down the call. */
2379         callid = ast_channel_callid(chan);
2380         ast_channel_callid_cleanup(chan);
2381
2382         ast_channel_unlock(chan);
2383
2384         /* Lock and unlock the channel just to be sure nobody has it locked still
2385            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2386         ast_channel_lock(chan);
2387         ast_channel_unlock(chan);
2388
2389         if (ast_channel_tech_pvt(chan)) {
2390                 ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2391                 ast_free(ast_channel_tech_pvt(chan));
2392         }
2393
2394         if (ast_channel_sched(chan)) {
2395                 ast_sched_context_destroy(ast_channel_sched(chan));
2396         }
2397
2398         if (ast_channel_internal_is_finalized(chan)) {
2399                 char *dashptr;
2400
2401                 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2402                 if ((dashptr = strrchr(device_name, '-'))) {
2403                         *dashptr = '\0';
2404                 }
2405         } else {
2406                 device_name[0] = '\0';
2407         }
2408
2409         /* Stop monitoring */
2410         if (ast_channel_monitor(chan))
2411                 ast_channel_monitor(chan)->stop( chan, 0 );
2412
2413         /* If there is native format music-on-hold state, free it */
2414         if (ast_channel_music_state(chan))
2415                 ast_moh_cleanup(chan);
2416
2417         /* Free translators */
2418         if (ast_channel_readtrans(chan))
2419                 ast_translator_free_path(ast_channel_readtrans(chan));
2420         if (ast_channel_writetrans(chan))
2421                 ast_translator_free_path(ast_channel_writetrans(chan));
2422         if (ast_channel_pbx(chan))
2423                 ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2424
2425         ast_party_dialed_free(ast_channel_dialed(chan));
2426         ast_party_caller_free(ast_channel_caller(chan));
2427         ast_party_connected_line_free(ast_channel_connected(chan));
2428         ast_party_redirecting_free(ast_channel_redirecting(chan));
2429
2430         /* Close pipes if appropriate */
2431         ast_channel_internal_alertpipe_close(chan);
2432         if (ast_channel_timer(chan)) {
2433                 ast_timer_close(ast_channel_timer(chan));
2434                 ast_channel_timer_set(chan, NULL);
2435         }
2436 #ifdef HAVE_EPOLL
2437         for (i = 0; i < AST_MAX_FDS; i++) {
2438                 if (ast_channel_internal_epfd_data(chan, i)) {
2439                         ast_free(ast_channel_internal_epfd_data(chan, i));
2440                 }
2441         }
2442         close(ast_channel_epfd(chan));
2443 #endif
2444         while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2445                 ast_frfree(f);
2446
2447         /* loop over the variables list, freeing all data and deleting list items */
2448         /* no need to lock the list, as the channel is already locked */
2449         headp = ast_channel_varshead(chan);
2450         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2451                 ast_var_delete(vardata);
2452
2453         ast_app_group_discard(chan);
2454
2455         /* Destroy the jitterbuffer */
2456         ast_jb_destroy(chan);
2457
2458         if (ast_channel_cdr(chan)) {
2459                 ast_cdr_discard(ast_channel_cdr(chan));
2460                 ast_channel_cdr_set(chan, NULL);
2461         }
2462
2463         if (ast_channel_zone(chan)) {
2464                 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2465         }
2466
2467         ast_channel_internal_cleanup(chan);
2468
2469         if (device_name[0]) {
2470                 /*
2471                  * We have a device name to notify of a new state.
2472                  *
2473                  * Queue an unknown state, because, while we know that this particular
2474                  * instance is dead, we don't know the state of all other possible
2475                  * instances.
2476                  */
2477                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2478         }
2479
2480         ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2481         if (callid) {
2482                 ast_callid_unref(callid);
2483         }
2484
2485         ast_channel_named_callgroups_set(chan, NULL);
2486         ast_channel_named_pickupgroups_set(chan, NULL);
2487
2488         ast_atomic_fetchadd_int(&chancount, -1);
2489 }
2490
2491 /*! \brief Free a dummy channel structure */
2492 static void ast_dummy_channel_destructor(void *obj)
2493 {
2494         struct ast_channel *chan = obj;
2495         struct ast_datastore *datastore;
2496         struct ast_var_t *vardata;
2497         struct varshead *headp;
2498
2499         ast_pbx_hangup_handler_destroy(chan);
2500
2501         /* Get rid of each of the data stores on the channel */
2502         while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
2503                 /* Free the data store */
2504                 ast_datastore_free(datastore);
2505         }
2506
2507         ast_party_dialed_free(ast_channel_dialed(chan));
2508         ast_party_caller_free(ast_channel_caller(chan));
2509         ast_party_connected_line_free(ast_channel_connected(chan));
2510         ast_party_redirecting_free(ast_channel_redirecting(chan));
2511
2512         /* loop over the variables list, freeing all data and deleting list items */
2513         /* no need to lock the list, as the channel is already locked */
2514         headp = ast_channel_varshead(chan);
2515         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2516                 ast_var_delete(vardata);
2517
2518         if (ast_channel_cdr(chan)) {
2519                 ast_cdr_discard(ast_channel_cdr(chan));
2520                 ast_channel_cdr_set(chan, NULL);
2521         }
2522
2523         ast_channel_internal_cleanup(chan);
2524 }
2525
2526 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2527 {
2528         return ast_datastore_alloc(info, uid);
2529 }
2530
2531 int ast_channel_datastore_free(struct ast_datastore *datastore)
2532 {
2533         return ast_datastore_free(datastore);
2534 }
2535
2536 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2537 {
2538         struct ast_datastore *datastore = NULL, *datastore2;
2539
2540         AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2541                 if (datastore->inheritance > 0) {
2542                         datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2543                         if (datastore2) {
2544                                 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2545                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2546                                 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2547                         }
2548                 }
2549         }
2550         return 0;
2551 }
2552
2553 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2554 {
2555         int res = 0;
2556
2557         AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2558
2559         return res;
2560 }
2561
2562 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2563 {
2564         return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2565 }
2566
2567 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2568 {
2569         struct ast_datastore *datastore = NULL;
2570
2571         if (info == NULL)
2572                 return NULL;
2573
2574         AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2575                 if (datastore->info != info) {
2576                         continue;
2577                 }
2578
2579                 if (uid == NULL) {
2580                         /* matched by type only */
2581                         break;
2582                 }
2583
2584                 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2585                         /* Matched by type AND uid */
2586                         break;
2587                 }
2588         }
2589
2590         return datastore;
2591 }
2592
2593 /*! Set the file descriptor on the channel */
2594 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2595 {
2596 #ifdef HAVE_EPOLL
2597         struct epoll_event ev;
2598         struct ast_epoll_data *aed = NULL;
2599
2600         if (ast_channel_fd_isset(chan, which)) {
2601                 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2602                 aed = ast_channel_internal_epfd_data(chan, which);
2603         }
2604
2605         /* If this new fd is valid, add it to the epoll */
2606         if (fd > -1) {
2607                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2608                         return;
2609
2610                 ast_channel_internal_epfd_data_set(chan, which, aed);
2611                 aed->chan = chan;
2612                 aed->which = which;
2613
2614                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2615                 ev.data.ptr = aed;
2616                 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2617         } else if (aed) {
2618                 /* We don't have to keep around this epoll data structure now */
2619                 ast_free(aed);
2620                 ast_channel_epfd_data_set(chan, which, NULL);
2621         }
2622 #endif
2623         ast_channel_internal_fd_set(chan, which, fd);
2624         return;
2625 }
2626
2627 /*! Add a channel to an optimized waitfor */
2628 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2629 {
2630 #ifdef HAVE_EPOLL
2631         struct epoll_event ev;
2632         int i = 0;
2633
2634         if (ast_channel_epfd(chan0) == -1)
2635                 return;
2636
2637         /* Iterate through the file descriptors on chan1, adding them to chan0 */
2638         for (i = 0; i < AST_MAX_FDS; i++) {
2639                 if (!ast_channel_fd_isset(chan1, i)) {
2640                         continue;
2641                 }
2642                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2643                 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2644                 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2645         }
2646
2647 #endif
2648         return;
2649 }
2650
2651 /*! Delete a channel from an optimized waitfor */
2652 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2653 {
2654 #ifdef HAVE_EPOLL
2655         struct epoll_event ev;
2656         int i = 0;
2657
2658         if (ast_channel_epfd(chan0) == -1)
2659                 return;
2660
2661         for (i = 0; i < AST_MAX_FDS; i++) {
2662                 if (!ast_channel_fd_isset(chan1, i)) {
2663                         continue;
2664                 }
2665                 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2666         }
2667
2668 #endif
2669         return;
2670 }
2671
2672 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2673 {
2674         ast_channel_lock(chan);
2675
2676         ast_channel_softhangup_internal_flag_clear(chan, flag);
2677
2678         if (!ast_channel_softhangup_internal_flag(chan)) {
2679                 struct ast_frame *fr;
2680
2681                 /* If we have completely cleared the softhangup flag,
2682                  * then we need to fully abort the hangup process.  This requires
2683                  * pulling the END_OF_Q frame out of the channel frame queue if it
2684                  * still happens to be there. */
2685
2686                 fr = AST_LIST_LAST(ast_channel_readq(chan));
2687                 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2688                                 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2689                         AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2690                         ast_frfree(fr);
2691                 }
2692         }
2693
2694         ast_channel_unlock(chan);
2695 }
2696
2697 /*! \brief Softly hangup a channel, don't lock */
2698 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2699 {
2700         ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2701         /* Inform channel driver that we need to be hung up, if it cares */
2702         ast_channel_softhangup_internal_flag_add(chan, cause);
2703         ast_queue_frame(chan, &ast_null_frame);
2704         /* Interrupt any poll call or such */
2705         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2706                 pthread_kill(ast_channel_blocker(chan), SIGURG);
2707         return 0;
2708 }
2709
2710 /*! \brief Softly hangup a channel, lock */
2711 int ast_softhangup(struct ast_channel *chan, int cause)
2712 {
2713         int res;
2714
2715         ast_channel_lock(chan);
2716         res = ast_softhangup_nolock(chan, cause);
2717         /*** DOCUMENTATION
2718                 <managerEventInstance>
2719                         <synopsis>Raised when a soft hangup is requested with a specific cause code.</synopsis>
2720                                 <syntax>
2721                                         <xi:include xpointer="xpointer(/docs/managerEvent[@name='Hangup']/managerEventInstance/syntax/parameter[@name='Cause'])" />
2722                                 </syntax>
2723                 </managerEventInstance>
2724         ***/
2725         manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2726                 "Channel: %s\r\n"
2727                 "Uniqueid: %s\r\n"
2728                 "Cause: %d\r\n",
2729                 ast_channel_name(chan),
2730                 ast_channel_uniqueid(chan),
2731                 cause);
2732         ast_channel_unlock(chan);
2733
2734         return res;
2735 }
2736
2737 static void free_translation(struct ast_channel *clonechan)
2738 {
2739         if (ast_channel_writetrans(clonechan))
2740                 ast_translator_free_path(ast_channel_writetrans(clonechan));
2741         if (ast_channel_readtrans(clonechan))
2742                 ast_translator_free_path(ast_channel_readtrans(clonechan));
2743         ast_channel_writetrans_set(clonechan, NULL);
2744         ast_channel_readtrans_set(clonechan, NULL);
2745         if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2746                 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2747                 ast_format_clear(ast_channel_rawreadformat(clonechan));
2748         } else {
2749                 struct ast_format tmpfmt;
2750                 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2751                 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2752                 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2753         }
2754 }
2755
2756 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2757 {
2758         struct ast_channel *bridge;
2759
2760         ast_channel_lock(chan);
2761         if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2762                 ast_channel_hangupsource_set(chan, source);
2763         }
2764         bridge = ast_bridged_channel(chan);
2765         if (bridge) {
2766                 ast_channel_ref(bridge);
2767         }
2768         ast_channel_unlock(chan);
2769
2770         if (bridge) {
2771                 ast_channel_lock(bridge);
2772                 if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
2773                         ast_channel_hangupsource_set(bridge, source);
2774                 }
2775                 ast_channel_unlock(bridge);
2776                 ast_channel_unref(bridge);
2777         }
2778 }
2779
2780 static void destroy_hooks(struct ast_channel *chan)
2781 {
2782         if (ast_channel_audiohooks(chan)) {
2783                 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2784                 ast_channel_audiohooks_set(chan, NULL);
2785         }
2786
2787         ast_framehook_list_destroy(chan);
2788 }
2789
2790 /*! \brief Hangup a channel */
2791 int ast_hangup(struct ast_channel *chan)
2792 {
2793         char extra_str[64]; /* used for cel logging below */
2794
2795         ast_autoservice_stop(chan);
2796
2797         ast_channel_lock(chan);
2798
2799         /*
2800          * Do the masquerade if someone is setup to masquerade into us.
2801          *
2802          * NOTE: We must hold the channel lock after testing for a
2803          * pending masquerade and setting the channel as a zombie to
2804          * prevent __ast_channel_masquerade() from setting up a
2805          * masquerade with a dead channel.
2806          */
2807         while (ast_channel_masq(chan)) {
2808                 ast_channel_unlock(chan);
2809                 ast_do_masquerade(chan);
2810                 ast_channel_lock(chan);
2811         }
2812
2813         if (ast_channel_masqr(chan)) {
2814                 /*
2815                  * This channel is one which will be masqueraded into something.
2816                  * Mark it as a zombie already so ast_do_masquerade() will know
2817                  * to free it later.
2818                  */
2819                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2820                 destroy_hooks(chan);
2821                 ast_channel_unlock(chan);
2822                 return 0;
2823         }
2824
2825         /* Mark as a zombie so a masquerade cannot be setup on this channel. */
2826         ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2827
2828         ast_channel_unlock(chan);
2829
2830         /*
2831          * XXX if running the hangup handlers here causes problems
2832          * because the handlers take too long to execute, we could move
2833          * the meat of this function into another thread.  A thread
2834          * where channels go to die.
2835          *
2836          * If this is done, ast_autoservice_chan_hangup_peer() will no
2837          * longer be needed.
2838          */
2839         ast_pbx_hangup_handler_run(chan);
2840         ao2_unlink(channels, chan);
2841         ast_channel_lock(chan);
2842
2843         destroy_hooks(chan);
2844
2845         free_translation(chan);
2846         /* Close audio stream */
2847         if (ast_channel_stream(chan)) {
2848                 ast_closestream(ast_channel_stream(chan));
2849                 ast_channel_stream_set(chan, NULL);
2850         }
2851         /* Close video stream */
2852         if (ast_channel_vstream(chan)) {
2853                 ast_closestream(ast_channel_vstream(chan));
2854                 ast_channel_vstream_set(chan, NULL);
2855         }
2856         if (ast_channel_sched(chan)) {
2857                 ast_sched_context_destroy(ast_channel_sched(chan));
2858                 ast_channel_sched_set(chan, NULL);
2859         }
2860
2861         if (ast_channel_generatordata(chan)) {  /* Clear any tone stuff remaining */
2862                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2863                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2864                 }
2865         }
2866         ast_channel_generatordata_set(chan, NULL);
2867         ast_channel_generator_set(chan, NULL);
2868
2869         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"), ""));
2870         ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2871
2872         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2873                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2874                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
2875                         (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2876                 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2877         }
2878
2879         ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2880         if (ast_channel_tech(chan)->hangup) {
2881                 ast_channel_tech(chan)->hangup(chan);
2882         }
2883
2884         ast_channel_unlock(chan);
2885
2886         ast_cc_offer(chan);
2887         /*** DOCUMENTATION
2888                 <managerEventInstance>
2889                         <synopsis>Raised when a channel is hung up.</synopsis>
2890                                 <syntax>
2891                                         <parameter name="Cause">
2892                                                 <para>A numeric cause code for why the channel was hung up.</para>
2893                                         </parameter>
2894                                         <parameter name="Cause-txt">
2895                                                 <para>A description of why the channel was hung up.</para>
2896                                         </parameter>
2897                                 </syntax>
2898                 </managerEventInstance>
2899         ***/
2900         ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2901                 "Channel: %s\r\n"
2902                 "Uniqueid: %s\r\n"
2903                 "CallerIDNum: %s\r\n"
2904                 "CallerIDName: %s\r\n"
2905                 "ConnectedLineNum: %s\r\n"
2906                 "ConnectedLineName: %s\r\n"
2907                 "AccountCode: %s\r\n"
2908                 "Cause: %d\r\n"
2909                 "Cause-txt: %s\r\n",
2910                 ast_channel_name(chan),
2911                 ast_channel_uniqueid(chan),
2912                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
2913                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
2914                 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
2915                 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
2916                 ast_channel_accountcode(chan),
2917                 ast_channel_hangupcause(chan),
2918                 ast_cause2str(ast_channel_hangupcause(chan))
2919                 );
2920
2921         if (ast_channel_cdr(chan) && !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_BRIDGED) &&
2922                 !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_POST_DISABLED) &&
2923                 (ast_channel_cdr(chan)->disposition != AST_CDR_NULL || ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_DIALED))) {
2924                 ast_channel_lock(chan);
2925                 ast_cdr_end(ast_channel_cdr(chan));
2926                 ast_cdr_detach(ast_channel_cdr(chan));
2927                 ast_channel_cdr_set(chan, NULL);
2928                 ast_channel_unlock(chan);
2929         }
2930
2931         ast_channel_unref(chan);
2932
2933         return 0;
2934 }
2935
2936 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2937 {
2938         int res = 0;
2939
2940         ast_channel_lock(chan);
2941
2942         /* You can't answer an outbound call */
2943         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2944                 ast_channel_unlock(chan);
2945                 return 0;
2946         }
2947
2948         /* Stop if we're a zombie or need a soft hangup */
2949         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2950                 ast_channel_unlock(chan);
2951                 return -1;
2952         }
2953
2954         ast_channel_unlock(chan);
2955
2956         switch (ast_channel_state(chan)) {
2957         case AST_STATE_RINGING:
2958         case AST_STATE_RING:
2959                 ast_channel_lock(chan);
2960                 if (ast_channel_tech(chan)->answer) {
2961                         res = ast_channel_tech(chan)->answer(chan);
2962                 }
2963                 ast_setstate(chan, AST_STATE_UP);
2964                 if (cdr_answer) {
2965                         ast_cdr_answer(ast_channel_cdr(chan));
2966                 }
2967                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2968                 ast_channel_unlock(chan);
2969                 break;
2970         case AST_STATE_UP:
2971                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2972                 /* Calling ast_cdr_answer when it it has previously been called
2973                  * is essentially a no-op, so it is safe.
2974                  */
2975                 if (cdr_answer) {
2976                         ast_cdr_answer(ast_channel_cdr(chan));
2977                 }
2978                 break;
2979         default:
2980                 break;
2981         }
2982
2983         ast_indicate(chan, -1);
2984
2985         return res;
2986 }
2987
2988 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2989 {
2990         int res = 0;
2991         enum ast_channel_state old_state;
2992
2993         old_state = ast_channel_state(chan);
2994         if ((res = ast_raw_answer(chan, cdr_answer))) {
2995                 return res;
2996         }
2997
2998         switch (old_state) {
2999         case AST_STATE_RINGING:
3000         case AST_STATE_RING:
3001                 /* wait for media to start flowing, but don't wait any longer
3002                  * than 'delay' or 500 milliseconds, whichever is longer
3003                  */
3004                 do {
3005                         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
3006                         struct ast_frame *cur, *new;
3007                         int ms = MAX(delay, 500);
3008                         unsigned int done = 0;
3009
3010                         AST_LIST_HEAD_INIT_NOLOCK(&frames);
3011
3012                         for (;;) {
3013                                 ms = ast_waitfor(chan, ms);
3014                                 if (ms < 0) {
3015                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
3016                                         res = -1;
3017                                         break;
3018                                 }
3019                                 if (ms == 0) {
3020                                         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));
3021                                         break;
3022                                 }
3023                                 cur = ast_read(chan);
3024                                 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
3025                                              (cur->subclass.integer == AST_CONTROL_HANGUP))) {
3026                                         if (cur) {
3027                                                 ast_frfree(cur);
3028                                         }
3029                                         res = -1;
3030                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
3031                                         break;
3032                                 }
3033
3034                                 if ((new = ast_frisolate(cur)) != cur) {
3035                                         ast_frfree(cur);
3036                                 }
3037
3038                                 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
3039
3040                                 /* if a specific delay period was requested, continue
3041                                  * until that delay has passed. don't stop just because
3042                                  * incoming media has arrived.
3043                                  */
3044                                 if (delay) {
3045                                         continue;
3046                                 }
3047
3048                                 switch (new->frametype) {
3049                                         /* all of these frametypes qualify as 'media' */
3050                                 case AST_FRAME_VOICE:
3051                                 case AST_FRAME_VIDEO:
3052                                 case AST_FRAME_TEXT:
3053                                 case AST_FRAME_DTMF_BEGIN:
3054                                 case AST_FRAME_DTMF_END:
3055                                 case AST_FRAME_IMAGE:
3056                                 case AST_FRAME_HTML:
3057                                 case AST_FRAME_MODEM:
3058                                         done = 1;
3059                                         break;
3060                                 case AST_FRAME_CONTROL:
3061                                 case AST_FRAME_IAX:
3062                                 case AST_FRAME_NULL:
3063                                 case AST_FRAME_CNG:
3064                                         break;
3065                                 }
3066
3067                                 if (done) {
3068                                         break;
3069                                 }
3070                         }
3071
3072                         if (res == 0) {
3073                                 ast_channel_lock(chan);
3074                                 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
3075                                         ast_queue_frame_head(chan, cur);
3076                                         ast_frfree(cur);
3077                                 }
3078                                 ast_channel_unlock(chan);
3079                         }
3080                 } while (0);
3081                 break;
3082         default:
3083                 break;
3084         }
3085
3086         return res;
3087 }
3088
3089 int ast_answer(struct ast_channel *chan)
3090 {
3091         return __ast_answer(chan, 0, 1);
3092 }
3093
3094 void ast_deactivate_generator(struct ast_channel *chan)
3095 {
3096         ast_channel_lock(chan);
3097         if (ast_channel_generatordata(chan)) {
3098                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3099                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3100                 }
3101                 ast_channel_generatordata_set(chan, NULL);
3102                 ast_channel_generator_set(chan, NULL);
3103                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
3104                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
3105                 ast_settimeout(chan, 0, NULL, NULL);
3106         }
3107         ast_channel_unlock(chan);
3108 }
3109
3110 static void generator_write_format_change(struct ast_channel *chan)
3111 {
3112         ast_channel_lock(chan);
3113         if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
3114                 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
3115         }
3116         ast_channel_unlock(chan);
3117 }
3118
3119 static int generator_force(const void *data)
3120 {
3121         /* Called if generator doesn't have data */
3122         void *tmp;
3123         int res;
3124         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
3125         struct ast_channel *chan = (struct ast_channel *)data;
3126
3127         ast_channel_lock(chan);
3128         tmp = ast_channel_generatordata(chan);
3129         ast_channel_generatordata_set(chan, NULL);
3130         if (ast_channel_generator(chan))
3131                 generate = ast_channel_generator(chan)->generate;
3132         ast_channel_unlock(chan);
3133
3134         if (!tmp || !generate)
3135                 return 0;
3136
3137         res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
3138
3139         ast_channel_generatordata_set(chan, tmp);
3140
3141         if (res) {
3142                 ast_debug(1, "Auto-deactivating generator\n");
3143                 ast_deactivate_generator(chan);
3144         }
3145
3146         return 0;
3147 }
3148
3149 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
3150 {
3151         int res = 0;
3152         void *generatordata = NULL;
3153
3154         ast_channel_lock(chan);
3155         if (ast_channel_generatordata(chan)) {
3156                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3157                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3158                 }
3159         }
3160         if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
3161                 res = -1;
3162         }
3163         ast_channel_generatordata_set(chan, generatordata);
3164         if (!res) {
3165                 ast_settimeout(chan, 50, generator_force, chan);
3166                 ast_channel_generator_set(chan, gen);
3167         }
3168         ast_channel_unlock(chan);
3169
3170         ast_prod(chan);
3171
3172         return res;
3173 }
3174
3175 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
3176 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
3177 {
3178         int winner = -1;
3179         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
3180         return winner;
3181 }
3182
3183 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
3184 #ifdef HAVE_EPOLL
3185 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
3186                                         int *exception, int *outfd, int *ms)
3187 #else
3188 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3189                                         int *exception, int *outfd, int *ms)
3190 #endif
3191 {
3192         struct timeval start = { 0 , 0 };
3193         struct pollfd *pfds = NULL;
3194         int res;
3195         long rms;
3196         int x, y, max;
3197         int sz;
3198         struct timeval now = { 0, 0 };
3199         struct timeval whentohangup = { 0, 0 }, diff;
3200         struct ast_channel *winner = NULL;
3201         struct fdmap {
3202                 int chan;
3203                 int fdno;
3204         } *fdmap = NULL;
3205
3206         if (outfd) {
3207                 *outfd = -99999;
3208         }
3209         if (exception) {
3210                 *exception = 0;
3211         }
3212
3213         if ((sz = n * AST_MAX_FDS + nfds)) {
3214                 pfds = ast_alloca(sizeof(*pfds) * sz);
3215                 fdmap = ast_alloca(sizeof(*fdmap) * sz);
3216         } else {
3217                 /* nothing to allocate and no FDs to check */
3218                 return NULL;
3219         }
3220
3221         /* Perform any pending masquerades */
3222         for (x = 0; x < n; x++) {
3223                 while (ast_channel_masq(c[x])) {
3224                         ast_do_masquerade(c[x]);
3225                 }
3226
3227                 ast_channel_lock(c[x]);
3228                 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
3229                         if (ast_tvzero(whentohangup))
3230                                 now = ast_tvnow();
3231                         diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
3232                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3233                                 /* Should already be hungup */
3234                                 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3235                                 ast_channel_unlock(c[x]);
3236                                 return c[x];
3237                         }
3238                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3239                                 whentohangup = diff;
3240                 }
3241                 ast_channel_unlock(c[x]);
3242         }
3243         /* Wait full interval */
3244         rms = *ms;
3245         /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3246         if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3247                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
3248                 if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
3249                         rms =  *ms;
3250                 }
3251         } else if (!ast_tvzero(whentohangup) && rms < 0) {
3252                 /* Tiny corner case... call would need to last >24 days */
3253                 rms = INT_MAX;
3254         }
3255         /*
3256          * Build the pollfd array, putting the channels' fds first,
3257          * followed by individual fds. Order is important because
3258          * individual fd's must have priority over channel fds.
3259          */
3260         max = 0;
3261         for (x = 0; x < n; x++) {
3262                 for (y = 0; y < AST_MAX_FDS; y++) {
3263                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
3264                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
3265                         max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3266                 }
3267                 CHECK_BLOCKING(c[x]);
3268         }
3269         /* Add the individual fds */
3270         for (x = 0; x < nfds; x++) {
3271                 fdmap[max].chan = -1;
3272                 max += ast_add_fd(&pfds[max], fds[x]);
3273         }
3274
3275         if (*ms > 0) {
3276                 start = ast_tvnow();
3277         }
3278
3279         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3280                 do {
3281                         int kbrms = rms;
3282                         if (kbrms > 600000) {
3283                                 kbrms = 600000;
3284                         }
3285                         res = ast_poll(pfds, max, kbrms);
3286                         if (!res) {
3287                                 rms -= kbrms;
3288                         }
3289                 } while (!res && (rms > 0));
3290         } else {
3291                 res = ast_poll(pfds, max, rms);
3292         }
3293         for (x = 0; x < n; x++) {
3294                 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3295         }
3296         if (res < 0) { /* Simulate a timeout if we were interrupted */
3297                 if (errno != EINTR) {
3298                         *ms = -1;
3299                 }
3300                 return NULL;
3301         }
3302         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
3303                 now = ast_tvnow();
3304                 for (x = 0; x < n; x++) {
3305                         if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3306                                 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3307                                 if (winner == NULL) {
3308                                         winner = c[x];
3309                                 }
3310                         }
3311                 }
3312         }
3313         if (res == 0) { /* no fd ready, reset timeout and done */
3314                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
3315                 return winner;
3316         }
3317         /*
3318          * Then check if any channel or fd has a pending event.
3319          * Remember to check channels first and fds last, as they
3320          * must have priority on setting 'winner'
3321          */
3322         for (x = 0; x < max; x++) {
3323                 res = pfds[x].revents;
3324                 if (res == 0) {
3325                         continue;
3326                 }
3327                 if (fdmap[x].chan >= 0) {       /* this is a channel */
3328                         winner = c[fdmap[x].chan];      /* override previous winners */
3329                         if (res & POLLPRI) {
3330                                 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3331                         } else {
3332                                 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3333                         }
3334                         ast_channel_fdno_set(winner, fdmap[x].fdno);
3335                 } else {                        /* this is an fd */
3336                         if (outfd) {
3337                                 *outfd = pfds[x].fd;
3338                         }
3339                         if (exception) {
3340                                 *exception = (res & POLLPRI) ? -1 : 0;
3341                         }
3342                         winner = NULL;
3343                 }
3344         }
3345         if (*ms > 0) {
3346                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3347                 if (*ms < 0) {
3348                         *ms = 0;
3349                 }
3350         }
3351         return winner;
3352 }
3353
3354 #ifdef HAVE_EPOLL
3355 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3356 {
3357         struct timeval start = { 0 , 0 };
3358         int res = 0;
3359         struct epoll_event ev[1];
3360         long diff, rms = *ms;
3361         struct ast_channel *winner = NULL;
3362         struct ast_epoll_data *aed = NULL;
3363
3364
3365         /* See if this channel needs to be masqueraded */
3366         while (ast_channel_masq(chan)) {
3367                 ast_do_masquerade(chan);
3368         }
3369
3370         ast_channel_lock(chan);
3371         /* Figure out their timeout */
3372         if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3373                 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow())) < 0) {
3374                         /* They should already be hungup! */
3375                         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3376                         ast_channel_unlock(chan);
3377                         return NULL;
3378                 }
3379                 /* If this value is smaller then the current one... make it priority */
3380                 if (rms > diff) {
3381                         rms = diff;
3382                 }
3383         }
3384
3385         ast_channel_unlock(chan);
3386
3387         /* Time to make this channel block... */
3388         CHECK_BLOCKING(chan);
3389
3390         if (*ms > 0) {
3391                 start = ast_tvnow();
3392         }
3393
3394         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3395         res = epoll_wait(ast_channel_epfd(chan), ev, 1, rms);
3396
3397         /* Stop blocking */
3398         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
3399
3400         /* Simulate a timeout if we were interrupted */
3401         if (res < 0) {
3402                 if (errno != EINTR) {
3403                         *ms = -1;
3404                 }
3405                 return NULL;
3406         }
3407
3408         /* If this channel has a timeout see if it expired */
3409         if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3410                 if (ast_tvdiff_ms(ast_tvnow(), *ast_channel_whentohangup(chan)) >= 0) {
3411                         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3412                         winner = chan;
3413                 }
3414         }
3415
3416         /* No fd ready, reset timeout and be done for now */
3417         if (!res) {
3418                 *ms = 0;
3419                 return winner;
3420         }
3421
3422         /* See what events are pending */
3423         aed = ev[0].data.ptr;
3424         ast_channel_fdno_set(chan, aed->which);
3425         if (ev[0].events & EPOLLPRI) {
3426                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3427         } else {
3428                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3429         }
3430
3431         if (*ms > 0) {
3432                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3433                 if (*ms < 0) {
3434                         *ms = 0;
3435                 }
3436         }
3437
3438         return chan;
3439 }
3440
3441 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3442 {
3443         struct timeval start = { 0 , 0 };
3444         int res = 0, i;
3445         struct epoll_event ev[25] = { { 0, } };
3446         struct timeval now = { 0, 0 };
3447         long whentohangup = 0, diff = 0, rms = *ms;
3448         struct ast_channel *winner = NULL;
3449
3450         for (i = 0; i < n; i++) {
3451                 while (ast_channel_masq(c[i])) {
3452                         ast_do_masquerade(c[i]);
3453                 }
3454
3455                 ast_channel_lock(c[i]);
3456                 if (!ast_tvzero(*ast_channel_whentohangup(c[i]))) {
3457                         if (whentohangup == 0) {
3458                                 now = ast_tvnow();
3459                         }
3460                         if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(c[i]), now)) < 0) {
3461                                 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3462                                 ast_channel_unlock(c[i]);
3463                                 return c[i];
3464                         }
3465                         if (!whentohangup || whentohangup > diff) {
3466                                 whentohangup = diff;
3467                         }
3468                 }
3469                 ast_channel_unlock(c[i]);
3470                 CHECK_BLOCKING(c[i]);
3471         }
3472
3473         rms = *ms;
3474         if (whentohangup) {
3475                 rms = whentohangup;
3476                 if (*ms >= 0 && *ms < rms) {
3477                         rms = *ms;
3478                 }
3479         }
3480
3481         if (*ms > 0) {
3482                 start = ast_tvnow();
3483         }
3484
3485         res = epoll_wait(ast_channel_epfd(c[0]), ev, 25, rms);
3486
3487         for (i = 0; i < n; i++) {
3488                 ast_clear_flag(ast_channel_flags(c[i]), AST_FLAG_BLOCKING);
3489         }
3490
3491         if (res < 0) {
3492                 if (errno != EINTR) {
3493                         *ms = -1;
3494                 }
3495                 return NULL;
3496         }
3497
3498         if (whentohangup) {
3499                 now = ast_tvnow();
3500                 for (i = 0; i < n; i++) {
3501                         if (!ast_tvzero(*ast_channel_whentohangup(c[i])) && ast_tvdiff_ms(now, *ast_channel_whentohangup(c[i])) >= 0) {
3502                                 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3503                                 if (!winner) {
3504                                         winner = c[i];
3505                                 }
3506                         }
3507                 }
3508         }
3509
3510         if (!res) {
3511                 *ms = 0;
3512                 return winner;
3513         }
3514
3515         for (i = 0; i < res; i++) {
3516                 struct ast_epoll_data *aed = ev[i].data.ptr;
3517
3518                 if (!ev[i].events || !aed) {
3519                         continue;
3520                 }
3521
3522                 winner = aed->chan;
3523                 if (ev[i].events & EPOLLPRI) {
3524                         ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3525                 } else {
3526                         ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3527                 }
3528                 ast_channel_fdno_set(winner, aed->which);
3529         }
3530
3531         if (*ms > 0) {
3532                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3533                 if (*ms < 0) {
3534                         *ms = 0;
3535                 }
3536         }
3537
3538         return winner;
3539 }
3540
3541 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3542                                         int *exception, int *outfd, int *ms)
3543 {
3544         /* Clear all provided values in one place. */
3545         if (outfd) {
3546                 *outfd = -99999;
3547         }
3548         if (exception) {
3549                 *exception = 0;
3550         }
3551
3552         /* If no epoll file descriptor is available resort to classic nandfds */
3553         if (!n || nfds || ast_channel_epfd(c[0]) == -1) {
3554                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3555         } else if (!nfds && n == 1) {
3556                 return ast_waitfor_nandfds_simple(c[0], ms);
3557         } else {
3558                 return ast_waitfor_nandfds_complex(c, n, ms);
3559         }
3560 }
3561 #endif
3562
3563 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3564 {
3565         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3566 }
3567
3568 int ast_waitfor(struct ast_channel *c, int ms)
3569 {
3570         int oldms = ms; /* -1 if no timeout */
3571
3572         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3573         if ((ms < 0) && (oldms < 0)) {
3574                 ms = 0;
3575         }
3576         return ms;
3577 }
3578
3579 int ast_waitfordigit(struct ast_channel *c, int ms)
3580 {
3581         return ast_waitfordigit_full(c, ms, -1, -1);
3582 }
3583
3584 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3585 {
3586         int res;
3587         unsigned int real_rate = rate, max_rate;
3588
3589         ast_channel_lock(c);
3590
3591         if (ast_channel_timingfd(c) == -1) {
3592                 ast_channel_unlock(c);
3593                 return -1;
3594         }
3595
3596         if (!func) {
3597                 rate = 0;
3598                 data = NULL;
3599         }
3600
3601         if (rate && rate > (max_rate = ast_timer_get_max_rate(ast_channel_timer(c)))) {
3602                 real_rate = max_rate;
3603         }
3604
3605         ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3606
3607         res = ast_timer_set_rate(ast_channel_timer(c), real_rate);
3608
3609         ast_channel_timingfunc_set(c, func);
3610         ast_channel_timingdata_set(c, data);
3611
3612         if (func == NULL && rate == 0 && ast_channel_fdno(c) == AST_TIMING_FD) {
3613                 /* Clearing the timing func and setting the rate to 0
3614                  * means that we don't want to be reading from the timingfd
3615                  * any more. Setting c->fdno to -1 means we won't have any
3616                  * errant reads from the timingfd, meaning we won't potentially
3617                  * miss any important frames.
3618                  */
3619                 ast_channel_fdno_set(c, -1);
3620         }
3621
3622         ast_channel_unlock(c);
3623
3624         return res;
3625 }
3626
3627 int ast_waitfordigit_full(struct ast_channel *c, int timeout_ms, int audiofd, int cmdfd)
3628 {
3629         struct timeval start = ast_tvnow();
3630
3631         /* Stop if we're a zombie or need a soft hangup */
3632         if (ast_test_flag(ast_channel_flags(c), AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3633                 return -1;
3634
3635         /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3636         ast_set_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3637
3638         /* Wait for a digit, no more than timeout_ms milliseconds total.
3639          * Or, wait indefinitely if timeout_ms is <0.
3640          */
3641         while (ast_tvdiff_ms(ast_tvnow(), start) < timeout_ms || timeout_ms < 0) {
3642                 struct ast_channel *rchan;
3643                 int outfd=-1;
3644                 int ms;
3645
3646                 if (timeout_ms < 0) {
3647                         ms = timeout_ms;
3648                 } else {
3649                         ms = timeout_ms - ast_tvdiff_ms(ast_tvnow(), start);
3650                         if (ms < 0) {
3651                                 ms = 0;
3652                         }
3653                 }
3654
3655                 errno = 0;
3656                 /* While ast_waitfor_nandfds tries to help by reducing the timeout by how much was waited,
3657                  * it is unhelpful if it waited less than a millisecond.
3658                  */
3659                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3660
3661                 if (!rchan && outfd < 0 && ms) {
3662                         if (errno == 0 || errno == EINTR)
3663                                 continue;
3664                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
3665                         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3666                         return -1;
3667                 } else if (outfd > -1) {
3668                         /* The FD we were watching has something waiting */
3669                         ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
3670                         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3671                         return 1;
3672                 } else if (rchan) {
3673                         int res;
3674                         struct ast_frame *f = ast_read(c);
3675                         if (!f)
3676                                 return -1;
3677
3678                         switch (f->frametype) {
3679                         case AST_FRAME_DTMF_BEGIN:
3680                                 break;
3681                         case AST_FRAME_DTMF_END:
3682                                 res = f->subclass.integer;
3683                                 ast_frfree(f);
3684                                 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3685                                 return res;
3686                         case AST_FRAME_CONTROL:
3687                                 switch (f->subclass.integer) {
3688                                 case AST_CONTROL_HANGUP:
3689                                         ast_frfree(f);
3690                                         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3691                                         return -1;
3692                                 case AST_CONTROL_PVT_CAUSE_CODE:
3693                                 case AST_CONTROL_RINGING:
3694                                 case AST_CONTROL_ANSWER:
3695                                 case AST_CONTROL_SRCUPDATE:
3696                                 case AST_CONTROL_SRCCHANGE:
3697                                 case AST_CONTROL_CONNECTED_LINE:
3698                                 case AST_CONTROL_REDIRECTING:
3699                                 case AST_CONTROL_UPDATE_RTP_PEER:
3700                                 case AST_CONTROL_HOLD:
3701                                 case AST_CONTROL_UNHOLD:
3702                                 case -1:
3703                                         /* Unimportant */
3704                                         break;
3705                                 default:
3706                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
3707                                         break;
3708                                 }
3709                                 break;
3710                         case AST_FRAME_VOICE:
3711                                 /* Write audio if appropriate */
3712                                 if (audiofd > -1) {
3713                                         if (write(audiofd, f->data.ptr, f->datalen) < 0) {
3714                                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3715                                         }
3716                                 }
3717                         default:
3718                                 /* Ignore */
3719                                 break;
3720                         }
3721                         ast_frfree(f);
3722                 }
3723         }
3724
3725         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3726
3727         return 0; /* Time is up */
3728 }
3729
3730 static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
3731 {
3732         /*** DOCUMENTATION
3733                 <managerEventInstance>
3734                         <synopsis>Raised when a DTMF digit has started or ended on a channel.</synopsis>
3735                                 <syntax>
3736                                         <parameter name="Direction">
3737                                                 <enumlist>
3738                                                         <enum name="Received"/>
3739                                                         <enum name="Sent"/>
3740                                                 </enumlist>
3741                                         </parameter>
3742                                         <parameter name="Begin">
3743                                                 <enumlist>
3744                                                         <enum name="Yes"/>
3745                                                         <enum name="No"/>
3746                                                 </enumlist>
3747                                         </parameter>
3748                                         <parameter name="End">
3749                                                 <enumlist>
3750                                                         <enum name="Yes"/>
3751                                                         <enum name="No"/>
3752                                                 </enumlist>
3753                                         </parameter>
3754                                 </syntax>
3755                 </managerEventInstance>
3756         ***/
3757         ast_manager_event(chan, EVENT_FLAG_DTMF,
3758                         "DTMF",
3759                         "Channel: %s\r\n"
3760                         "Uniqueid: %s\r\n"
3761                         "Digit: %c\r\n"
3762                         "Direction: %s\r\n"
3763                         "Begin: %s\r\n"
3764                         "End: %s\r\n",
3765                         ast_channel_name(chan), ast_channel_uniqueid(chan), digit, direction, begin, end);
3766 }
3767
3768 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
3769 {
3770         if (ast_channel_generator(chan) && ast_channel_generator(chan)->generate && ast_channel_generatordata(chan) &&  !ast_internal_timing_enabled(chan)) {
3771                 void *tmp = ast_channel_generatordata(chan);
3772                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = ast_channel_generator(chan)->generate;
3773                 int res;
3774                 int samples;
3775
3776                 if (ast_channel_timingfunc(chan)) {
3777                         ast_debug(1, "Generator got voice, switching to phase locked mode\n");
3778                         ast_settimeout(chan, 0, NULL, NULL);
3779                 }
3780
3781                 ast_channel_generatordata_set(chan, NULL);     /* reset, to let writes go through */
3782
3783                 if (ast_format_cmp(&f->subclass.format, ast_channel_writeformat(chan)) == AST_FORMAT_CMP_NOT_EQUAL) {
3784                         float factor;
3785                         factor = ((float) ast_format_rate(ast_channel_writeformat(chan))) / ((float) ast_format_rate(&f->subclass.format));
3786                         samples = (int) ( ((float) f->samples) * factor );
3787                 } else {
3788                         samples = f->samples;
3789                 }
3790
3791                 /* This unlock is here based on two assumptions that hold true at this point in the
3792                  * code. 1) this function is only called from within __ast_read() and 2) all generators
3793                  * call ast_write() in their generate callback.
3794                  *
3795                  * The reason this is added is so that when ast_write is called, the lock that occurs
3796                  * there will not recursively lock the channel. Doing this will cause intended deadlock
3797                  * avoidance not to work in deeper functions
3798                  */
3799                 ast_channel_unlock(chan);
3800                 res = generate(chan, tmp, f->datalen, samples);
3801                 ast_channel_lock(chan);
3802                 ast_channel_generatordata_set(chan, tmp);
3803                 if (res) {
3804                         ast_debug(1, "Auto-deactivating generator\n");
3805                         ast_deactivate_generator(chan);
3806                 }
3807
3808         } else if (f->frametype == AST_FRAME_CNG) {
3809                 if (ast_channel_generator(chan) && !ast_channel_timingfunc(chan) && (ast_channel_timingfd(chan) > -1)) {
3810                         ast_debug(1, "Generator got CNG, switching to timed mode\n");
3811                         ast_settimeout(chan, 50, generator_force, chan);
3812                 }
3813         }
3814 }
3815
3816 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3817 {
3818         struct ast_frame *fr = ast_channel_dtmff(chan);
3819
3820         fr->frametype = AST_FRAME_DTMF_END;
3821         fr->subclass.integer = f->subclass.integer;
3822         fr->len = f->len;
3823
3824         /* The only time this function will be called is for a frame that just came
3825          * out of the channel driver.  So, we want to stick it on the tail of the
3826          * readq. */
3827
3828         ast_queue_frame(chan, fr);
3829 }
3830
3831 /*!
3832  * \brief Determine whether or not we should ignore DTMF in the readq
3833  */
3834 static inline int should_skip_dtmf(struct ast_channel *chan)
3835 {
3836         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
3837                 /* We're in the middle of emulating a digit, or DTMF has been
3838                  * explicitly deferred.  Skip this digit, then. */
3839                 return 1;
3840         }
3841
3842         if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
3843                         ast_tvdiff_ms(ast_tvnow(), *ast_channel_dtmf_tv(chan)) < AST_MIN_DTMF_GAP) {
3844                 /* We're not in the middle of a digit, but it hasn't been long enough
3845                  * since the last digit, so we'll have to skip DTMF for now. */
3846                 return 1;
3847         }
3848
3849         return 0;
3850 }
3851
3852 /*!
3853  * \brief calculates the number of samples to jump forward with in a monitor stream.
3854
3855  * \note When using ast_seekstream() with the read and write streams of a monitor,
3856  * the number of samples to seek forward must be of the same sample rate as the stream