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