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