bridge_native_rtp: Deadlock during 4-way conference 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         snapshot = ast_channel_snapshot_create(channel);
682         if (!snapshot) {
683                 return NULL;
684         }
685
686         return stasis_message_create(ast_channel_snapshot_type(), snapshot);
687 }
688
689 static void publish_cache_clear(struct ast_channel *chan)
690 {
691         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
692         RAII_VAR(struct stasis_message *, clear_msg, NULL, ao2_cleanup);
693
694         clear_msg = create_channel_snapshot_message(chan);
695         if (!clear_msg) {
696                 return;
697         }
698
699         message = stasis_cache_clear_create(clear_msg);
700         stasis_publish(ast_channel_topic(chan), message);
701 }
702
703 /*! \brief Gives the string form of a given channel state.
704  *
705  * \note This function is not reentrant.
706  *
707  * \param state
708  */
709 const char *ast_state2str(enum ast_channel_state state)
710 {
711         char *buf;
712
713         switch (state) {
714         case AST_STATE_DOWN:
715                 return "Down";
716         case AST_STATE_RESERVED:
717                 return "Rsrvd";
718         case AST_STATE_OFFHOOK:
719                 return "OffHook";
720         case AST_STATE_DIALING:
721                 return "Dialing";
722         case AST_STATE_RING:
723                 return "Ring";
724         case AST_STATE_RINGING:
725                 return "Ringing";
726         case AST_STATE_UP:
727                 return "Up";
728         case AST_STATE_BUSY:
729                 return "Busy";
730         case AST_STATE_DIALING_OFFHOOK:
731                 return "Dialing Offhook";
732         case AST_STATE_PRERING:
733                 return "Pre-ring";
734         default:
735                 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
736                         return "Unknown";
737                 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
738                 return buf;
739         }
740 }
741
742 /*! \brief Gives the string form of a given transfer capability */
743 char *ast_transfercapability2str(int transfercapability)
744 {
745         switch (transfercapability) {
746         case AST_TRANS_CAP_SPEECH:
747                 return "SPEECH";
748         case AST_TRANS_CAP_DIGITAL:
749                 return "DIGITAL";
750         case AST_TRANS_CAP_RESTRICTED_DIGITAL:
751                 return "RESTRICTED_DIGITAL";
752         case AST_TRANS_CAP_3_1K_AUDIO:
753                 return "3K1AUDIO";
754         case AST_TRANS_CAP_DIGITAL_W_TONES:
755                 return "DIGITAL_W_TONES";
756         case AST_TRANS_CAP_VIDEO:
757                 return "VIDEO";
758         default:
759                 return "UNKNOWN";
760         }
761 }
762
763 /*! \brief Pick the best audio codec */
764 struct ast_format *ast_best_codec(struct ast_format_cap *cap, struct ast_format *result)
765 {
766         /* This just our opinion, expressed in code.  We are asked to choose
767            the best codec to use, given no information */
768         static const enum ast_format_id prefs[] =
769         {
770                 /*! Okay, ulaw is used by all telephony equipment, so start with it */
771                 AST_FORMAT_ULAW,
772                 /*! Unless of course, you're a silly European, so then prefer ALAW */
773                 AST_FORMAT_ALAW,
774                 AST_FORMAT_G719,
775                 AST_FORMAT_SIREN14,
776                 AST_FORMAT_SIREN7,
777                 AST_FORMAT_TESTLAW,
778                 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
779                 AST_FORMAT_G722,
780                 /*! Okay, well, signed linear is easy to translate into other stuff */
781                 AST_FORMAT_SLINEAR192,
782                 AST_FORMAT_SLINEAR96,
783                 AST_FORMAT_SLINEAR48,
784                 AST_FORMAT_SLINEAR44,
785                 AST_FORMAT_SLINEAR32,
786                 AST_FORMAT_SLINEAR24,
787                 AST_FORMAT_SLINEAR16,
788                 AST_FORMAT_SLINEAR12,
789                 AST_FORMAT_SLINEAR,
790                 /*! G.726 is standard ADPCM, in RFC3551 packing order */
791                 AST_FORMAT_G726,
792                 /*! G.726 is standard ADPCM, in AAL2 packing order */
793                 AST_FORMAT_G726_AAL2,
794                 /*! ADPCM has great sound quality and is still pretty easy to translate */
795                 AST_FORMAT_ADPCM,
796                 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
797                     translate and sounds pretty good */
798                 AST_FORMAT_GSM,
799                 /*! iLBC is not too bad */
800                 AST_FORMAT_ILBC,
801                 /*! Speex is free, but computationally more expensive than GSM */
802                 AST_FORMAT_SPEEX32,
803                 AST_FORMAT_SPEEX16,
804                 AST_FORMAT_SPEEX,
805                 /*! Opus */
806                 AST_FORMAT_OPUS,
807                 /*! SILK is pretty awesome. */
808                 AST_FORMAT_SILK,
809                 /*! CELT supports crazy high sample rates */
810                 AST_FORMAT_CELT,
811                 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
812                     to use it */
813                 AST_FORMAT_LPC10,
814                 /*! G.729a is faster than 723 and slightly less expensive */
815                 AST_FORMAT_G729A,
816                 /*! Down to G.723.1 which is proprietary but at least designed for voice */
817                 AST_FORMAT_G723_1,
818         };
819         char buf[512];
820         int x;
821
822         /* Find the first preferred codec in the format given */
823         for (x = 0; x < ARRAY_LEN(prefs); x++) {
824                 if (ast_format_cap_best_byid(cap, prefs[x], result)) {
825                         return result;
826                 }
827         }
828
829         ast_format_clear(result);
830         ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
831
832         return NULL;
833 }
834
835 /*! \brief Channel technology used to extract a channel from a running application. The
836  * channel created with this technology will be immediately hung up - most external
837  * applications won't ever want to see this.
838  */
839 static const struct ast_channel_tech surrogate_tech = {
840         .type = "Surrogate",
841         .description = "Surrogate channel used to pull channel from an application",
842         .properties = AST_CHAN_TP_INTERNAL,
843 };
844
845 static const struct ast_channel_tech null_tech = {
846         .type = "NULL",
847         .description = "Null channel (should not see this)",
848 };
849
850 static void ast_channel_destructor(void *obj);
851 static void ast_dummy_channel_destructor(void *obj);
852
853 /*! \brief Create a new channel structure */
854 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
855 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
856                        const char *acctcode, const char *exten, const char *context,
857                        const char *linkedid, enum ama_flags amaflag, const char *file, int line,
858                        const char *function, const char *name_fmt, va_list ap)
859 {
860         struct ast_channel *tmp;
861         struct varshead *headp;
862         char *tech = "", *tech2 = NULL;
863         struct ast_format_cap *nativeformats;
864         struct ast_sched_context *schedctx;
865         struct ast_timer *timer;
866         struct timeval now;
867         const struct ast_channel_tech *channel_tech;
868
869         /* If shutting down, don't allocate any new channels */
870         if (ast_shutting_down()) {
871                 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
872                 return NULL;
873         }
874
875         if (!(tmp = ast_channel_internal_alloc(ast_channel_destructor, linkedid))) {
876                 /* Channel structure allocation failure. */
877                 return NULL;
878         }
879
880         ast_channel_stage_snapshot(tmp);
881
882         if (!(nativeformats = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_CACHE_STRINGS))) {
883                 ao2_ref(tmp, -1);
884                 /* format capabilities structure allocation failure */
885                 return NULL;
886         }
887         ast_channel_nativeformats_set(tmp, nativeformats);
888
889         /*
890          * Init file descriptors to unopened state so
891          * the destructor can know not to close them.
892          */
893         ast_channel_timingfd_set(tmp, -1);
894         ast_channel_internal_alertpipe_clear(tmp);
895         ast_channel_internal_fd_clear_all(tmp);
896
897 #ifdef HAVE_EPOLL
898         ast_channel_epfd_set(tmp, epoll_create(25));
899 #endif
900
901         if (!(schedctx = ast_sched_context_create())) {
902                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
903                 return ast_channel_unref(tmp);
904         }
905         ast_channel_sched_set(tmp, schedctx);
906
907         ast_party_dialed_init(ast_channel_dialed(tmp));
908         ast_party_caller_init(ast_channel_caller(tmp));
909         ast_party_connected_line_init(ast_channel_connected(tmp));
910         ast_party_connected_line_init(ast_channel_connected_indicated(tmp));
911         ast_party_redirecting_init(ast_channel_redirecting(tmp));
912
913         if (cid_name) {
914                 ast_channel_caller(tmp)->id.name.valid = 1;
915                 ast_channel_caller(tmp)->id.name.str = ast_strdup(cid_name);
916                 if (!ast_channel_caller(tmp)->id.name.str) {
917                         return ast_channel_unref(tmp);
918                 }
919         }
920         if (cid_num) {
921                 ast_channel_caller(tmp)->id.number.valid = 1;
922                 ast_channel_caller(tmp)->id.number.str = ast_strdup(cid_num);
923                 if (!ast_channel_caller(tmp)->id.number.str) {
924                         return ast_channel_unref(tmp);
925                 }
926         }
927
928         if ((timer = ast_timer_open())) {
929                 ast_channel_timer_set(tmp, timer);
930                 if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
931                         needqueue = 0;
932                 }
933                 ast_channel_timingfd_set(tmp, ast_timer_fd(ast_channel_timer(tmp)));
934         }
935
936         if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
937                 return ast_channel_unref(tmp);
938         }
939
940         /* Always watch the alertpipe */
941         ast_channel_set_fd(tmp, AST_ALERT_FD, ast_channel_internal_alert_readfd(tmp));
942         /* And timing pipe */
943         ast_channel_set_fd(tmp, AST_TIMING_FD, ast_channel_timingfd(tmp));
944
945         /* Initial state */
946         ast_channel_state_set(tmp, state);
947         ast_channel_hold_state_set(tmp, AST_CONTROL_UNHOLD);
948
949         ast_channel_streamid_set(tmp, -1);
950
951         ast_channel_fin_set(tmp, global_fin);
952         ast_channel_fout_set(tmp, global_fout);
953
954         now = ast_tvnow();
955         ast_channel_creationtime_set(tmp, &now);
956
957         ast_channel_internal_setup_topics(tmp);
958
959         if (!ast_strlen_zero(name_fmt)) {
960                 char *slash, *slash2;
961                 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
962                  * And they all use slightly different formats for their name string.
963                  * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
964                  * This means, that the stringfields must have a routine that takes the va_lists directly, and
965                  * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
966                  * This new function was written so this can be accomplished.
967                  */
968                 ast_channel_name_build_va(tmp, name_fmt, ap);
969                 tech = ast_strdupa(ast_channel_name(tmp));
970                 if ((slash = strchr(tech, '/'))) {
971                         if ((slash2 = strchr(slash + 1, '/'))) {
972                                 tech2 = slash + 1;
973                                 *slash2 = '\0';
974                         }
975                         *slash = '\0';
976                 }
977         } else {
978                 /*
979                  * Start the string with '-' so it becomes an empty string
980                  * in the destructor.
981                  */
982                 ast_channel_name_set(tmp, "-**Unknown**");
983         }
984
985         if (amaflag != AST_AMA_NONE) {
986                 ast_channel_amaflags_set(tmp, amaflag);
987         } else {
988                 ast_channel_amaflags_set(tmp, DEFAULT_AMA_FLAGS);
989         }
990
991         if (!ast_strlen_zero(acctcode)) {
992                 ast_channel_accountcode_set(tmp, acctcode);
993         }
994         ast_channel_language_set(tmp, ast_defaultlanguage);
995
996         ast_channel_context_set(tmp, S_OR(context, "default"));
997         ast_channel_exten_set(tmp, S_OR(exten, "s"));
998         ast_channel_priority_set(tmp, 1);
999
1000         headp = ast_channel_varshead(tmp);
1001         AST_LIST_HEAD_INIT_NOLOCK(headp);
1002
1003         ast_pbx_hangup_handler_init(tmp);
1004         AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1005         AST_LIST_HEAD_INIT_NOLOCK(ast_channel_autochans(tmp));
1006
1007         channel_tech = ast_get_channel_tech(tech);
1008         if (!channel_tech && !ast_strlen_zero(tech2)) {
1009                 channel_tech = ast_get_channel_tech(tech2);
1010         }
1011         if (channel_tech) {
1012                 ast_channel_tech_set(tmp, channel_tech);
1013         } else {
1014                 ast_channel_tech_set(tmp, &null_tech);
1015         }
1016
1017         ast_channel_internal_finalize(tmp);
1018
1019         ast_atomic_fetchadd_int(&chancount, +1);
1020         ao2_link(channels, tmp);
1021
1022         /*
1023          * And now, since the channel structure is built, and has its name, let
1024          * the world know of its existance
1025          */
1026         ast_channel_stage_snapshot_done(tmp);
1027         return tmp;
1028 }
1029
1030 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1031                                         const char *cid_name, const char *acctcode,
1032                                         const char *exten, const char *context,
1033                                         const char *linkedid, enum ama_flags amaflag,
1034                                         const char *file, int line, const char *function,
1035                                         const char *name_fmt, ...)
1036 {
1037         va_list ap;
1038         struct ast_channel *result;
1039
1040         va_start(ap, name_fmt);
1041         result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1042                                         linkedid, amaflag, file, line, function, name_fmt, ap);
1043         va_end(ap);
1044
1045         return result;
1046 }
1047
1048 /* only do the minimum amount of work needed here to make a channel
1049  * structure that can be used to expand channel vars */
1050 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1051 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1052 #else
1053 struct ast_channel *ast_dummy_channel_alloc(void)
1054 #endif
1055 {
1056         struct ast_channel *tmp;
1057         struct varshead *headp;
1058
1059         if (!(tmp = ast_channel_internal_alloc(ast_dummy_channel_destructor, NULL))) {
1060                 /* Dummy channel structure allocation failure. */
1061                 return NULL;
1062         }
1063
1064         ast_pbx_hangup_handler_init(tmp);
1065         AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1066
1067         /*
1068          * Init file descriptors to unopened state just in case
1069          * autoservice is called on the channel or something tries to
1070          * read a frame from it.
1071          */
1072         ast_channel_timingfd_set(tmp, -1);
1073         ast_channel_internal_alertpipe_clear(tmp);
1074         ast_channel_internal_fd_clear_all(tmp);
1075 #ifdef HAVE_EPOLL
1076         ast_channel_epfd_set(tmp, -1);
1077 #endif
1078
1079         ast_channel_hold_state_set(tmp, AST_CONTROL_UNHOLD);
1080
1081         ast_channel_internal_setup_topics(tmp);
1082
1083         headp = ast_channel_varshead(tmp);
1084         AST_LIST_HEAD_INIT_NOLOCK(headp);
1085
1086         return tmp;
1087 }
1088
1089 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1090 {
1091         struct ast_frame *f;
1092         struct ast_frame *cur;
1093         unsigned int new_frames = 0;
1094         unsigned int new_voice_frames = 0;
1095         unsigned int queued_frames = 0;
1096         unsigned int queued_voice_frames = 0;
1097         AST_LIST_HEAD_NOLOCK(,ast_frame) frames;
1098
1099         ast_channel_lock(chan);
1100
1101         /*
1102          * Check the last frame on the queue if we are queuing the new
1103          * frames after it.
1104          */
1105         cur = AST_LIST_LAST(ast_channel_readq(chan));
1106         if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1107                 switch (cur->subclass.integer) {
1108                 case AST_CONTROL_END_OF_Q:
1109                         if (fin->frametype == AST_FRAME_CONTROL
1110                                 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1111                                 /*
1112                                  * Destroy the end-of-Q marker frame so we can queue the hangup
1113                                  * frame in its place.
1114                                  */
1115                                 AST_LIST_REMOVE(ast_channel_readq(chan), cur, frame_list);
1116                                 ast_frfree(cur);
1117
1118                                 /*
1119                                  * This has degenerated to a normal queue append anyway.  Since
1120                                  * we just destroyed the last frame in the queue we must make
1121                                  * sure that "after" is NULL or bad things will happen.
1122                                  */
1123                                 after = NULL;
1124                                 break;
1125                         }
1126                         /* Fall through */
1127                 case AST_CONTROL_HANGUP:
1128                         /* Don't queue anything. */
1129                         ast_channel_unlock(chan);
1130                         return 0;
1131                 default:
1132                         break;
1133                 }
1134         }
1135
1136         /* Build copies of all the new frames and count them */
1137         AST_LIST_HEAD_INIT_NOLOCK(&frames);
1138         for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1139                 if (!(f = ast_frdup(cur))) {
1140                         if (AST_LIST_FIRST(&frames)) {
1141                                 ast_frfree(AST_LIST_FIRST(&frames));
1142                         }
1143                         ast_channel_unlock(chan);
1144                         return -1;
1145                 }
1146
1147                 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1148                 new_frames++;
1149                 if (f->frametype == AST_FRAME_VOICE) {
1150                         new_voice_frames++;
1151                 }
1152         }
1153
1154         /* Count how many frames exist on the queue */
1155         AST_LIST_TRAVERSE(ast_channel_readq(chan), cur, frame_list) {
1156                 queued_frames++;
1157                 if (cur->frametype == AST_FRAME_VOICE) {
1158                         queued_voice_frames++;
1159                 }
1160         }
1161
1162         if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1163                 int count = 0;
1164                 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1165                 AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), cur, frame_list) {
1166                         /* Save the most recent frame */
1167                         if (!AST_LIST_NEXT(cur, frame_list)) {
1168                                 break;
1169                         } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1170                                 if (++count > 64) {
1171                                         break;
1172                                 }
1173                                 AST_LIST_REMOVE_CURRENT(frame_list);
1174                                 ast_frfree(cur);
1175                         }
1176                 }
1177                 AST_LIST_TRAVERSE_SAFE_END;
1178         }
1179
1180         if (after) {
1181                 AST_LIST_INSERT_LIST_AFTER(ast_channel_readq(chan), &frames, after, frame_list);
1182         } else {
1183                 if (head) {
1184                         AST_LIST_APPEND_LIST(&frames, ast_channel_readq(chan), frame_list);
1185                         AST_LIST_HEAD_INIT_NOLOCK(ast_channel_readq(chan));
1186                 }
1187                 AST_LIST_APPEND_LIST(ast_channel_readq(chan), &frames, frame_list);
1188         }
1189
1190         if (ast_channel_alert_writable(chan)) {
1191                 if (ast_channel_alert_write(chan)) {
1192                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1193                                 ast_channel_name(chan), queued_frames, strerror(errno));
1194                 }
1195         } else if (ast_channel_timingfd(chan) > -1) {
1196                 ast_timer_enable_continuous(ast_channel_timer(chan));
1197         } else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
1198                 pthread_kill(ast_channel_blocker(chan), SIGURG);
1199         }
1200
1201         ast_channel_unlock(chan);
1202
1203         return 0;
1204 }
1205
1206 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1207 {
1208         return __ast_queue_frame(chan, fin, 0, NULL);
1209 }
1210
1211 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1212 {
1213         return __ast_queue_frame(chan, fin, 1, NULL);
1214 }
1215
1216 /*! \brief Queue a hangup frame for channel */
1217 int ast_queue_hangup(struct ast_channel *chan)
1218 {
1219         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1220         int res;
1221
1222         /* Yeah, let's not change a lock-critical value without locking */
1223         ast_channel_lock(chan);
1224         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1225         ast_channel_publish_blob(chan, ast_channel_hangup_request_type(), NULL);
1226
1227         res = ast_queue_frame(chan, &f);
1228         ast_channel_unlock(chan);
1229         return res;
1230 }
1231
1232 /*! \brief Queue a hangup frame for channel */
1233 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1234 {
1235         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
1236         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1237         int res;
1238
1239         if (cause >= 0) {
1240                 f.data.uint32 = cause;
1241         }
1242
1243         /* Yeah, let's not change a lock-critical value without locking */
1244         ast_channel_lock(chan);
1245         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1246         if (cause < 0) {
1247                 f.data.uint32 = ast_channel_hangupcause(chan);
1248         }
1249         blob = ast_json_pack("{s: i}",
1250                              "cause", cause);
1251         ast_channel_publish_blob(chan, ast_channel_hangup_request_type(), blob);
1252
1253         res = ast_queue_frame(chan, &f);
1254         ast_channel_unlock(chan);
1255         return res;
1256 }
1257
1258 int ast_queue_hold(struct ast_channel *chan, const char *musicclass)
1259 {
1260         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
1261         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HOLD };
1262         int res;
1263
1264         if (!ast_strlen_zero(musicclass)) {
1265                 f.data.ptr = (void *) musicclass;
1266                 f.datalen = strlen(musicclass) + 1;
1267
1268                 blob = ast_json_pack("{s: s}",
1269                                      "musicclass", musicclass);
1270         }
1271
1272         ast_channel_publish_blob(chan, ast_channel_hold_type(), blob);
1273
1274         res = ast_queue_frame(chan, &f);
1275         return res;
1276 }
1277
1278 int ast_queue_unhold(struct ast_channel *chan)
1279 {
1280         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_UNHOLD };
1281         int res;
1282
1283         ast_channel_publish_blob(chan, ast_channel_unhold_type(), NULL);
1284
1285         res = ast_queue_frame(chan, &f);
1286         return res;
1287 }
1288
1289 /*! \brief Queue a control frame */
1290 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1291 {
1292         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1293         return ast_queue_frame(chan, &f);
1294 }
1295
1296 /*! \brief Queue a control frame with payload */
1297 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1298                            const void *data, size_t datalen)
1299 {
1300         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1301         return ast_queue_frame(chan, &f);
1302 }
1303
1304 /*! \brief Set defer DTMF flag on channel */
1305 int ast_channel_defer_dtmf(struct ast_channel *chan)
1306 {
1307         int pre = 0;
1308
1309         if (chan) {
1310                 pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1311                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1312         }
1313         return pre;
1314 }
1315
1316 /*! \brief Unset defer DTMF flag on channel */
1317 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1318 {
1319         if (chan)
1320                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1321 }
1322
1323 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1324                 void *data, int ao2_flags)
1325 {
1326         return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1327 }
1328
1329 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1330 {
1331         struct ast_channel *chan = obj;
1332         const char *name = arg;
1333         size_t name_len = *(size_t *) data;
1334         int ret = CMP_MATCH;
1335
1336         if (ast_strlen_zero(name)) {
1337                 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1338                 return CMP_STOP;
1339         }
1340
1341         ast_channel_lock(chan);
1342         if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1343                 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1344                 ret = 0; /* name match failed, keep looking */
1345         }
1346         ast_channel_unlock(chan);
1347
1348         return ret;
1349 }
1350
1351 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1352 {
1353         struct ast_channel *chan = obj;
1354         char *context = arg;
1355         char *exten = data;
1356         int ret = CMP_MATCH;
1357
1358         if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1359                 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1360                 return CMP_STOP;
1361         }
1362
1363         ast_channel_lock(chan);
1364         if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1365                 ret = 0; /* Context match failed, continue */
1366         } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1367                 ret = 0; /* Extension match failed, continue */
1368         }
1369         ast_channel_unlock(chan);
1370
1371         return ret;
1372 }
1373
1374 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1375 {
1376         struct ast_channel *chan = obj;
1377         char *uniqueid = arg;
1378         size_t id_len = *(size_t *) data;
1379         int ret = CMP_MATCH;
1380
1381         if (ast_strlen_zero(uniqueid)) {
1382                 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1383                 return CMP_STOP;
1384         }
1385
1386         ast_channel_lock(chan);
1387         if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1388                 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1389                 ret = 0; /* uniqueid match failed, keep looking */
1390         }
1391         ast_channel_unlock(chan);
1392
1393         return ret;
1394 }
1395
1396 struct ast_channel_iterator {
1397         /* storage for non-dynamically allocated iterator */
1398         struct ao2_iterator simple_iterator;
1399         /* pointer to the actual iterator (simple_iterator or a dynamically
1400          * allocated iterator)
1401          */
1402         struct ao2_iterator *active_iterator;
1403 };
1404
1405 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1406 {
1407         ao2_iterator_destroy(i->active_iterator);
1408         ast_free(i);
1409
1410         return NULL;
1411 }
1412
1413 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1414 {
1415         struct ast_channel_iterator *i;
1416         char *l_exten = (char *) exten;
1417         char *l_context = (char *) context;
1418
1419         if (!(i = ast_calloc(1, sizeof(*i)))) {
1420                 return NULL;
1421         }
1422
1423         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1424                 l_context, l_exten, OBJ_MULTIPLE);
1425         if (!i->active_iterator) {
1426                 ast_free(i);
1427                 return NULL;
1428         }
1429
1430         return i;
1431 }
1432
1433 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1434 {
1435         struct ast_channel_iterator *i;
1436         char *l_name = (char *) name;
1437
1438         if (!(i = ast_calloc(1, sizeof(*i)))) {
1439                 return NULL;
1440         }
1441
1442         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1443                 l_name, &name_len,
1444                 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1445         if (!i->active_iterator) {
1446                 ast_free(i);
1447                 return NULL;
1448         }
1449
1450         return i;
1451 }
1452
1453 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1454 {
1455         struct ast_channel_iterator *i;
1456
1457         if (!(i = ast_calloc(1, sizeof(*i)))) {
1458                 return NULL;
1459         }
1460
1461         i->simple_iterator = ao2_iterator_init(channels, 0);
1462         i->active_iterator = &i->simple_iterator;
1463
1464         return i;
1465 }
1466
1467 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1468 {
1469         return ao2_iterator_next(i->active_iterator);
1470 }
1471
1472 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1473 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1474 {
1475         ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1476         return CMP_STOP;
1477 }
1478
1479 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1480 {
1481         struct ast_channel *chan;
1482         char *l_name = (char *) name;
1483
1484         chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1485                 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1486         if (chan) {
1487                 return chan;
1488         }
1489
1490         if (ast_strlen_zero(l_name)) {
1491                 /* We didn't have a name to search for so quit. */
1492                 return NULL;
1493         }
1494
1495         /* Now try a search for uniqueid. */
1496         return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1497 }
1498
1499 struct ast_channel *ast_channel_get_by_name(const char *name)
1500 {
1501         return ast_channel_get_by_name_prefix(name, 0);
1502 }
1503
1504 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1505 {
1506         char *l_exten = (char *) exten;
1507         char *l_context = (char *) context;
1508
1509         return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1510 }
1511
1512 int ast_is_deferrable_frame(const struct ast_frame *frame)
1513 {
1514         /* Do not add a default entry in this switch statement.  Each new
1515          * frame type should be addressed directly as to whether it should
1516          * be queued up or not.
1517          */
1518         switch (frame->frametype) {
1519         case AST_FRAME_BRIDGE_ACTION:
1520         case AST_FRAME_CONTROL:
1521         case AST_FRAME_TEXT:
1522         case AST_FRAME_IMAGE:
1523         case AST_FRAME_HTML:
1524                 return 1;
1525
1526         case AST_FRAME_DTMF_END:
1527         case AST_FRAME_DTMF_BEGIN:
1528         case AST_FRAME_VOICE:
1529         case AST_FRAME_VIDEO:
1530         case AST_FRAME_NULL:
1531         case AST_FRAME_IAX:
1532         case AST_FRAME_CNG:
1533         case AST_FRAME_MODEM:
1534                 return 0;
1535         }
1536         return 0;
1537 }
1538
1539 /*! \brief Wait, look for hangups and condition arg */
1540 int ast_safe_sleep_conditional(struct ast_channel *chan, int timeout_ms, int (*cond)(void*), void *data)
1541 {
1542         struct ast_frame *f;
1543         struct ast_silence_generator *silgen = NULL;
1544         int res = 0;
1545         struct timeval start;
1546         int ms;
1547         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1548
1549         AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1550
1551         /* If no other generator is present, start silencegen while waiting */
1552         if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1553                 silgen = ast_channel_start_silence_generator(chan);
1554         }
1555
1556         start = ast_tvnow();
1557         while ((ms = ast_remaining_ms(start, timeout_ms))) {
1558                 struct ast_frame *dup_f = NULL;
1559
1560                 if (cond && ((*cond)(data) == 0)) {
1561                         break;
1562                 }
1563                 ms = ast_waitfor(chan, ms);
1564                 if (ms < 0) {
1565                         res = -1;
1566                         break;
1567                 }
1568                 if (ms > 0) {
1569                         f = ast_read(chan);
1570                         if (!f) {
1571                                 res = -1;
1572                                 break;
1573                         }
1574
1575                         if (!ast_is_deferrable_frame(f)) {
1576                                 ast_frfree(f);
1577                                 continue;
1578                         }
1579
1580                         if ((dup_f = ast_frisolate(f))) {
1581                                 if (dup_f != f) {
1582                                         ast_frfree(f);
1583                                 }
1584                                 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1585                         }
1586                 }
1587         }
1588
1589         /* stop silgen if present */
1590         if (silgen) {
1591                 ast_channel_stop_silence_generator(chan, silgen);
1592         }
1593
1594         /* We need to free all the deferred frames, but we only need to
1595          * queue the deferred frames if there was no error and no
1596          * hangup was received
1597          */
1598         ast_channel_lock(chan);
1599         while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1600                 if (!res) {
1601                         ast_queue_frame_head(chan, f);
1602                 }
1603                 ast_frfree(f);
1604         }
1605         ast_channel_unlock(chan);
1606
1607         return res;
1608 }
1609
1610 /*! \brief Wait, look for hangups */
1611 int ast_safe_sleep(struct ast_channel *chan, int ms)
1612 {
1613         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1614 }
1615
1616 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1617 {
1618         /* Safe, even if already unlinked. */
1619         ao2_unlink(channels, chan);
1620         return ast_channel_unref(chan);
1621 }
1622
1623 void ast_party_name_init(struct ast_party_name *init)
1624 {
1625         init->str = NULL;
1626         init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1627         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1628         init->valid = 0;
1629 }
1630
1631 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1632 {
1633         if (dest == src) {
1634                 /* Don't copy to self */
1635                 return;
1636         }
1637
1638         ast_free(dest->str);
1639         dest->str = ast_strdup(src->str);
1640         dest->char_set = src->char_set;
1641         dest->presentation = src->presentation;
1642         dest->valid = src->valid;
1643 }
1644
1645 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1646 {
1647         init->str = NULL;
1648         init->char_set = guide->char_set;
1649         init->presentation = guide->presentation;
1650         init->valid = guide->valid;
1651 }
1652
1653 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1654 {
1655         if (dest == src) {
1656                 /* Don't set to self */
1657                 return;
1658         }
1659
1660         if (src->str && src->str != dest->str) {
1661                 ast_free(dest->str);
1662                 dest->str = ast_strdup(src->str);
1663         }
1664
1665         dest->char_set = src->char_set;
1666         dest->presentation = src->presentation;
1667         dest->valid = src->valid;
1668 }
1669
1670 void ast_party_name_free(struct ast_party_name *doomed)
1671 {
1672         ast_free(doomed->str);
1673         doomed->str = NULL;
1674 }
1675
1676 void ast_party_number_init(struct ast_party_number *init)
1677 {
1678         init->str = NULL;
1679         init->plan = 0;/* Unknown */
1680         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1681         init->valid = 0;
1682 }
1683
1684 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1685 {
1686         if (dest == src) {
1687                 /* Don't copy to self */
1688                 return;
1689         }
1690
1691         ast_free(dest->str);
1692         dest->str = ast_strdup(src->str);
1693         dest->plan = src->plan;
1694         dest->presentation = src->presentation;
1695         dest->valid = src->valid;
1696 }
1697
1698 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1699 {
1700         init->str = NULL;
1701         init->plan = guide->plan;
1702         init->presentation = guide->presentation;
1703         init->valid = guide->valid;
1704 }
1705
1706 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1707 {
1708         if (dest == src) {
1709                 /* Don't set to self */
1710                 return;
1711         }
1712
1713         if (src->str && src->str != dest->str) {
1714                 ast_free(dest->str);
1715                 dest->str = ast_strdup(src->str);
1716         }
1717
1718         dest->plan = src->plan;
1719         dest->presentation = src->presentation;
1720         dest->valid = src->valid;
1721 }
1722
1723 void ast_party_number_free(struct ast_party_number *doomed)
1724 {
1725         ast_free(doomed->str);
1726         doomed->str = NULL;
1727 }
1728
1729 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1730 {
1731         init->str = NULL;
1732         init->type = 0;
1733         init->odd_even_indicator = 0;
1734         init->valid = 0;
1735 }
1736
1737 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1738 {
1739         if (dest == src) {
1740                 /* Don't copy to self */
1741                 return;
1742         }
1743
1744         ast_free(dest->str);
1745         dest->str = ast_strdup(src->str);
1746         dest->type = src->type;
1747         dest->odd_even_indicator = src->odd_even_indicator;
1748         dest->valid = src->valid;
1749 }
1750
1751 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1752 {
1753         init->str = NULL;
1754         init->type = guide->type;
1755         init->odd_even_indicator = guide->odd_even_indicator;
1756         init->valid = guide->valid;
1757 }
1758
1759 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1760 {
1761         if (dest == src) {
1762                 /* Don't set to self */
1763                 return;
1764         }
1765
1766         if (src->str && src->str != dest->str) {
1767                 ast_free(dest->str);
1768                 dest->str = ast_strdup(src->str);
1769         }
1770
1771         dest->type = src->type;
1772         dest->odd_even_indicator = src->odd_even_indicator;
1773         dest->valid = src->valid;
1774 }
1775
1776 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1777 {
1778         ast_free(doomed->str);
1779         doomed->str = NULL;
1780 }
1781
1782 void ast_set_party_id_all(struct ast_set_party_id *update_id)
1783 {
1784         update_id->name = 1;
1785         update_id->number = 1;
1786         update_id->subaddress = 1;
1787 }
1788
1789 void ast_party_id_init(struct ast_party_id *init)
1790 {
1791         ast_party_name_init(&init->name);
1792         ast_party_number_init(&init->number);
1793         ast_party_subaddress_init(&init->subaddress);
1794         init->tag = NULL;
1795 }
1796
1797 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1798 {
1799         if (dest == src) {
1800                 /* Don't copy to self */
1801                 return;
1802         }
1803
1804         ast_party_name_copy(&dest->name, &src->name);
1805         ast_party_number_copy(&dest->number, &src->number);
1806         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1807
1808         ast_free(dest->tag);
1809         dest->tag = ast_strdup(src->tag);
1810 }
1811
1812 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1813 {
1814         ast_party_name_set_init(&init->name, &guide->name);
1815         ast_party_number_set_init(&init->number, &guide->number);
1816         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1817         init->tag = NULL;
1818 }
1819
1820 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1821 {
1822         if (dest == src) {
1823                 /* Don't set to self */
1824                 return;
1825         }
1826
1827         if (!update || update->name) {
1828                 ast_party_name_set(&dest->name, &src->name);
1829         }
1830         if (!update || update->number) {
1831                 ast_party_number_set(&dest->number, &src->number);
1832         }
1833         if (!update || update->subaddress) {
1834                 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1835         }
1836
1837         if (src->tag && src->tag != dest->tag) {
1838                 ast_free(dest->tag);
1839                 dest->tag = ast_strdup(src->tag);
1840         }
1841 }
1842
1843 void ast_party_id_free(struct ast_party_id *doomed)
1844 {
1845         ast_party_name_free(&doomed->name);
1846         ast_party_number_free(&doomed->number);
1847         ast_party_subaddress_free(&doomed->subaddress);
1848
1849         ast_free(doomed->tag);
1850         doomed->tag = NULL;
1851 }
1852
1853 int ast_party_id_presentation(const struct ast_party_id *id)
1854 {
1855         int number_priority;
1856         int number_value;
1857         int number_screening;
1858         int name_priority;
1859         int name_value;
1860
1861         /* Determine name presentation priority. */
1862         if (!id->name.valid) {
1863                 name_value = AST_PRES_UNAVAILABLE;
1864                 name_priority = 3;
1865         } else {
1866                 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1867                 switch (name_value) {
1868                 case AST_PRES_RESTRICTED:
1869                         name_priority = 0;
1870                         break;
1871                 case AST_PRES_ALLOWED:
1872                         name_priority = 1;
1873                         break;
1874                 case AST_PRES_UNAVAILABLE:
1875                         name_priority = 2;
1876                         break;
1877                 default:
1878                         name_value = AST_PRES_UNAVAILABLE;
1879                         name_priority = 3;
1880                         break;
1881                 }
1882         }
1883
1884         /* Determine number presentation priority. */
1885         if (!id->number.valid) {
1886                 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1887                 number_value = AST_PRES_UNAVAILABLE;
1888                 number_priority = 3;
1889         } else {
1890                 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1891                 number_value = id->number.presentation & AST_PRES_RESTRICTION;
1892                 switch (number_value) {
1893                 case AST_PRES_RESTRICTED:
1894                         number_priority = 0;
1895                         break;
1896                 case AST_PRES_ALLOWED:
1897                         number_priority = 1;
1898                         break;
1899                 case AST_PRES_UNAVAILABLE:
1900                         number_priority = 2;
1901                         break;
1902                 default:
1903                         number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1904                         number_value = AST_PRES_UNAVAILABLE;
1905                         number_priority = 3;
1906                         break;
1907                 }
1908         }
1909
1910         /* Select the wining presentation value. */
1911         if (name_priority < number_priority) {
1912                 number_value = name_value;
1913         }
1914         if (number_value == AST_PRES_UNAVAILABLE) {
1915                 return AST_PRES_NUMBER_NOT_AVAILABLE;
1916         }
1917
1918         return number_value | number_screening;
1919 }
1920
1921 void ast_party_id_invalidate(struct ast_party_id *id)
1922 {
1923         id->name.valid = 0;
1924         id->number.valid = 0;
1925         id->subaddress.valid = 0;
1926 }
1927
1928 void ast_party_id_reset(struct ast_party_id *id)
1929 {
1930         ast_party_id_free(id);
1931         ast_party_id_init(id);
1932 }
1933
1934 struct ast_party_id ast_party_id_merge(struct ast_party_id *base, struct ast_party_id *overlay)
1935 {
1936         struct ast_party_id merged;
1937
1938         merged = *base;
1939         if (overlay->name.valid) {
1940                 merged.name = overlay->name;
1941         }
1942         if (overlay->number.valid) {
1943                 merged.number = overlay->number;
1944         }
1945         if (overlay->subaddress.valid) {
1946                 merged.subaddress = overlay->subaddress;
1947         }
1948         /* Note the actual structure is returned and not a pointer to it! */
1949         return merged;
1950 }
1951
1952 void ast_party_id_merge_copy(struct ast_party_id *dest, struct ast_party_id *base, struct ast_party_id *overlay)
1953 {
1954         struct ast_party_id merged;
1955
1956         merged = ast_party_id_merge(base, overlay);
1957         ast_party_id_copy(dest, &merged);
1958 }
1959
1960 void ast_party_dialed_init(struct ast_party_dialed *init)
1961 {
1962         init->number.str = NULL;
1963         init->number.plan = 0;/* Unknown */
1964         ast_party_subaddress_init(&init->subaddress);
1965         init->transit_network_select = 0;
1966 }
1967
1968 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1969 {
1970         if (dest == src) {
1971                 /* Don't copy to self */
1972                 return;
1973         }
1974
1975         ast_free(dest->number.str);
1976         dest->number.str = ast_strdup(src->number.str);
1977         dest->number.plan = src->number.plan;
1978         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1979         dest->transit_network_select = src->transit_network_select;
1980 }
1981
1982 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
1983 {
1984         init->number.str = NULL;
1985         init->number.plan = guide->number.plan;
1986         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1987         init->transit_network_select = guide->transit_network_select;
1988 }
1989
1990 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1991 {
1992         if (src->number.str && src->number.str != dest->number.str) {
1993                 ast_free(dest->number.str);
1994                 dest->number.str = ast_strdup(src->number.str);
1995         }
1996         dest->number.plan = src->number.plan;
1997
1998         ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1999
2000         dest->transit_network_select = src->transit_network_select;
2001 }
2002
2003 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2004 {
2005         ast_free(doomed->number.str);
2006         doomed->number.str = NULL;
2007         ast_party_subaddress_free(&doomed->subaddress);
2008 }
2009
2010 void ast_party_caller_init(struct ast_party_caller *init)
2011 {
2012         ast_party_id_init(&init->id);
2013         ast_party_id_init(&init->ani);
2014         ast_party_id_init(&init->priv);
2015         init->ani2 = 0;
2016 }
2017
2018 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2019 {
2020         if (dest == src) {
2021                 /* Don't copy to self */
2022                 return;
2023         }
2024
2025         ast_party_id_copy(&dest->id, &src->id);
2026         ast_party_id_copy(&dest->ani, &src->ani);
2027         ast_party_id_copy(&dest->priv, &src->priv);
2028         dest->ani2 = src->ani2;
2029 }
2030
2031 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2032 {
2033         ast_party_id_set_init(&init->id, &guide->id);
2034         ast_party_id_set_init(&init->ani, &guide->ani);
2035         ast_party_id_set_init(&init->priv, &guide->priv);
2036         init->ani2 = guide->ani2;
2037 }
2038
2039 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2040 {
2041         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2042         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2043         ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2044         dest->ani2 = src->ani2;
2045 }
2046
2047 void ast_party_caller_free(struct ast_party_caller *doomed)
2048 {
2049         ast_party_id_free(&doomed->id);
2050         ast_party_id_free(&doomed->ani);
2051         ast_party_id_free(&doomed->priv);
2052 }
2053
2054 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2055 {
2056         ast_party_id_init(&init->id);
2057         ast_party_id_init(&init->ani);
2058         ast_party_id_init(&init->priv);
2059         init->ani2 = 0;
2060         init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2061 }
2062
2063 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2064 {
2065         if (dest == src) {
2066                 /* Don't copy to self */
2067                 return;
2068         }
2069
2070         ast_party_id_copy(&dest->id, &src->id);
2071         ast_party_id_copy(&dest->ani, &src->ani);
2072         ast_party_id_copy(&dest->priv, &src->priv);
2073         dest->ani2 = src->ani2;
2074         dest->source = src->source;
2075 }
2076
2077 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2078 {
2079         ast_party_id_set_init(&init->id, &guide->id);
2080         ast_party_id_set_init(&init->ani, &guide->ani);
2081         ast_party_id_set_init(&init->priv, &guide->priv);
2082         init->ani2 = guide->ani2;
2083         init->source = guide->source;
2084 }
2085
2086 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)
2087 {
2088         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2089         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2090         ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2091         dest->ani2 = src->ani2;
2092         dest->source = src->source;
2093 }
2094
2095 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2096 {
2097         connected->id = caller->id;
2098         connected->ani = caller->ani;
2099         connected->priv = caller->priv;
2100         connected->ani2 = caller->ani2;
2101         connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2102 }
2103
2104 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2105 {
2106         ast_party_id_free(&doomed->id);
2107         ast_party_id_free(&doomed->ani);
2108         ast_party_id_free(&doomed->priv);
2109 }
2110
2111 void ast_party_redirecting_reason_init(struct ast_party_redirecting_reason *init)
2112 {
2113         init->str = NULL;
2114         init->code = AST_REDIRECTING_REASON_UNKNOWN;
2115 }
2116
2117 void ast_party_redirecting_reason_copy(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2118 {
2119         if (dest == src) {
2120                 return;
2121         }
2122
2123         ast_free(dest->str);
2124         dest->str = ast_strdup(src->str);
2125         dest->code = src->code;
2126 }
2127
2128 void ast_party_redirecting_reason_set_init(struct ast_party_redirecting_reason *init, const struct ast_party_redirecting_reason *guide)
2129 {
2130         init->str = NULL;
2131         init->code = guide->code;
2132 }
2133
2134 void ast_party_redirecting_reason_set(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2135 {
2136         if (dest == src) {
2137                 return;
2138         }
2139
2140         if (src->str && src->str != dest->str) {
2141                 ast_free(dest->str);
2142                 dest->str = ast_strdup(src->str);
2143         }
2144
2145         dest->code = src->code;
2146 }
2147
2148 void ast_party_redirecting_reason_free(struct ast_party_redirecting_reason *doomed)
2149 {
2150         ast_free(doomed->str);
2151 }
2152
2153
2154 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2155 {
2156         ast_party_id_init(&init->orig);
2157         ast_party_id_init(&init->from);
2158         ast_party_id_init(&init->to);
2159         ast_party_id_init(&init->priv_orig);
2160         ast_party_id_init(&init->priv_from);
2161         ast_party_id_init(&init->priv_to);
2162         ast_party_redirecting_reason_init(&init->reason);
2163         ast_party_redirecting_reason_init(&init->orig_reason);
2164         init->count = 0;
2165 }
2166
2167 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2168 {
2169         if (dest == src) {
2170                 /* Don't copy to self */
2171                 return;
2172         }
2173
2174         ast_party_id_copy(&dest->orig, &src->orig);
2175         ast_party_id_copy(&dest->from, &src->from);
2176         ast_party_id_copy(&dest->to, &src->to);
2177         ast_party_id_copy(&dest->priv_orig, &src->priv_orig);
2178         ast_party_id_copy(&dest->priv_from, &src->priv_from);
2179         ast_party_id_copy(&dest->priv_to, &src->priv_to);
2180         ast_party_redirecting_reason_copy(&dest->reason, &src->reason);
2181         ast_party_redirecting_reason_copy(&dest->orig_reason, &src->orig_reason);
2182         dest->count = src->count;
2183 }
2184
2185 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2186 {
2187         ast_party_id_set_init(&init->orig, &guide->orig);
2188         ast_party_id_set_init(&init->from, &guide->from);
2189         ast_party_id_set_init(&init->to, &guide->to);
2190         ast_party_id_set_init(&init->priv_orig, &guide->priv_orig);
2191         ast_party_id_set_init(&init->priv_from, &guide->priv_from);
2192         ast_party_id_set_init(&init->priv_to, &guide->priv_to);
2193         ast_party_redirecting_reason_set_init(&init->reason, &guide->reason);
2194         ast_party_redirecting_reason_set_init(&init->orig_reason, &guide->orig_reason);
2195         init->count = guide->count;
2196 }
2197
2198 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2199 {
2200         ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2201         ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2202         ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2203         ast_party_id_set(&dest->priv_orig, &src->priv_orig, update ? &update->priv_orig : NULL);
2204         ast_party_id_set(&dest->priv_from, &src->priv_from, update ? &update->priv_from : NULL);
2205         ast_party_id_set(&dest->priv_to, &src->priv_to, update ? &update->priv_to : NULL);
2206         ast_party_redirecting_reason_set(&dest->reason, &src->reason);
2207         ast_party_redirecting_reason_set(&dest->orig_reason, &src->orig_reason);
2208         dest->count = src->count;
2209 }
2210
2211 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2212 {
2213         ast_party_id_free(&doomed->orig);
2214         ast_party_id_free(&doomed->from);
2215         ast_party_id_free(&doomed->to);
2216         ast_party_id_free(&doomed->priv_orig);
2217         ast_party_id_free(&doomed->priv_from);
2218         ast_party_id_free(&doomed->priv_to);
2219         ast_party_redirecting_reason_free(&doomed->reason);
2220         ast_party_redirecting_reason_free(&doomed->orig_reason);
2221 }
2222
2223 /*! \brief Free a channel structure */
2224 static void ast_channel_destructor(void *obj)
2225 {
2226         struct ast_channel *chan = obj;
2227 #ifdef HAVE_EPOLL
2228         int i;
2229 #endif
2230         struct ast_var_t *vardata;
2231         struct ast_frame *f;
2232         struct varshead *headp;
2233         struct ast_datastore *datastore;
2234         char device_name[AST_CHANNEL_NAME];
2235         struct ast_callid *callid;
2236
2237         /* Stop monitoring */
2238         if (ast_channel_monitor(chan)) {
2239                 ast_channel_monitor(chan)->stop(chan, 0);
2240         }
2241
2242         /* If there is native format music-on-hold state, free it */
2243         if (ast_channel_music_state(chan)) {
2244                 ast_moh_cleanup(chan);
2245         }
2246
2247         ast_pbx_hangup_handler_destroy(chan);
2248
2249         /* Things that may possibly raise Stasis messages shouldn't occur after this point */
2250         ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEAD);
2251         ast_channel_publish_snapshot(chan);
2252         publish_cache_clear(chan);
2253
2254         ast_channel_lock(chan);
2255
2256         /* Get rid of each of the data stores on the channel */
2257         while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2258                 /* Free the data store */
2259                 ast_datastore_free(datastore);
2260
2261         /* While the channel is locked, take the reference to its callid while we tear down the call. */
2262         callid = ast_channel_callid(chan);
2263         ast_channel_callid_cleanup(chan);
2264
2265         ast_channel_unlock(chan);
2266
2267         /* Lock and unlock the channel just to be sure nobody has it locked still
2268            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2269         ast_channel_lock(chan);
2270         ast_channel_unlock(chan);
2271
2272         if (ast_channel_tech_pvt(chan)) {
2273                 ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2274                 ast_free(ast_channel_tech_pvt(chan));
2275         }
2276
2277         if (ast_channel_sched(chan)) {
2278                 ast_sched_context_destroy(ast_channel_sched(chan));
2279         }
2280
2281         if (ast_channel_internal_is_finalized(chan)) {
2282                 char *dashptr;
2283
2284                 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2285                 if ((dashptr = strrchr(device_name, '-'))) {
2286                         *dashptr = '\0';
2287                 }
2288         } else {
2289                 device_name[0] = '\0';
2290         }
2291
2292         /* Free translators */
2293         if (ast_channel_readtrans(chan))
2294                 ast_translator_free_path(ast_channel_readtrans(chan));
2295         if (ast_channel_writetrans(chan))
2296                 ast_translator_free_path(ast_channel_writetrans(chan));
2297         if (ast_channel_pbx(chan))
2298                 ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2299
2300         ast_party_dialed_free(ast_channel_dialed(chan));
2301         ast_party_caller_free(ast_channel_caller(chan));
2302         ast_party_connected_line_free(ast_channel_connected(chan));
2303         ast_party_connected_line_free(ast_channel_connected_indicated(chan));
2304         ast_party_redirecting_free(ast_channel_redirecting(chan));
2305
2306         /* Close pipes if appropriate */
2307         ast_channel_internal_alertpipe_close(chan);
2308         if (ast_channel_timer(chan)) {
2309                 ast_timer_close(ast_channel_timer(chan));
2310                 ast_channel_timer_set(chan, NULL);
2311         }
2312 #ifdef HAVE_EPOLL
2313         for (i = 0; i < AST_MAX_FDS; i++) {
2314                 if (ast_channel_internal_epfd_data(chan, i)) {
2315                         ast_free(ast_channel_internal_epfd_data(chan, i));
2316                 }
2317         }
2318         close(ast_channel_epfd(chan));
2319 #endif
2320         while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2321                 ast_frfree(f);
2322
2323         /* loop over the variables list, freeing all data and deleting list items */
2324         /* no need to lock the list, as the channel is already locked */
2325         headp = ast_channel_varshead(chan);
2326         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2327                 ast_var_delete(vardata);
2328
2329         ast_app_group_discard(chan);
2330
2331         /* Destroy the jitterbuffer */
2332         ast_jb_destroy(chan);
2333
2334         if (ast_channel_cdr(chan)) {
2335                 ast_cdr_free(ast_channel_cdr(chan));
2336                 ast_channel_cdr_set(chan, NULL);
2337         }
2338
2339         if (ast_channel_zone(chan)) {
2340                 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2341         }
2342
2343         ast_channel_internal_cleanup(chan);
2344
2345         if (device_name[0]) {
2346                 /*
2347                  * We have a device name to notify of a new state.
2348                  *
2349                  * Queue an unknown state, because, while we know that this particular
2350                  * instance is dead, we don't know the state of all other possible
2351                  * instances.
2352                  */
2353                 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);
2354         }
2355
2356         ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2357         if (callid) {
2358                 ast_callid_unref(callid);
2359         }
2360
2361         ast_channel_named_callgroups_set(chan, NULL);
2362         ast_channel_named_pickupgroups_set(chan, NULL);
2363
2364         ast_atomic_fetchadd_int(&chancount, -1);
2365 }
2366
2367 /*! \brief Free a dummy channel structure */
2368 static void ast_dummy_channel_destructor(void *obj)
2369 {
2370         struct ast_channel *chan = obj;
2371         struct ast_datastore *datastore;
2372         struct ast_var_t *vardata;
2373         struct varshead *headp;
2374
2375         ast_pbx_hangup_handler_destroy(chan);
2376
2377         /* Get rid of each of the data stores on the channel */
2378         while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
2379                 /* Free the data store */
2380                 ast_datastore_free(datastore);
2381         }
2382
2383         ast_party_dialed_free(ast_channel_dialed(chan));
2384         ast_party_caller_free(ast_channel_caller(chan));
2385         ast_party_connected_line_free(ast_channel_connected(chan));
2386         ast_party_connected_line_free(ast_channel_connected_indicated(chan));
2387         ast_party_redirecting_free(ast_channel_redirecting(chan));
2388
2389         /* loop over the variables list, freeing all data and deleting list items */
2390         /* no need to lock the list, as the channel is already locked */
2391         headp = ast_channel_varshead(chan);
2392         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2393                 ast_var_delete(vardata);
2394
2395         if (ast_channel_cdr(chan)) {
2396                 ast_cdr_free(ast_channel_cdr(chan));
2397                 ast_channel_cdr_set(chan, NULL);
2398         }
2399
2400         ast_channel_internal_cleanup(chan);
2401 }
2402
2403 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2404 {
2405         return ast_datastore_alloc(info, uid);
2406 }
2407
2408 int ast_channel_datastore_free(struct ast_datastore *datastore)
2409 {
2410         return ast_datastore_free(datastore);
2411 }
2412
2413 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2414 {
2415         struct ast_datastore *datastore = NULL, *datastore2;
2416
2417         AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2418                 if (datastore->inheritance > 0) {
2419                         datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2420                         if (datastore2) {
2421                                 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2422                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2423                                 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2424                         }
2425                 }
2426         }
2427         return 0;
2428 }
2429
2430 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2431 {
2432         int res = 0;
2433
2434         AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2435
2436         return res;
2437 }
2438
2439 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2440 {
2441         return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2442 }
2443
2444 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2445 {
2446         struct ast_datastore *datastore = NULL;
2447
2448         if (info == NULL)
2449                 return NULL;
2450
2451         AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2452                 if (datastore->info != info) {
2453                         continue;
2454                 }
2455
2456                 if (uid == NULL) {
2457                         /* matched by type only */
2458                         break;
2459                 }
2460
2461                 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2462                         /* Matched by type AND uid */
2463                         break;
2464                 }
2465         }
2466
2467         return datastore;
2468 }
2469
2470 /*! Set the file descriptor on the channel */
2471 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2472 {
2473 #ifdef HAVE_EPOLL
2474         struct epoll_event ev;
2475         struct ast_epoll_data *aed = NULL;
2476
2477         if (ast_channel_fd_isset(chan, which)) {
2478                 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2479                 aed = ast_channel_internal_epfd_data(chan, which);
2480         }
2481
2482         /* If this new fd is valid, add it to the epoll */
2483         if (fd > -1) {
2484                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2485                         return;
2486
2487                 ast_channel_internal_epfd_data_set(chan, which, aed);
2488                 aed->chan = chan;
2489                 aed->which = which;
2490
2491                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2492                 ev.data.ptr = aed;
2493                 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2494         } else if (aed) {
2495                 /* We don't have to keep around this epoll data structure now */
2496                 ast_free(aed);
2497                 ast_channel_epfd_data_set(chan, which, NULL);
2498         }
2499 #endif
2500         ast_channel_internal_fd_set(chan, which, fd);
2501         return;
2502 }
2503
2504 /*! Add a channel to an optimized waitfor */
2505 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2506 {
2507 #ifdef HAVE_EPOLL
2508         struct epoll_event ev;
2509         int i = 0;
2510
2511         if (ast_channel_epfd(chan0) == -1)
2512                 return;
2513
2514         /* Iterate through the file descriptors on chan1, adding them to chan0 */
2515         for (i = 0; i < AST_MAX_FDS; i++) {
2516                 if (!ast_channel_fd_isset(chan1, i)) {
2517                         continue;
2518                 }
2519                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2520                 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2521                 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2522         }
2523
2524 #endif
2525         return;
2526 }
2527
2528 /*! Delete a channel from an optimized waitfor */
2529 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2530 {
2531 #ifdef HAVE_EPOLL
2532         struct epoll_event ev;
2533         int i = 0;
2534
2535         if (ast_channel_epfd(chan0) == -1)
2536                 return;
2537
2538         for (i = 0; i < AST_MAX_FDS; i++) {
2539                 if (!ast_channel_fd_isset(chan1, i)) {
2540                         continue;
2541                 }
2542                 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2543         }
2544
2545 #endif
2546         return;
2547 }
2548
2549 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2550 {
2551         ast_channel_lock(chan);
2552
2553         ast_channel_softhangup_internal_flag_clear(chan, flag);
2554
2555         if (!ast_channel_softhangup_internal_flag(chan)) {
2556                 struct ast_frame *fr;
2557
2558                 /* If we have completely cleared the softhangup flag,
2559                  * then we need to fully abort the hangup process.  This requires
2560                  * pulling the END_OF_Q frame out of the channel frame queue if it
2561                  * still happens to be there. */
2562
2563                 fr = AST_LIST_LAST(ast_channel_readq(chan));
2564                 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2565                                 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2566                         AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2567                         ast_frfree(fr);
2568                 }
2569         }
2570
2571         ast_channel_unlock(chan);
2572 }
2573
2574 /*! \brief Softly hangup a channel, don't lock */
2575 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2576 {
2577         ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2578         /* Inform channel driver that we need to be hung up, if it cares */
2579         ast_channel_softhangup_internal_flag_add(chan, cause);
2580         ast_queue_frame(chan, &ast_null_frame);
2581         /* Interrupt any poll call or such */
2582         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2583                 pthread_kill(ast_channel_blocker(chan), SIGURG);
2584         return 0;
2585 }
2586
2587 /*! \brief Softly hangup a channel, lock */
2588 int ast_softhangup(struct ast_channel *chan, int cause)
2589 {
2590         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
2591         int res;
2592
2593         ast_channel_lock(chan);
2594         res = ast_softhangup_nolock(chan, cause);
2595         blob = ast_json_pack("{s: i, s: b}",
2596                              "cause", cause,
2597                              "soft", 1);
2598         ast_channel_publish_blob(chan, ast_channel_hangup_request_type(), blob);
2599         ast_channel_unlock(chan);
2600
2601         return res;
2602 }
2603
2604 static void free_translation(struct ast_channel *clonechan)
2605 {
2606         if (ast_channel_writetrans(clonechan))
2607                 ast_translator_free_path(ast_channel_writetrans(clonechan));
2608         if (ast_channel_readtrans(clonechan))
2609                 ast_translator_free_path(ast_channel_readtrans(clonechan));
2610         ast_channel_writetrans_set(clonechan, NULL);
2611         ast_channel_readtrans_set(clonechan, NULL);
2612         if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2613                 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2614                 ast_format_clear(ast_channel_rawreadformat(clonechan));
2615         } else {
2616                 struct ast_format tmpfmt;
2617                 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2618                 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2619                 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2620         }
2621 }
2622
2623 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2624 {
2625         RAII_VAR(struct ast_channel *, bridge, ast_channel_bridge_peer(chan), ast_channel_cleanup);
2626
2627         ast_channel_lock(chan);
2628         if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2629                 ast_channel_hangupsource_set(chan, source);
2630         }
2631         ast_channel_unlock(chan);
2632
2633         if (bridge) {
2634                 ast_channel_lock(bridge);
2635                 if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
2636                         ast_channel_hangupsource_set(bridge, source);
2637                 }
2638                 ast_channel_unlock(bridge);
2639         }
2640 }
2641
2642 int ast_channel_has_audio_frame_or_monitor(struct ast_channel *chan)
2643 {
2644         return ast_channel_monitor(chan)
2645                 || !ast_audiohook_write_list_empty(ast_channel_audiohooks(chan))
2646                 || !ast_framehook_list_contains_no_active(ast_channel_framehooks(chan));
2647 }
2648
2649 static void destroy_hooks(struct ast_channel *chan)
2650 {
2651         if (ast_channel_audiohooks(chan)) {
2652                 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2653                 ast_channel_audiohooks_set(chan, NULL);
2654         }
2655
2656         ast_framehook_list_destroy(chan);
2657 }
2658
2659 /*! \brief Hangup a channel */
2660 void ast_hangup(struct ast_channel *chan)
2661 {
2662         /* Be NULL safe for RAII_VAR() usage. */
2663         if (!chan) {
2664                 return;
2665         }
2666
2667         ast_autoservice_stop(chan);
2668
2669         ast_channel_lock(chan);
2670
2671         /*
2672          * Do the masquerade if someone is setup to masquerade into us.
2673          *
2674          * NOTE: We must hold the channel lock after testing for a
2675          * pending masquerade and setting the channel as a zombie to
2676          * prevent ast_channel_masquerade() from setting up a
2677          * masquerade with a dead channel.
2678          */
2679         while (ast_channel_masq(chan)) {
2680                 ast_channel_unlock(chan);
2681                 ast_do_masquerade(chan);
2682                 ast_channel_lock(chan);
2683         }
2684
2685         if (ast_channel_masqr(chan)) {
2686                 /*
2687                  * This channel is one which will be masqueraded into something.
2688                  * Mark it as a zombie already so ast_do_masquerade() will know
2689                  * to free it later.
2690                  */
2691                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2692                 destroy_hooks(chan);
2693                 ast_channel_unlock(chan);
2694                 return;
2695         }
2696
2697         /* Mark as a zombie so a masquerade cannot be setup on this channel. */
2698         ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2699
2700         ast_channel_unlock(chan);
2701
2702         /*
2703          * XXX if running the hangup handlers here causes problems
2704          * because the handlers take too long to execute, we could move
2705          * the meat of this function into another thread.  A thread
2706          * where channels go to die.
2707          *
2708          * If this is done, ast_autoservice_chan_hangup_peer() will no
2709          * longer be needed.
2710          */
2711         ast_pbx_hangup_handler_run(chan);
2712         ao2_unlink(channels, chan);
2713         ast_channel_lock(chan);
2714
2715         destroy_hooks(chan);
2716
2717         free_translation(chan);
2718         /* Close audio stream */
2719         if (ast_channel_stream(chan)) {
2720                 ast_closestream(ast_channel_stream(chan));
2721                 ast_channel_stream_set(chan, NULL);
2722         }
2723         /* Close video stream */
2724         if (ast_channel_vstream(chan)) {
2725                 ast_closestream(ast_channel_vstream(chan));
2726                 ast_channel_vstream_set(chan, NULL);
2727         }
2728         if (ast_channel_sched(chan)) {
2729                 ast_sched_context_destroy(ast_channel_sched(chan));
2730                 ast_channel_sched_set(chan, NULL);
2731         }
2732
2733         if (ast_channel_generatordata(chan)) {  /* Clear any tone stuff remaining */
2734                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2735                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2736                 }
2737         }
2738         ast_channel_generatordata_set(chan, NULL);
2739         ast_channel_generator_set(chan, NULL);
2740
2741         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2742                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2743                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
2744                         (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2745                 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2746         }
2747
2748         ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2749         if (ast_channel_tech(chan)->hangup) {
2750                 ast_channel_tech(chan)->hangup(chan);
2751         }
2752
2753         ast_channel_unlock(chan);
2754
2755         ast_cc_offer(chan);
2756
2757         ast_channel_unref(chan);
2758 }
2759
2760 int ast_raw_answer(struct ast_channel *chan)
2761 {
2762         int res = 0;
2763         struct timeval answertime;
2764
2765         ast_channel_lock(chan);
2766
2767         /* You can't answer an outbound call */
2768         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2769                 ast_channel_unlock(chan);
2770                 return 0;
2771         }
2772
2773         /* Stop if we're a zombie or need a soft hangup */
2774         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2775                 ast_channel_unlock(chan);
2776                 return -1;
2777         }
2778
2779         answertime = ast_tvnow();
2780         ast_channel_answertime_set(chan, &answertime);
2781
2782         ast_channel_unlock(chan);
2783
2784         switch (ast_channel_state(chan)) {
2785         case AST_STATE_RINGING:
2786         case AST_STATE_RING:
2787                 ast_channel_lock(chan);
2788                 if (ast_channel_tech(chan)->answer) {
2789                         res = ast_channel_tech(chan)->answer(chan);
2790                 }
2791                 ast_setstate(chan, AST_STATE_UP);
2792                 ast_channel_unlock(chan);
2793                 break;
2794         case AST_STATE_UP:
2795                 break;
2796         default:
2797                 break;
2798         }
2799
2800         ast_indicate(chan, -1);
2801
2802         return res;
2803 }
2804
2805 int __ast_answer(struct ast_channel *chan, unsigned int delay)
2806 {
2807         int res = 0;
2808         enum ast_channel_state old_state;
2809
2810         old_state = ast_channel_state(chan);
2811         if ((res = ast_raw_answer(chan))) {
2812                 return res;
2813         }
2814
2815         switch (old_state) {
2816         case AST_STATE_RINGING:
2817         case AST_STATE_RING:
2818                 /* wait for media to start flowing, but don't wait any longer
2819                  * than 'delay' or 500 milliseconds, whichever is longer
2820                  */
2821                 do {
2822                         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2823                         struct ast_frame *cur;
2824                         struct ast_frame *new_frame;
2825                         int timeout_ms = MAX(delay, 500);
2826                         unsigned int done = 0;
2827                         struct timeval start;
2828
2829                         AST_LIST_HEAD_INIT_NOLOCK(&frames);
2830
2831                         start = ast_tvnow();
2832                         for (;;) {
2833                                 int ms = ast_remaining_ms(start, timeout_ms);
2834                                 ms = ast_waitfor(chan, ms);
2835                                 if (ms < 0) {
2836                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2837                                         res = -1;
2838                                         break;
2839                                 }
2840                                 if (ms == 0) {
2841                                         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));
2842                                         break;
2843                                 }
2844                                 cur = ast_read(chan);
2845                                 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2846                                              (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2847                                         if (cur) {
2848                                                 ast_frfree(cur);
2849                                         }
2850                                         res = -1;
2851                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2852                                         break;
2853                                 }
2854
2855                                 if ((new_frame = ast_frisolate(cur)) != cur) {
2856                                         ast_frfree(cur);
2857                                 }
2858
2859                                 AST_LIST_INSERT_HEAD(&frames, new_frame, frame_list);
2860
2861                                 /* if a specific delay period was requested, continue
2862                                  * until that delay has passed. don't stop just because
2863                                  * incoming media has arrived.
2864                                  */
2865                                 if (delay) {
2866                                         continue;
2867                                 }
2868
2869                                 switch (new_frame->frametype) {
2870                                         /* all of these frametypes qualify as 'media' */
2871                                 case AST_FRAME_VOICE:
2872                                 case AST_FRAME_VIDEO:
2873                                 case AST_FRAME_TEXT:
2874                                 case AST_FRAME_DTMF_BEGIN:
2875                                 case AST_FRAME_DTMF_END:
2876                                 case AST_FRAME_IMAGE:
2877                                 case AST_FRAME_HTML:
2878                                 case AST_FRAME_MODEM:
2879                                         done = 1;
2880                                         break;
2881                                 case AST_FRAME_CONTROL:
2882                                 case AST_FRAME_IAX:
2883                                 case AST_FRAME_BRIDGE_ACTION:
2884                                 case AST_FRAME_NULL:
2885                                 case AST_FRAME_CNG:
2886                                         break;
2887                                 }
2888
2889                                 if (done) {
2890                                         break;
2891                                 }
2892                         }
2893
2894                         if (res == 0) {
2895                                 ast_channel_lock(chan);
2896                                 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2897                                         ast_queue_frame_head(chan, cur);
2898                                         ast_frfree(cur);
2899                                 }
2900                                 ast_channel_unlock(chan);
2901                         }
2902                 } while (0);
2903                 break;
2904         default:
2905                 break;
2906         }
2907
2908         return res;
2909 }
2910
2911 int ast_answer(struct ast_channel *chan)
2912 {
2913         return __ast_answer(chan, 0);
2914 }
2915
2916 inline int ast_auto_answer(struct ast_channel *chan)
2917 {
2918         if (ast_channel_state(chan) == AST_STATE_UP) {
2919                 /* Already answered */
2920                 return 0;
2921         }
2922         return ast_answer(chan);
2923 }
2924
2925 int ast_channel_get_duration(struct ast_channel *chan)
2926 {
2927         ast_assert(NULL != chan);
2928
2929         if (ast_tvzero(ast_channel_creationtime(chan))) {
2930                 return 0;
2931         }
2932         return (ast_tvdiff_ms(ast_tvnow(), ast_channel_creationtime(chan)) / 1000);
2933 }
2934
2935 int ast_channel_get_up_time(struct ast_channel *chan)
2936 {
2937         ast_assert(NULL != chan);
2938
2939         if (ast_tvzero(ast_channel_answertime(chan))) {
2940                 return 0;
2941         }
2942         return (ast_tvdiff_ms(ast_tvnow(), ast_channel_answertime(chan)) / 1000);
2943 }
2944
2945 void ast_deactivate_generator(struct ast_channel *chan)
2946 {
2947         ast_channel_lock(chan);
2948         if (ast_channel_generatordata(chan)) {
2949                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2950                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2951                 }
2952                 ast_channel_generatordata_set(chan, NULL);
2953                 ast_channel_generator_set(chan, NULL);
2954                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2955                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
2956                 ast_settimeout(chan, 0, NULL, NULL);
2957         }
2958         ast_channel_unlock(chan);
2959 }
2960
2961 static void generator_write_format_change(struct ast_channel *chan)
2962 {
2963         ast_channel_lock(chan);
2964         if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
2965                 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
2966         }
2967         ast_channel_unlock(chan);
2968 }
2969
2970 static int generator_force(const void *data)
2971 {
2972         /* Called if generator doesn't have data */
2973         void *tmp;
2974         int res;
2975         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2976         struct ast_channel *chan = (struct ast_channel *)data;
2977
2978         ast_channel_lock(chan);
2979         tmp = ast_channel_generatordata(chan);
2980         ast_channel_generatordata_set(chan, NULL);
2981         if (ast_channel_generator(chan))
2982                 generate = ast_channel_generator(chan)->generate;
2983         ast_channel_unlock(chan);
2984
2985         if (!tmp || !generate)
2986                 return 0;
2987
2988         res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
2989
2990         ast_channel_lock(chan);
2991         if (ast_channel_generator(chan) && generate == ast_channel_generator(chan)->generate) {
2992                 ast_channel_generatordata_set(chan, tmp);
2993         }
2994         ast_channel_unlock(chan);
2995
2996         if (res) {
2997                 ast_debug(1, "Auto-deactivating generator\n");
2998                 ast_deactivate_generator(chan);
2999         }
3000
3001         return 0;
3002 }
3003
3004 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
3005 {
3006         int res = 0;
3007         void *generatordata = NULL;
3008
3009         ast_channel_lock(chan);
3010         if (ast_channel_generatordata(chan)) {
3011                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3012                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3013                 }
3014         }
3015         if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
3016                 res = -1;
3017         }
3018         ast_channel_generatordata_set(chan, generatordata);
3019         if (!res) {
3020                 ast_settimeout(chan, 50, generator_force, chan);
3021                 ast_channel_generator_set(chan, gen);
3022         }
3023         ast_channel_unlock(chan);
3024
3025         ast_prod(chan);
3026
3027         return res;
3028 }
3029
3030 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
3031 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
3032 {
3033         int winner = -1;
3034         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
3035         return winner;
3036 }
3037
3038 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
3039 #ifdef HAVE_EPOLL
3040 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
3041                                         int *exception, int *outfd, int *ms)
3042 #else
3043 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3044                                         int *exception, int *outfd, int *ms)
3045 #endif
3046 {
3047         struct timeval start = { 0 , 0 };
3048         struct pollfd *pfds = NULL;
3049         int res;
3050         long rms;
3051         int x, y, max;
3052         int sz;
3053         struct timeval now = { 0, 0 };
3054         struct timeval whentohangup = { 0, 0 }, diff;
3055         struct ast_channel *winner = NULL;
3056         struct fdmap {
3057                 int chan;
3058                 int fdno;
3059         } *fdmap = NULL;
3060
3061         if (outfd) {
3062                 *outfd = -99999;
3063         }
3064         if (exception) {
3065                 *exception = 0;
3066         }
3067
3068         if ((sz = n * AST_MAX_FDS + nfds)) {
3069                 pfds = ast_alloca(sizeof(*pfds) * sz);
3070                 fdmap = ast_alloca(sizeof(*fdmap) * sz);
3071         } else {
3072                 /* nothing to allocate and no FDs to check */
3073                 return NULL;
3074         }
3075
3076         /* Perform any pending masquerades */
3077         for (x = 0; x < n; x++) {
3078                 while (ast_channel_masq(c[x])) {
3079                         ast_do_masquerade(c[x]);
3080                 }
3081
3082                 ast_channel_lock(c[x]);
3083                 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
3084                         if (ast_tvzero(whentohangup))
3085                                 now = ast_tvnow();
3086                         diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
3087                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3088                                 ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3089                                 /* Should already be hungup */
3090                                 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3091                                 ast_channel_unlock(c[x]);
3092                                 return c[x];
3093                         }
3094                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3095                                 whentohangup = diff;
3096                 }
3097                 ast_channel_unlock(c[x]);
3098         }
3099         /* Wait full interval */
3100         rms = *ms;
3101         /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3102         if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3103                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
3104                 if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
3105                         rms =  *ms;
3106                 }
3107         } else if (!ast_tvzero(whentohangup) && rms < 0) {
3108                 /* Tiny corner case... call would need to last >24 days */
3109                 rms = INT_MAX;
3110         }
3111         /*
3112          * Build the pollfd array, putting the channels' fds first,
3113          * followed by individual fds. Order is important because
3114          * individual fd's must have priority over channel fds.
3115          */
3116         max = 0;
3117         for (x = 0; x < n; x++) {
3118                 for (y = 0; y < AST_MAX_FDS; y++) {
3119                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
3120                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
3121                         max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3122                 }
3123                 CHECK_BLOCKING(c[x]);
3124         }
3125         /* Add the individual fds */
3126         for (x = 0; x < nfds; x++) {
3127                 fdmap[max].chan = -1;
3128                 max += ast_add_fd(&pfds[max], fds[x]);
3129         }
3130
3131         if (*ms > 0) {
3132                 start = ast_tvnow();
3133         }
3134
3135         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3136                 do {
3137                         int kbrms = rms;
3138                         if (kbrms > 600000) {
3139                                 kbrms = 600000;
3140                         }
3141                         res = ast_poll(pfds, max, kbrms);
3142                         if (!res) {
3143                                 rms -= kbrms;
3144                         }
3145                 } while (!res && (rms > 0));
3146         } else {
3147                 res = ast_poll(pfds, max, rms);
3148         }
3149         for (x = 0; x < n; x++) {
3150                 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3151         }
3152         if (res < 0) { /* Simulate a timeout if we were interrupted */
3153                 if (errno != EINTR) {
3154                         *ms = -1;
3155                 }
3156                 return NULL;
3157         }
3158         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
3159                 now = ast_tvnow();
3160                 for (x = 0; x < n; x++) {
3161                         if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3162                                 ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3163                                 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3164                                 if (winner == NULL) {
3165                                         winner = c[x];
3166                                 }
3167                         }
3168                 }
3169         }
3170         if (res == 0) { /* no fd ready, reset timeout and done */
3171                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
3172                 return winner;
3173         }
3174         /*
3175          * Then check if any channel or fd has a pending event.
3176          * Remember to check channels first and fds last, as they
3177          * must have priority on setting 'winner'
3178          */
3179         for (x = 0; x < max; x++) {
3180                 res = pfds[x].revents;
3181                 if (res == 0) {
3182                         continue;
3183                 }
3184                 if (fdmap[x].chan >= 0) {       /* this is a channel */
3185                         winner = c[fdmap[x].chan];      /* override previous winners */
3186                         if (res & POLLPRI) {
3187                                 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3188                         } else {
3189                                 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3190                         }
3191                         ast_channel_fdno_set(winner, fdmap[x].fdno);
3192                 } else {                        /* this is an fd */
3193                         if (outfd) {
3194                                 *outfd = pfds[x].fd;
3195                         }
3196                         if (exception) {
3197                                 *exception = (res & POLLPRI) ? -1 : 0;
3198                         }
3199                         winner = NULL;
3200                 }
3201         }
3202         if (*ms > 0) {
3203                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3204                 if (*ms < 0) {
3205                         *ms = 0;
3206                 }
3207         }
3208         return winner;
3209 }
3210
3211 #ifdef HAVE_EPOLL
3212 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3213 {
3214         struct timeval start = { 0 , 0 };
3215         int res = 0;
3216         struct epoll_event ev[1];
3217         long diff, rms = *ms;
3218         struct ast_channel *winner = NULL;
3219         struct ast_epoll_data *aed = NULL;
3220
3221
3222         /* See if this channel needs to be masqueraded */
3223         while (ast_channel_masq(chan)) {
3224                 ast_do_masquerade(chan);
3225         }
3226
3227         ast_channel_lock(chan);
3228         /* Figure out their timeout */
3229         if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3230                 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow())) < 0) {
3231                         /* They should already be hungup! */
3232                         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3233                         ast_channel_unlock(chan);
3234                         return NULL;
3235                 }
3236                 /* If this value is smaller then the current one... make it priority */
3237                 if (rms > diff) {
3238                         rms = diff;
3239                 }
3240         }
3241
3242         ast_channel_unlock(chan);
3243
3244         /* Time to make this channel block... */
3245         CHECK_BLOCKING(chan);
3246
3247         if (*ms > 0) {
3248                 start = ast_tvnow();
3249         }
3250
3251         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3252         res = epoll_wait(ast_channel_epfd(chan), ev, 1, rms);
3253
3254         /* Stop blocking */
3255         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
3256
3257         /* Simulate a timeout if we were interrupted */
3258         if (res < 0) {
3259                 if (errno != EINTR) {
3260                         *ms = -1;
3261                 }
3262                 return NULL;
3263         }
3264
3265         /* If this channel has a timeout see if it expired */
3266         if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3267                 if (ast_tvdiff_ms(ast_tvnow(), *ast_channel_whentohangup(chan)) >= 0) {
3268                         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3269                         winner = chan;
3270                 }
3271         }
3272
3273         /* No fd ready, reset timeout and be done for now */
3274         if (!res) {
3275                 *ms = 0;
3276                 return winner;
3277         }
3278
3279         /* See what events are pending */
3280         aed = ev[0].data.ptr;
3281         ast_channel_fdno_set(chan, aed->which);
3282         if (ev[0].events & EPOLLPRI) {
3283                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3284         } else {
3285                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3286         }
3287
3288         if (*ms > 0) {
3289                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3290                 if (*ms < 0) {
3291                         *ms = 0;
3292                 }
3293         }
3294
3295         return chan;
3296 }
3297
3298 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3299 {
3300         struct timeval start = { 0 , 0 };
3301         int res = 0, i;
3302         struct epoll_event ev[25] = { { 0, } };
3303         struct timeval now = { 0, 0 };
3304         long whentohangup = 0, diff = 0, rms = *ms;
3305         struct ast_channel *winner = NULL;
3306
3307         for (i = 0; i < n; i++) {
3308                 while (ast_channel_masq(c[i])) {
3309                         ast_do_masquerade(c[i]);
3310                 }
3311
3312                 ast_channel_lock(c[i]);
3313                 if (!ast_tvzero(*ast_channel_whentohangup(c[i]))) {
3314                         if (whentohangup == 0) {
3315                                 now = ast_tvnow();
3316                         }
3317                         if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(c[i]), now)) < 0) {
3318                                 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3319                                 ast_channel_unlock(c[i]);
3320                                 return c[i];
3321                         }
3322                         if (!whentohangup || whentohangup > diff) {
3323                                 whentohangup = diff;
3324                         }
3325                 }
3326                 ast_channel_unlock(c[i]);
3327                 CHECK_BLOCKING(c[i]);
3328         }
3329
3330         rms = *ms;
3331         if (whentohangup) {
3332                 rms = whentohangup;
3333                 if (*ms >= 0 && *ms < rms) {
3334                         rms = *ms;
3335                 }
3336         }
3337
3338         if (*ms > 0) {
3339                 start = ast_tvnow();
3340         }
3341
3342         res = epoll_wait(ast_channel_epfd(c[0]), ev, 25, rms);
3343
3344         for (i = 0; i < n; i++) {
3345                 ast_clear_flag(ast_channel_flags(c[i]), AST_FLAG_BLOCKING);
3346         }
3347
3348         if (res < 0) {
3349                 if (errno != EINTR) {
3350                         *ms = -1;
3351                 }
3352                 return NULL;
3353         }
3354
3355         if (whentohangup) {
3356                 now = ast_tvnow();
3357                 for (i = 0; i < n; i++) {
3358                         if (!ast_tvzero(*ast_channel_whentohangup(c[i])) && ast_tvdiff_ms(now, *ast_channel_whentohangup(c[i])) >= 0) {
3359                                 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3360                                 if (!winner) {
3361                                         winner = c[i];
3362                                 }
3363                         }
3364                 }
3365         }
3366
3367         if (!res) {
3368                 *ms = 0;
3369                 return winner;
3370         }
3371
3372         for (i = 0; i < res; i++) {
3373                 struct ast_epoll_data *aed = ev[i].data.ptr;
3374
3375                 if (!ev[i].events || !aed) {
3376                         continue;
3377                 }
3378
3379                 winner = aed->chan;
3380                 if (ev[i].events & EPOLLPRI) {
3381                         ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3382                 } else {
3383                         ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3384                 }
3385                 ast_channel_fdno_set(winner, aed->which);
3386         }
3387