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