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