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