Add missing end-of-file line terminators.
[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/bridging.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                 /*! SILK is pretty awesome. */
806                 AST_FORMAT_SILK,
807                 /*! CELT supports crazy high sample rates */
808                 AST_FORMAT_CELT,
809                 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
810                     to use it */
811                 AST_FORMAT_LPC10,
812                 /*! G.729a is faster than 723 and slightly less expensive */
813                 AST_FORMAT_G729A,
814                 /*! Down to G.723.1 which is proprietary but at least designed for voice */
815                 AST_FORMAT_G723_1,
816         };
817         char buf[512];
818         int x;
819
820         /* Find the first preferred codec in the format given */
821         for (x = 0; x < ARRAY_LEN(prefs); x++) {
822                 if (ast_format_cap_best_byid(cap, prefs[x], result)) {
823                         return result;
824                 }
825         }
826
827         ast_format_clear(result);
828         ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
829
830         return NULL;
831 }
832
833 static const struct ast_channel_tech null_tech = {
834         .type = "NULL",
835         .description = "Null channel (should not see this)",
836 };
837
838 static void ast_channel_destructor(void *obj);
839 static void ast_dummy_channel_destructor(void *obj);
840
841 /*! \brief Create a new channel structure */
842 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
843 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
844                        const char *acctcode, const char *exten, const char *context,
845                        const char *linkedid, enum ama_flags amaflag, const char *file, int line,
846                        const char *function, const char *name_fmt, va_list ap)
847 {
848         struct ast_channel *tmp;
849         struct varshead *headp;
850         char *tech = "", *tech2 = NULL;
851         struct ast_format_cap *nativeformats;
852         struct ast_sched_context *schedctx;
853         struct ast_timer *timer;
854         struct timeval now;
855
856         /* If shutting down, don't allocate any new channels */
857         if (ast_shutting_down()) {
858                 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
859                 return NULL;
860         }
861
862         if (!(tmp = ast_channel_internal_alloc(ast_channel_destructor, linkedid))) {
863                 /* Channel structure allocation failure. */
864                 return NULL;
865         }
866         if (!(nativeformats = ast_format_cap_alloc())) {
867                 ao2_ref(tmp, -1);
868                 /* format capabilities structure allocation failure */
869                 return NULL;
870         }
871         ast_channel_nativeformats_set(tmp, nativeformats);
872
873         /*
874          * Init file descriptors to unopened state so
875          * the destructor can know not to close them.
876          */
877         ast_channel_timingfd_set(tmp, -1);
878         ast_channel_internal_alertpipe_clear(tmp);
879         ast_channel_internal_fd_clear_all(tmp);
880
881 #ifdef HAVE_EPOLL
882         ast_channel_epfd_set(tmp, epoll_create(25));
883 #endif
884
885         if (!(schedctx = ast_sched_context_create())) {
886                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
887                 return ast_channel_unref(tmp);
888         }
889         ast_channel_sched_set(tmp, schedctx);
890
891         ast_party_dialed_init(ast_channel_dialed(tmp));
892         ast_party_caller_init(ast_channel_caller(tmp));
893         ast_party_connected_line_init(ast_channel_connected(tmp));
894         ast_party_connected_line_init(ast_channel_connected_indicated(tmp));
895         ast_party_redirecting_init(ast_channel_redirecting(tmp));
896
897         if (cid_name) {
898                 ast_channel_caller(tmp)->id.name.valid = 1;
899                 ast_channel_caller(tmp)->id.name.str = ast_strdup(cid_name);
900                 if (!ast_channel_caller(tmp)->id.name.str) {
901                         return ast_channel_unref(tmp);
902                 }
903         }
904         if (cid_num) {
905                 ast_channel_caller(tmp)->id.number.valid = 1;
906                 ast_channel_caller(tmp)->id.number.str = ast_strdup(cid_num);
907                 if (!ast_channel_caller(tmp)->id.number.str) {
908                         return ast_channel_unref(tmp);
909                 }
910         }
911
912         if ((timer = ast_timer_open())) {
913                 ast_channel_timer_set(tmp, timer);
914                 if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
915                         needqueue = 0;
916                 }
917                 ast_channel_timingfd_set(tmp, ast_timer_fd(ast_channel_timer(tmp)));
918         }
919
920         if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
921                 return ast_channel_unref(tmp);
922         }
923
924         /* Always watch the alertpipe */
925         ast_channel_set_fd(tmp, AST_ALERT_FD, ast_channel_internal_alert_readfd(tmp));
926         /* And timing pipe */
927         ast_channel_set_fd(tmp, AST_TIMING_FD, ast_channel_timingfd(tmp));
928
929         /* Initial state */
930         ast_channel_state_set(tmp, state);
931
932         ast_channel_streamid_set(tmp, -1);
933
934         ast_channel_fin_set(tmp, global_fin);
935         ast_channel_fout_set(tmp, global_fout);
936
937         now = ast_tvnow();
938         ast_channel_creationtime_set(tmp, &now);
939
940         ast_channel_internal_setup_topics(tmp);
941
942         if (!ast_strlen_zero(name_fmt)) {
943                 char *slash, *slash2;
944                 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
945                  * And they all use slightly different formats for their name string.
946                  * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
947                  * This means, that the stringfields must have a routine that takes the va_lists directly, and
948                  * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
949                  * This new function was written so this can be accomplished.
950                  */
951                 ast_channel_name_build_va(tmp, name_fmt, ap);
952                 tech = ast_strdupa(ast_channel_name(tmp));
953                 if ((slash = strchr(tech, '/'))) {
954                         if ((slash2 = strchr(slash + 1, '/'))) {
955                                 tech2 = slash + 1;
956                                 *slash2 = '\0';
957                         }
958                         *slash = '\0';
959                 }
960         } else {
961                 /*
962                  * Start the string with '-' so it becomes an empty string
963                  * in the destructor.
964                  */
965                 ast_channel_name_set(tmp, "-**Unknown**");
966         }
967
968         /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
969
970         /* These 4 variables need to be set up for the cdr_init() to work right */
971         if (amaflag != AST_AMA_NONE) {
972                 ast_channel_amaflags_set(tmp, amaflag);
973         } else {
974                 ast_channel_amaflags_set(tmp, DEFAULT_AMA_FLAGS);
975         }
976
977         if (!ast_strlen_zero(acctcode)) {
978                 ast_channel_accountcode_set(tmp, acctcode);
979         }
980
981         ast_channel_context_set(tmp, S_OR(context, "default"));
982         ast_channel_exten_set(tmp, S_OR(exten, "s"));
983         ast_channel_priority_set(tmp, 1);
984
985         ast_atomic_fetchadd_int(&chancount, +1);
986
987         headp = ast_channel_varshead(tmp);
988         AST_LIST_HEAD_INIT_NOLOCK(headp);
989
990         ast_pbx_hangup_handler_init(tmp);
991         AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
992
993         AST_LIST_HEAD_INIT_NOLOCK(ast_channel_autochans(tmp));
994
995         ast_channel_language_set(tmp, defaultlanguage);
996
997         ast_channel_tech_set(tmp, &null_tech);
998
999         ao2_link(channels, tmp);
1000
1001         /*
1002          * And now, since the channel structure is built, and has its name, let's
1003          * call the manager event generator with this Newchannel event. This is the
1004          * proper and correct place to make this call, but you sure do have to pass
1005          * a lot of data into this func to do it here!
1006          */
1007         if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1008                 ast_channel_publish_snapshot(tmp);
1009         }
1010
1011         ast_channel_internal_finalize(tmp);
1012         ast_publish_channel_state(tmp);
1013         return tmp;
1014 }
1015
1016 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1017                                         const char *cid_name, const char *acctcode,
1018                                         const char *exten, const char *context,
1019                                         const char *linkedid, enum ama_flags amaflag,
1020                                         const char *file, int line, const char *function,
1021                                         const char *name_fmt, ...)
1022 {
1023         va_list ap;
1024         struct ast_channel *result;
1025
1026         va_start(ap, name_fmt);
1027         result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1028                                         linkedid, amaflag, file, line, function, name_fmt, ap);
1029         va_end(ap);
1030
1031         return result;
1032 }
1033
1034 /* only do the minimum amount of work needed here to make a channel
1035  * structure that can be used to expand channel vars */
1036 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1037 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1038 #else
1039 struct ast_channel *ast_dummy_channel_alloc(void)
1040 #endif
1041 {
1042         struct ast_channel *tmp;
1043         struct varshead *headp;
1044
1045         if (!(tmp = ast_channel_internal_alloc(ast_dummy_channel_destructor, NULL))) {
1046                 /* Dummy channel structure allocation failure. */
1047                 return NULL;
1048         }
1049
1050         ast_pbx_hangup_handler_init(tmp);
1051         AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
1052
1053         /*
1054          * Init file descriptors to unopened state just in case
1055          * autoservice is called on the channel or something tries to
1056          * read a frame from it.
1057          */
1058         ast_channel_timingfd_set(tmp, -1);
1059         ast_channel_internal_alertpipe_clear(tmp);
1060         ast_channel_internal_fd_clear_all(tmp);
1061 #ifdef HAVE_EPOLL
1062         ast_channel_epfd_set(tmp, -1);
1063 #endif
1064
1065         ast_channel_internal_setup_topics(tmp);
1066
1067         headp = ast_channel_varshead(tmp);
1068         AST_LIST_HEAD_INIT_NOLOCK(headp);
1069
1070         return tmp;
1071 }
1072
1073 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1074 {
1075         struct ast_frame *f;
1076         struct ast_frame *cur;
1077         unsigned int new_frames = 0;
1078         unsigned int new_voice_frames = 0;
1079         unsigned int queued_frames = 0;
1080         unsigned int queued_voice_frames = 0;
1081         AST_LIST_HEAD_NOLOCK(,ast_frame) frames;
1082
1083         ast_channel_lock(chan);
1084
1085         /*
1086          * Check the last frame on the queue if we are queuing the new
1087          * frames after it.
1088          */
1089         cur = AST_LIST_LAST(ast_channel_readq(chan));
1090         if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1091                 switch (cur->subclass.integer) {
1092                 case AST_CONTROL_END_OF_Q:
1093                         if (fin->frametype == AST_FRAME_CONTROL
1094                                 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1095                                 /*
1096                                  * Destroy the end-of-Q marker frame so we can queue the hangup
1097                                  * frame in its place.
1098                                  */
1099                                 AST_LIST_REMOVE(ast_channel_readq(chan), cur, frame_list);
1100                                 ast_frfree(cur);
1101
1102                                 /*
1103                                  * This has degenerated to a normal queue append anyway.  Since
1104                                  * we just destroyed the last frame in the queue we must make
1105                                  * sure that "after" is NULL or bad things will happen.
1106                                  */
1107                                 after = NULL;
1108                                 break;
1109                         }
1110                         /* Fall through */
1111                 case AST_CONTROL_HANGUP:
1112                         /* Don't queue anything. */
1113                         ast_channel_unlock(chan);
1114                         return 0;
1115                 default:
1116                         break;
1117                 }
1118         }
1119
1120         /* Build copies of all the new frames and count them */
1121         AST_LIST_HEAD_INIT_NOLOCK(&frames);
1122         for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1123                 if (!(f = ast_frdup(cur))) {
1124                         if (AST_LIST_FIRST(&frames)) {
1125                                 ast_frfree(AST_LIST_FIRST(&frames));
1126                         }
1127                         ast_channel_unlock(chan);
1128                         return -1;
1129                 }
1130
1131                 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1132                 new_frames++;
1133                 if (f->frametype == AST_FRAME_VOICE) {
1134                         new_voice_frames++;
1135                 }
1136         }
1137
1138         /* Count how many frames exist on the queue */
1139         AST_LIST_TRAVERSE(ast_channel_readq(chan), cur, frame_list) {
1140                 queued_frames++;
1141                 if (cur->frametype == AST_FRAME_VOICE) {
1142                         queued_voice_frames++;
1143                 }
1144         }
1145
1146         if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1147                 int count = 0;
1148                 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1149                 AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), cur, frame_list) {
1150                         /* Save the most recent frame */
1151                         if (!AST_LIST_NEXT(cur, frame_list)) {
1152                                 break;
1153                         } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1154                                 if (++count > 64) {
1155                                         break;
1156                                 }
1157                                 AST_LIST_REMOVE_CURRENT(frame_list);
1158                                 ast_frfree(cur);
1159                         }
1160                 }
1161                 AST_LIST_TRAVERSE_SAFE_END;
1162         }
1163
1164         if (after) {
1165                 AST_LIST_INSERT_LIST_AFTER(ast_channel_readq(chan), &frames, after, frame_list);
1166         } else {
1167                 if (head) {
1168                         AST_LIST_APPEND_LIST(&frames, ast_channel_readq(chan), frame_list);
1169                         AST_LIST_HEAD_INIT_NOLOCK(ast_channel_readq(chan));
1170                 }
1171                 AST_LIST_APPEND_LIST(ast_channel_readq(chan), &frames, frame_list);
1172         }
1173
1174         if (ast_channel_alert_writable(chan)) {
1175                 if (ast_channel_alert_write(chan)) {
1176                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1177                                 ast_channel_name(chan), queued_frames, strerror(errno));
1178                 }
1179         } else if (ast_channel_timingfd(chan) > -1) {
1180                 ast_timer_enable_continuous(ast_channel_timer(chan));
1181         } else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
1182                 pthread_kill(ast_channel_blocker(chan), SIGURG);
1183         }
1184
1185         ast_channel_unlock(chan);
1186
1187         return 0;
1188 }
1189
1190 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1191 {
1192         return __ast_queue_frame(chan, fin, 0, NULL);
1193 }
1194
1195 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1196 {
1197         return __ast_queue_frame(chan, fin, 1, NULL);
1198 }
1199
1200 /*! \brief Queue a hangup frame for channel */
1201 int ast_queue_hangup(struct ast_channel *chan)
1202 {
1203         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1204         int res;
1205
1206         /* Yeah, let's not change a lock-critical value without locking */
1207         ast_channel_lock(chan);
1208         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1209         ast_channel_publish_blob(chan, ast_channel_hangup_request_type(), NULL);
1210
1211         res = ast_queue_frame(chan, &f);
1212         ast_channel_unlock(chan);
1213         return res;
1214 }
1215
1216 /*! \brief Queue a hangup frame for channel */
1217 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1218 {
1219         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
1220         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1221         int res;
1222
1223         if (cause >= 0) {
1224                 f.data.uint32 = cause;
1225         }
1226
1227         /* Yeah, let's not change a lock-critical value without locking */
1228         ast_channel_lock(chan);
1229         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1230         if (cause < 0) {
1231                 f.data.uint32 = ast_channel_hangupcause(chan);
1232         }
1233         blob = ast_json_pack("{s: i}",
1234                              "cause", cause);
1235         ast_channel_publish_blob(chan, ast_channel_hangup_request_type(), blob);
1236
1237         res = ast_queue_frame(chan, &f);
1238         ast_channel_unlock(chan);
1239         return res;
1240 }
1241
1242 int ast_queue_hold(struct ast_channel *chan, const char *musicclass)
1243 {
1244         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
1245         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HOLD };
1246         int res;
1247
1248         if (!ast_strlen_zero(musicclass)) {
1249                 f.data.ptr = (void *) musicclass;
1250                 f.datalen = strlen(musicclass) + 1;
1251
1252                 blob = ast_json_pack("{s: s}",
1253                                      "musicclass", musicclass);
1254         }
1255
1256         ast_channel_publish_blob(chan, ast_channel_hold_type(), blob);
1257
1258         res = ast_queue_frame(chan, &f);
1259         return res;
1260 }
1261
1262 int ast_queue_unhold(struct ast_channel *chan)
1263 {
1264         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_UNHOLD };
1265         int res;
1266
1267         ast_channel_publish_blob(chan, ast_channel_unhold_type(), NULL);
1268
1269         res = ast_queue_frame(chan, &f);
1270         return res;
1271 }
1272
1273 /*! \brief Queue a control frame */
1274 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1275 {
1276         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1277         return ast_queue_frame(chan, &f);
1278 }
1279
1280 /*! \brief Queue a control frame with payload */
1281 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1282                            const void *data, size_t datalen)
1283 {
1284         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1285         return ast_queue_frame(chan, &f);
1286 }
1287
1288 /*! \brief Set defer DTMF flag on channel */
1289 int ast_channel_defer_dtmf(struct ast_channel *chan)
1290 {
1291         int pre = 0;
1292
1293         if (chan) {
1294                 pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1295                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1296         }
1297         return pre;
1298 }
1299
1300 /*! \brief Unset defer DTMF flag on channel */
1301 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1302 {
1303         if (chan)
1304                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1305 }
1306
1307 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1308                 void *data, int ao2_flags)
1309 {
1310         return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1311 }
1312
1313 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1314 {
1315         struct ast_channel *chan = obj;
1316         const char *name = arg;
1317         size_t name_len = *(size_t *) data;
1318         int ret = CMP_MATCH;
1319
1320         if (ast_strlen_zero(name)) {
1321                 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1322                 return CMP_STOP;
1323         }
1324
1325         ast_channel_lock(chan);
1326         if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1327                 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1328                 ret = 0; /* name match failed, keep looking */
1329         }
1330         ast_channel_unlock(chan);
1331
1332         return ret;
1333 }
1334
1335 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1336 {
1337         struct ast_channel *chan = obj;
1338         char *context = arg;
1339         char *exten = data;
1340         int ret = CMP_MATCH;
1341
1342         if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1343                 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1344                 return CMP_STOP;
1345         }
1346
1347         ast_channel_lock(chan);
1348         if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1349                 ret = 0; /* Context match failed, continue */
1350         } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1351                 ret = 0; /* Extension match failed, continue */
1352         }
1353         ast_channel_unlock(chan);
1354
1355         return ret;
1356 }
1357
1358 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1359 {
1360         struct ast_channel *chan = obj;
1361         char *uniqueid = arg;
1362         size_t id_len = *(size_t *) data;
1363         int ret = CMP_MATCH;
1364
1365         if (ast_strlen_zero(uniqueid)) {
1366                 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1367                 return CMP_STOP;
1368         }
1369
1370         ast_channel_lock(chan);
1371         if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1372                 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1373                 ret = 0; /* uniqueid match failed, keep looking */
1374         }
1375         ast_channel_unlock(chan);
1376
1377         return ret;
1378 }
1379
1380 struct ast_channel_iterator {
1381         /* storage for non-dynamically allocated iterator */
1382         struct ao2_iterator simple_iterator;
1383         /* pointer to the actual iterator (simple_iterator or a dynamically
1384          * allocated iterator)
1385          */
1386         struct ao2_iterator *active_iterator;
1387 };
1388
1389 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1390 {
1391         ao2_iterator_destroy(i->active_iterator);
1392         ast_free(i);
1393
1394         return NULL;
1395 }
1396
1397 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1398 {
1399         struct ast_channel_iterator *i;
1400         char *l_exten = (char *) exten;
1401         char *l_context = (char *) context;
1402
1403         if (!(i = ast_calloc(1, sizeof(*i)))) {
1404                 return NULL;
1405         }
1406
1407         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1408                 l_context, l_exten, OBJ_MULTIPLE);
1409         if (!i->active_iterator) {
1410                 ast_free(i);
1411                 return NULL;
1412         }
1413
1414         return i;
1415 }
1416
1417 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1418 {
1419         struct ast_channel_iterator *i;
1420         char *l_name = (char *) name;
1421
1422         if (!(i = ast_calloc(1, sizeof(*i)))) {
1423                 return NULL;
1424         }
1425
1426         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1427                 l_name, &name_len,
1428                 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1429         if (!i->active_iterator) {
1430                 ast_free(i);
1431                 return NULL;
1432         }
1433
1434         return i;
1435 }
1436
1437 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1438 {
1439         struct ast_channel_iterator *i;
1440
1441         if (!(i = ast_calloc(1, sizeof(*i)))) {
1442                 return NULL;
1443         }
1444
1445         i->simple_iterator = ao2_iterator_init(channels, 0);
1446         i->active_iterator = &i->simple_iterator;
1447
1448         return i;
1449 }
1450
1451 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1452 {
1453         return ao2_iterator_next(i->active_iterator);
1454 }
1455
1456 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1457 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1458 {
1459         ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1460         return CMP_STOP;
1461 }
1462
1463 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1464 {
1465         struct ast_channel *chan;
1466         char *l_name = (char *) name;
1467
1468         chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1469                 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1470         if (chan) {
1471                 return chan;
1472         }
1473
1474         if (ast_strlen_zero(l_name)) {
1475                 /* We didn't have a name to search for so quit. */
1476                 return NULL;
1477         }
1478
1479         /* Now try a search for uniqueid. */
1480         return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1481 }
1482
1483 struct ast_channel *ast_channel_get_by_name(const char *name)
1484 {
1485         return ast_channel_get_by_name_prefix(name, 0);
1486 }
1487
1488 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1489 {
1490         char *l_exten = (char *) exten;
1491         char *l_context = (char *) context;
1492
1493         return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1494 }
1495
1496 int ast_is_deferrable_frame(const struct ast_frame *frame)
1497 {
1498         /* Do not add a default entry in this switch statement.  Each new
1499          * frame type should be addressed directly as to whether it should
1500          * be queued up or not.
1501          */
1502         switch (frame->frametype) {
1503         case AST_FRAME_BRIDGE_ACTION:
1504         case AST_FRAME_CONTROL:
1505         case AST_FRAME_TEXT:
1506         case AST_FRAME_IMAGE:
1507         case AST_FRAME_HTML:
1508                 return 1;
1509
1510         case AST_FRAME_DTMF_END:
1511         case AST_FRAME_DTMF_BEGIN:
1512         case AST_FRAME_VOICE:
1513         case AST_FRAME_VIDEO:
1514         case AST_FRAME_NULL:
1515         case AST_FRAME_IAX:
1516         case AST_FRAME_CNG:
1517         case AST_FRAME_MODEM:
1518                 return 0;
1519         }
1520         return 0;
1521 }
1522
1523 /*! \brief Wait, look for hangups and condition arg */
1524 int ast_safe_sleep_conditional(struct ast_channel *chan, int timeout_ms, int (*cond)(void*), void *data)
1525 {
1526         struct ast_frame *f;
1527         struct ast_silence_generator *silgen = NULL;
1528         int res = 0;
1529         struct timeval start;
1530         int ms;
1531         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1532
1533         AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1534
1535         /* If no other generator is present, start silencegen while waiting */
1536         if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1537                 silgen = ast_channel_start_silence_generator(chan);
1538         }
1539
1540         start = ast_tvnow();
1541         while ((ms = ast_remaining_ms(start, timeout_ms))) {
1542                 struct ast_frame *dup_f = NULL;
1543
1544                 if (cond && ((*cond)(data) == 0)) {
1545                         break;
1546                 }
1547                 ms = ast_waitfor(chan, ms);
1548                 if (ms < 0) {
1549                         res = -1;
1550                         break;
1551                 }
1552                 if (ms > 0) {
1553                         f = ast_read(chan);
1554                         if (!f) {
1555                                 res = -1;
1556                                 break;
1557                         }
1558
1559                         if (!ast_is_deferrable_frame(f)) {
1560                                 ast_frfree(f);
1561                                 continue;
1562                         }
1563
1564                         if ((dup_f = ast_frisolate(f))) {
1565                                 if (dup_f != f) {
1566                                         ast_frfree(f);
1567                                 }
1568                                 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1569                         }
1570                 }
1571         }
1572
1573         /* stop silgen if present */
1574         if (silgen) {
1575                 ast_channel_stop_silence_generator(chan, silgen);
1576         }
1577
1578         /* We need to free all the deferred frames, but we only need to
1579          * queue the deferred frames if there was no error and no
1580          * hangup was received
1581          */
1582         ast_channel_lock(chan);
1583         while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1584                 if (!res) {
1585                         ast_queue_frame_head(chan, f);
1586                 }
1587                 ast_frfree(f);
1588         }
1589         ast_channel_unlock(chan);
1590
1591         return res;
1592 }
1593
1594 /*! \brief Wait, look for hangups */
1595 int ast_safe_sleep(struct ast_channel *chan, int ms)
1596 {
1597         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1598 }
1599
1600 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1601 {
1602         /* Safe, even if already unlinked. */
1603         ao2_unlink(channels, chan);
1604         return ast_channel_unref(chan);
1605 }
1606
1607 void ast_party_name_init(struct ast_party_name *init)
1608 {
1609         init->str = NULL;
1610         init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1611         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1612         init->valid = 0;
1613 }
1614
1615 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1616 {
1617         if (dest == src) {
1618                 /* Don't copy to self */
1619                 return;
1620         }
1621
1622         ast_free(dest->str);
1623         dest->str = ast_strdup(src->str);
1624         dest->char_set = src->char_set;
1625         dest->presentation = src->presentation;
1626         dest->valid = src->valid;
1627 }
1628
1629 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1630 {
1631         init->str = NULL;
1632         init->char_set = guide->char_set;
1633         init->presentation = guide->presentation;
1634         init->valid = guide->valid;
1635 }
1636
1637 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1638 {
1639         if (dest == src) {
1640                 /* Don't set to self */
1641                 return;
1642         }
1643
1644         if (src->str && src->str != dest->str) {
1645                 ast_free(dest->str);
1646                 dest->str = ast_strdup(src->str);
1647         }
1648
1649         dest->char_set = src->char_set;
1650         dest->presentation = src->presentation;
1651         dest->valid = src->valid;
1652 }
1653
1654 void ast_party_name_free(struct ast_party_name *doomed)
1655 {
1656         ast_free(doomed->str);
1657         doomed->str = NULL;
1658 }
1659
1660 void ast_party_number_init(struct ast_party_number *init)
1661 {
1662         init->str = NULL;
1663         init->plan = 0;/* Unknown */
1664         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1665         init->valid = 0;
1666 }
1667
1668 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1669 {
1670         if (dest == src) {
1671                 /* Don't copy to self */
1672                 return;
1673         }
1674
1675         ast_free(dest->str);
1676         dest->str = ast_strdup(src->str);
1677         dest->plan = src->plan;
1678         dest->presentation = src->presentation;
1679         dest->valid = src->valid;
1680 }
1681
1682 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1683 {
1684         init->str = NULL;
1685         init->plan = guide->plan;
1686         init->presentation = guide->presentation;
1687         init->valid = guide->valid;
1688 }
1689
1690 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1691 {
1692         if (dest == src) {
1693                 /* Don't set to self */
1694                 return;
1695         }
1696
1697         if (src->str && src->str != dest->str) {
1698                 ast_free(dest->str);
1699                 dest->str = ast_strdup(src->str);
1700         }
1701
1702         dest->plan = src->plan;
1703         dest->presentation = src->presentation;
1704         dest->valid = src->valid;
1705 }
1706
1707 void ast_party_number_free(struct ast_party_number *doomed)
1708 {
1709         ast_free(doomed->str);
1710         doomed->str = NULL;
1711 }
1712
1713 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1714 {
1715         init->str = NULL;
1716         init->type = 0;
1717         init->odd_even_indicator = 0;
1718         init->valid = 0;
1719 }
1720
1721 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1722 {
1723         if (dest == src) {
1724                 /* Don't copy to self */
1725                 return;
1726         }
1727
1728         ast_free(dest->str);
1729         dest->str = ast_strdup(src->str);
1730         dest->type = src->type;
1731         dest->odd_even_indicator = src->odd_even_indicator;
1732         dest->valid = src->valid;
1733 }
1734
1735 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1736 {
1737         init->str = NULL;
1738         init->type = guide->type;
1739         init->odd_even_indicator = guide->odd_even_indicator;
1740         init->valid = guide->valid;
1741 }
1742
1743 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1744 {
1745         if (dest == src) {
1746                 /* Don't set to self */
1747                 return;
1748         }
1749
1750         if (src->str && src->str != dest->str) {
1751                 ast_free(dest->str);
1752                 dest->str = ast_strdup(src->str);
1753         }
1754
1755         dest->type = src->type;
1756         dest->odd_even_indicator = src->odd_even_indicator;
1757         dest->valid = src->valid;
1758 }
1759
1760 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1761 {
1762         ast_free(doomed->str);
1763         doomed->str = NULL;
1764 }
1765
1766 void ast_set_party_id_all(struct ast_set_party_id *update_id)
1767 {
1768         update_id->name = 1;
1769         update_id->number = 1;
1770         update_id->subaddress = 1;
1771 }
1772
1773 void ast_party_id_init(struct ast_party_id *init)
1774 {
1775         ast_party_name_init(&init->name);
1776         ast_party_number_init(&init->number);
1777         ast_party_subaddress_init(&init->subaddress);
1778         init->tag = NULL;
1779 }
1780
1781 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1782 {
1783         if (dest == src) {
1784                 /* Don't copy to self */
1785                 return;
1786         }
1787
1788         ast_party_name_copy(&dest->name, &src->name);
1789         ast_party_number_copy(&dest->number, &src->number);
1790         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1791
1792         ast_free(dest->tag);
1793         dest->tag = ast_strdup(src->tag);
1794 }
1795
1796 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1797 {
1798         ast_party_name_set_init(&init->name, &guide->name);
1799         ast_party_number_set_init(&init->number, &guide->number);
1800         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1801         init->tag = NULL;
1802 }
1803
1804 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1805 {
1806         if (dest == src) {
1807                 /* Don't set to self */
1808                 return;
1809         }
1810
1811         if (!update || update->name) {
1812                 ast_party_name_set(&dest->name, &src->name);
1813         }
1814         if (!update || update->number) {
1815                 ast_party_number_set(&dest->number, &src->number);
1816         }
1817         if (!update || update->subaddress) {
1818                 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1819         }
1820
1821         if (src->tag && src->tag != dest->tag) {
1822                 ast_free(dest->tag);
1823                 dest->tag = ast_strdup(src->tag);
1824         }
1825 }
1826
1827 void ast_party_id_free(struct ast_party_id *doomed)
1828 {
1829         ast_party_name_free(&doomed->name);
1830         ast_party_number_free(&doomed->number);
1831         ast_party_subaddress_free(&doomed->subaddress);
1832
1833         ast_free(doomed->tag);
1834         doomed->tag = NULL;
1835 }
1836
1837 int ast_party_id_presentation(const struct ast_party_id *id)
1838 {
1839         int number_priority;
1840         int number_value;
1841         int number_screening;
1842         int name_priority;
1843         int name_value;
1844
1845         /* Determine name presentation priority. */
1846         if (!id->name.valid) {
1847                 name_value = AST_PRES_UNAVAILABLE;
1848                 name_priority = 3;
1849         } else {
1850                 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1851                 switch (name_value) {
1852                 case AST_PRES_RESTRICTED:
1853                         name_priority = 0;
1854                         break;
1855                 case AST_PRES_ALLOWED:
1856                         name_priority = 1;
1857                         break;
1858                 case AST_PRES_UNAVAILABLE:
1859                         name_priority = 2;
1860                         break;
1861                 default:
1862                         name_value = AST_PRES_UNAVAILABLE;
1863                         name_priority = 3;
1864                         break;
1865                 }
1866         }
1867
1868         /* Determine number presentation priority. */
1869         if (!id->number.valid) {
1870                 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1871                 number_value = AST_PRES_UNAVAILABLE;
1872                 number_priority = 3;
1873         } else {
1874                 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1875                 number_value = id->number.presentation & AST_PRES_RESTRICTION;
1876                 switch (number_value) {
1877                 case AST_PRES_RESTRICTED:
1878                         number_priority = 0;
1879                         break;
1880                 case AST_PRES_ALLOWED:
1881                         number_priority = 1;
1882                         break;
1883                 case AST_PRES_UNAVAILABLE:
1884                         number_priority = 2;
1885                         break;
1886                 default:
1887                         number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1888                         number_value = AST_PRES_UNAVAILABLE;
1889                         number_priority = 3;
1890                         break;
1891                 }
1892         }
1893
1894         /* Select the wining presentation value. */
1895         if (name_priority < number_priority) {
1896                 number_value = name_value;
1897         }
1898         if (number_value == AST_PRES_UNAVAILABLE) {
1899                 return AST_PRES_NUMBER_NOT_AVAILABLE;
1900         }
1901
1902         return number_value | number_screening;
1903 }
1904
1905 void ast_party_id_invalidate(struct ast_party_id *id)
1906 {
1907         id->name.valid = 0;
1908         id->number.valid = 0;
1909         id->subaddress.valid = 0;
1910 }
1911
1912 void ast_party_id_reset(struct ast_party_id *id)
1913 {
1914         ast_party_id_free(id);
1915         ast_party_id_init(id);
1916 }
1917
1918 struct ast_party_id ast_party_id_merge(struct ast_party_id *base, struct ast_party_id *overlay)
1919 {
1920         struct ast_party_id merged;
1921
1922         merged = *base;
1923         if (overlay->name.valid) {
1924                 merged.name = overlay->name;
1925         }
1926         if (overlay->number.valid) {
1927                 merged.number = overlay->number;
1928         }
1929         if (overlay->subaddress.valid) {
1930                 merged.subaddress = overlay->subaddress;
1931         }
1932         /* Note the actual structure is returned and not a pointer to it! */
1933         return merged;
1934 }
1935
1936 void ast_party_id_merge_copy(struct ast_party_id *dest, struct ast_party_id *base, struct ast_party_id *overlay)
1937 {
1938         struct ast_party_id merged;
1939
1940         merged = ast_party_id_merge(base, overlay);
1941         ast_party_id_copy(dest, &merged);
1942 }
1943
1944 void ast_party_dialed_init(struct ast_party_dialed *init)
1945 {
1946         init->number.str = NULL;
1947         init->number.plan = 0;/* Unknown */
1948         ast_party_subaddress_init(&init->subaddress);
1949         init->transit_network_select = 0;
1950 }
1951
1952 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1953 {
1954         if (dest == src) {
1955                 /* Don't copy to self */
1956                 return;
1957         }
1958
1959         ast_free(dest->number.str);
1960         dest->number.str = ast_strdup(src->number.str);
1961         dest->number.plan = src->number.plan;
1962         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1963         dest->transit_network_select = src->transit_network_select;
1964 }
1965
1966 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
1967 {
1968         init->number.str = NULL;
1969         init->number.plan = guide->number.plan;
1970         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1971         init->transit_network_select = guide->transit_network_select;
1972 }
1973
1974 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1975 {
1976         if (src->number.str && src->number.str != dest->number.str) {
1977                 ast_free(dest->number.str);
1978                 dest->number.str = ast_strdup(src->number.str);
1979         }
1980         dest->number.plan = src->number.plan;
1981
1982         ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1983
1984         dest->transit_network_select = src->transit_network_select;
1985 }
1986
1987 void ast_party_dialed_free(struct ast_party_dialed *doomed)
1988 {
1989         ast_free(doomed->number.str);
1990         doomed->number.str = NULL;
1991         ast_party_subaddress_free(&doomed->subaddress);
1992 }
1993
1994 void ast_party_caller_init(struct ast_party_caller *init)
1995 {
1996         ast_party_id_init(&init->id);
1997         ast_party_id_init(&init->ani);
1998         ast_party_id_init(&init->priv);
1999         init->ani2 = 0;
2000 }
2001
2002 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2003 {
2004         if (dest == src) {
2005                 /* Don't copy to self */
2006                 return;
2007         }
2008
2009         ast_party_id_copy(&dest->id, &src->id);
2010         ast_party_id_copy(&dest->ani, &src->ani);
2011         ast_party_id_copy(&dest->priv, &src->priv);
2012         dest->ani2 = src->ani2;
2013 }
2014
2015 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2016 {
2017         ast_party_id_set_init(&init->id, &guide->id);
2018         ast_party_id_set_init(&init->ani, &guide->ani);
2019         ast_party_id_set_init(&init->priv, &guide->priv);
2020         init->ani2 = guide->ani2;
2021 }
2022
2023 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2024 {
2025         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2026         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2027         ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2028         dest->ani2 = src->ani2;
2029 }
2030
2031 void ast_party_caller_free(struct ast_party_caller *doomed)
2032 {
2033         ast_party_id_free(&doomed->id);
2034         ast_party_id_free(&doomed->ani);
2035         ast_party_id_free(&doomed->priv);
2036 }
2037
2038 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2039 {
2040         ast_party_id_init(&init->id);
2041         ast_party_id_init(&init->ani);
2042         ast_party_id_init(&init->priv);
2043         init->ani2 = 0;
2044         init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2045 }
2046
2047 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2048 {
2049         if (dest == src) {
2050                 /* Don't copy to self */
2051                 return;
2052         }
2053
2054         ast_party_id_copy(&dest->id, &src->id);
2055         ast_party_id_copy(&dest->ani, &src->ani);
2056         ast_party_id_copy(&dest->priv, &src->priv);
2057         dest->ani2 = src->ani2;
2058         dest->source = src->source;
2059 }
2060
2061 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2062 {
2063         ast_party_id_set_init(&init->id, &guide->id);
2064         ast_party_id_set_init(&init->ani, &guide->ani);
2065         ast_party_id_set_init(&init->priv, &guide->priv);
2066         init->ani2 = guide->ani2;
2067         init->source = guide->source;
2068 }
2069
2070 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)
2071 {
2072         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2073         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2074         ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
2075         dest->ani2 = src->ani2;
2076         dest->source = src->source;
2077 }
2078
2079 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2080 {
2081         connected->id = caller->id;
2082         connected->ani = caller->ani;
2083         connected->priv = caller->priv;
2084         connected->ani2 = caller->ani2;
2085         connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2086 }
2087
2088 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2089 {
2090         ast_party_id_free(&doomed->id);
2091         ast_party_id_free(&doomed->ani);
2092         ast_party_id_free(&doomed->priv);
2093 }
2094
2095 void ast_party_redirecting_reason_init(struct ast_party_redirecting_reason *init)
2096 {
2097         init->str = NULL;
2098         init->code = AST_REDIRECTING_REASON_UNKNOWN;
2099 }
2100
2101 void ast_party_redirecting_reason_copy(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2102 {
2103         if (dest == src) {
2104                 return;
2105         }
2106
2107         ast_free(dest->str);
2108         dest->str = ast_strdup(src->str);
2109         dest->code = src->code;
2110 }
2111
2112 void ast_party_redirecting_reason_set_init(struct ast_party_redirecting_reason *init, const struct ast_party_redirecting_reason *guide)
2113 {
2114         init->str = NULL;
2115         init->code = guide->code;
2116 }
2117
2118 void ast_party_redirecting_reason_set(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
2119 {
2120         if (dest == src) {
2121                 return;
2122         }
2123
2124         if (src->str && src->str != dest->str) {
2125                 ast_free(dest->str);
2126                 dest->str = ast_strdup(src->str);
2127         }
2128
2129         dest->code = src->code;
2130 }
2131
2132 void ast_party_redirecting_reason_free(struct ast_party_redirecting_reason *doomed)
2133 {
2134         ast_free(doomed->str);
2135 }
2136
2137
2138 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2139 {
2140         ast_party_id_init(&init->orig);
2141         ast_party_id_init(&init->from);
2142         ast_party_id_init(&init->to);
2143         ast_party_id_init(&init->priv_orig);
2144         ast_party_id_init(&init->priv_from);
2145         ast_party_id_init(&init->priv_to);
2146         ast_party_redirecting_reason_init(&init->reason);
2147         ast_party_redirecting_reason_init(&init->orig_reason);
2148         init->count = 0;
2149 }
2150
2151 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2152 {
2153         if (dest == src) {
2154                 /* Don't copy to self */
2155                 return;
2156         }
2157
2158         ast_party_id_copy(&dest->orig, &src->orig);
2159         ast_party_id_copy(&dest->from, &src->from);
2160         ast_party_id_copy(&dest->to, &src->to);
2161         ast_party_id_copy(&dest->priv_orig, &src->priv_orig);
2162         ast_party_id_copy(&dest->priv_from, &src->priv_from);
2163         ast_party_id_copy(&dest->priv_to, &src->priv_to);
2164         ast_party_redirecting_reason_copy(&dest->reason, &src->reason);
2165         ast_party_redirecting_reason_copy(&dest->orig_reason, &src->orig_reason);
2166         dest->count = src->count;
2167 }
2168
2169 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2170 {
2171         ast_party_id_set_init(&init->orig, &guide->orig);
2172         ast_party_id_set_init(&init->from, &guide->from);
2173         ast_party_id_set_init(&init->to, &guide->to);
2174         ast_party_id_set_init(&init->priv_orig, &guide->priv_orig);
2175         ast_party_id_set_init(&init->priv_from, &guide->priv_from);
2176         ast_party_id_set_init(&init->priv_to, &guide->priv_to);
2177         ast_party_redirecting_reason_set_init(&init->reason, &guide->reason);
2178         ast_party_redirecting_reason_set_init(&init->orig_reason, &guide->orig_reason);
2179         init->count = guide->count;
2180 }
2181
2182 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2183 {
2184         ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2185         ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2186         ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2187         ast_party_id_set(&dest->priv_orig, &src->priv_orig, update ? &update->priv_orig : NULL);
2188         ast_party_id_set(&dest->priv_from, &src->priv_from, update ? &update->priv_from : NULL);
2189         ast_party_id_set(&dest->priv_to, &src->priv_to, update ? &update->priv_to : NULL);
2190         ast_party_redirecting_reason_set(&dest->reason, &src->reason);
2191         ast_party_redirecting_reason_set(&dest->orig_reason, &src->orig_reason);
2192         dest->count = src->count;
2193 }
2194
2195 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2196 {
2197         ast_party_id_free(&doomed->orig);
2198         ast_party_id_free(&doomed->from);
2199         ast_party_id_free(&doomed->to);
2200         ast_party_id_free(&doomed->priv_orig);
2201         ast_party_id_free(&doomed->priv_from);
2202         ast_party_id_free(&doomed->priv_to);
2203         ast_party_redirecting_reason_free(&doomed->reason);
2204         ast_party_redirecting_reason_free(&doomed->orig_reason);
2205 }
2206
2207 /*! \brief Free a channel structure */
2208 static void ast_channel_destructor(void *obj)
2209 {
2210         struct ast_channel *chan = obj;
2211 #ifdef HAVE_EPOLL
2212         int i;
2213 #endif
2214         struct ast_var_t *vardata;
2215         struct ast_frame *f;
2216         struct varshead *headp;
2217         struct ast_datastore *datastore;
2218         char device_name[AST_CHANNEL_NAME];
2219         struct ast_callid *callid;
2220
2221         /* Stop monitoring */
2222         if (ast_channel_monitor(chan)) {
2223                 ast_channel_monitor(chan)->stop(chan, 0);
2224         }
2225
2226         /* If there is native format music-on-hold state, free it */
2227         if (ast_channel_music_state(chan)) {
2228                 ast_moh_cleanup(chan);
2229         }
2230
2231         ast_pbx_hangup_handler_destroy(chan);
2232
2233         /* Things that may possibly raise Stasis messages shouldn't occur after this point */
2234         ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEAD);
2235         ast_channel_publish_snapshot(chan);
2236         publish_cache_clear(chan);
2237
2238         ast_channel_lock(chan);
2239
2240         /* Get rid of each of the data stores on the channel */
2241         while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2242                 /* Free the data store */
2243                 ast_datastore_free(datastore);
2244
2245         /* While the channel is locked, take the reference to its callid while we tear down the call. */
2246         callid = ast_channel_callid(chan);
2247         ast_channel_callid_cleanup(chan);
2248
2249         ast_channel_unlock(chan);
2250
2251         /* Lock and unlock the channel just to be sure nobody has it locked still
2252            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2253         ast_channel_lock(chan);
2254         ast_channel_unlock(chan);
2255
2256         if (ast_channel_tech_pvt(chan)) {
2257                 ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2258                 ast_free(ast_channel_tech_pvt(chan));
2259         }
2260
2261         if (ast_channel_sched(chan)) {
2262                 ast_sched_context_destroy(ast_channel_sched(chan));
2263         }
2264
2265         if (ast_channel_internal_is_finalized(chan)) {
2266                 char *dashptr;
2267
2268                 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2269                 if ((dashptr = strrchr(device_name, '-'))) {
2270                         *dashptr = '\0';
2271                 }
2272         } else {
2273                 device_name[0] = '\0';
2274         }
2275
2276         /* Free translators */
2277         if (ast_channel_readtrans(chan))
2278                 ast_translator_free_path(ast_channel_readtrans(chan));
2279         if (ast_channel_writetrans(chan))
2280                 ast_translator_free_path(ast_channel_writetrans(chan));
2281         if (ast_channel_pbx(chan))
2282                 ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2283
2284         ast_party_dialed_free(ast_channel_dialed(chan));
2285         ast_party_caller_free(ast_channel_caller(chan));
2286         ast_party_connected_line_free(ast_channel_connected(chan));
2287         ast_party_connected_line_free(ast_channel_connected_indicated(chan));
2288         ast_party_redirecting_free(ast_channel_redirecting(chan));
2289
2290         /* Close pipes if appropriate */
2291         ast_channel_internal_alertpipe_close(chan);
2292         if (ast_channel_timer(chan)) {
2293                 ast_timer_close(ast_channel_timer(chan));
2294                 ast_channel_timer_set(chan, NULL);
2295         }
2296 #ifdef HAVE_EPOLL
2297         for (i = 0; i < AST_MAX_FDS; i++) {
2298                 if (ast_channel_internal_epfd_data(chan, i)) {
2299                         ast_free(ast_channel_internal_epfd_data(chan, i));
2300                 }
2301         }
2302         close(ast_channel_epfd(chan));
2303 #endif
2304         while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2305                 ast_frfree(f);
2306
2307         /* loop over the variables list, freeing all data and deleting list items */
2308         /* no need to lock the list, as the channel is already locked */
2309         headp = ast_channel_varshead(chan);
2310         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2311                 ast_var_delete(vardata);
2312
2313         ast_app_group_discard(chan);
2314
2315         /* Destroy the jitterbuffer */
2316         ast_jb_destroy(chan);
2317
2318         if (ast_channel_cdr(chan)) {
2319                 ast_cdr_free(ast_channel_cdr(chan));
2320                 ast_channel_cdr_set(chan, NULL);
2321         }
2322
2323         if (ast_channel_zone(chan)) {
2324                 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2325         }
2326
2327         ast_channel_internal_cleanup(chan);
2328
2329         if (device_name[0]) {
2330                 /*
2331                  * We have a device name to notify of a new state.
2332                  *
2333                  * Queue an unknown state, because, while we know that this particular
2334                  * instance is dead, we don't know the state of all other possible
2335                  * instances.
2336                  */
2337                 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);
2338         }
2339
2340         ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2341         if (callid) {
2342                 ast_callid_unref(callid);
2343         }
2344
2345         ast_channel_named_callgroups_set(chan, NULL);
2346         ast_channel_named_pickupgroups_set(chan, NULL);
2347
2348         ast_atomic_fetchadd_int(&chancount, -1);
2349 }
2350
2351 /*! \brief Free a dummy channel structure */
2352 static void ast_dummy_channel_destructor(void *obj)
2353 {
2354         struct ast_channel *chan = obj;
2355         struct ast_datastore *datastore;
2356         struct ast_var_t *vardata;
2357         struct varshead *headp;
2358
2359         ast_pbx_hangup_handler_destroy(chan);
2360
2361         /* Get rid of each of the data stores on the channel */
2362         while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
2363                 /* Free the data store */
2364                 ast_datastore_free(datastore);
2365         }
2366
2367         ast_party_dialed_free(ast_channel_dialed(chan));
2368         ast_party_caller_free(ast_channel_caller(chan));
2369         ast_party_connected_line_free(ast_channel_connected(chan));
2370         ast_party_connected_line_free(ast_channel_connected_indicated(chan));
2371         ast_party_redirecting_free(ast_channel_redirecting(chan));
2372
2373         /* loop over the variables list, freeing all data and deleting list items */
2374         /* no need to lock the list, as the channel is already locked */
2375         headp = ast_channel_varshead(chan);
2376         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2377                 ast_var_delete(vardata);
2378
2379         if (ast_channel_cdr(chan)) {
2380                 ast_cdr_free(ast_channel_cdr(chan));
2381                 ast_channel_cdr_set(chan, NULL);
2382         }
2383
2384         ast_channel_internal_cleanup(chan);
2385 }
2386
2387 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2388 {
2389         return ast_datastore_alloc(info, uid);
2390 }
2391
2392 int ast_channel_datastore_free(struct ast_datastore *datastore)
2393 {
2394         return ast_datastore_free(datastore);
2395 }
2396
2397 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2398 {
2399         struct ast_datastore *datastore = NULL, *datastore2;
2400
2401         AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2402                 if (datastore->inheritance > 0) {
2403                         datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2404                         if (datastore2) {
2405                                 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2406                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2407                                 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2408                         }
2409                 }
2410         }
2411         return 0;
2412 }
2413
2414 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2415 {
2416         int res = 0;
2417
2418         AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2419
2420         return res;
2421 }
2422
2423 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2424 {
2425         return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2426 }
2427
2428 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2429 {
2430         struct ast_datastore *datastore = NULL;
2431
2432         if (info == NULL)
2433                 return NULL;
2434
2435         AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2436                 if (datastore->info != info) {
2437                         continue;
2438                 }
2439
2440                 if (uid == NULL) {
2441                         /* matched by type only */
2442                         break;
2443                 }
2444
2445                 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2446                         /* Matched by type AND uid */
2447                         break;
2448                 }
2449         }
2450
2451         return datastore;
2452 }
2453
2454 /*! Set the file descriptor on the channel */
2455 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2456 {
2457 #ifdef HAVE_EPOLL
2458         struct epoll_event ev;
2459         struct ast_epoll_data *aed = NULL;
2460
2461         if (ast_channel_fd_isset(chan, which)) {
2462                 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2463                 aed = ast_channel_internal_epfd_data(chan, which);
2464         }
2465
2466         /* If this new fd is valid, add it to the epoll */
2467         if (fd > -1) {
2468                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2469                         return;
2470
2471                 ast_channel_internal_epfd_data_set(chan, which, aed);
2472                 aed->chan = chan;
2473                 aed->which = which;
2474
2475                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2476                 ev.data.ptr = aed;
2477                 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2478         } else if (aed) {
2479                 /* We don't have to keep around this epoll data structure now */
2480                 ast_free(aed);
2481                 ast_channel_epfd_data_set(chan, which, NULL);
2482         }
2483 #endif
2484         ast_channel_internal_fd_set(chan, which, fd);
2485         return;
2486 }
2487
2488 /*! Add a channel to an optimized waitfor */
2489 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2490 {
2491 #ifdef HAVE_EPOLL
2492         struct epoll_event ev;
2493         int i = 0;
2494
2495         if (ast_channel_epfd(chan0) == -1)
2496                 return;
2497
2498         /* Iterate through the file descriptors on chan1, adding them to chan0 */
2499         for (i = 0; i < AST_MAX_FDS; i++) {
2500                 if (!ast_channel_fd_isset(chan1, i)) {
2501                         continue;
2502                 }
2503                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2504                 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2505                 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2506         }
2507
2508 #endif
2509         return;
2510 }
2511
2512 /*! Delete a channel from an optimized waitfor */
2513 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2514 {
2515 #ifdef HAVE_EPOLL
2516         struct epoll_event ev;
2517         int i = 0;
2518
2519         if (ast_channel_epfd(chan0) == -1)
2520                 return;
2521
2522         for (i = 0; i < AST_MAX_FDS; i++) {
2523                 if (!ast_channel_fd_isset(chan1, i)) {
2524                         continue;
2525                 }
2526                 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2527         }
2528
2529 #endif
2530         return;
2531 }
2532
2533 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2534 {
2535         ast_channel_lock(chan);
2536
2537         ast_channel_softhangup_internal_flag_clear(chan, flag);
2538
2539         if (!ast_channel_softhangup_internal_flag(chan)) {
2540                 struct ast_frame *fr;
2541
2542                 /* If we have completely cleared the softhangup flag,
2543                  * then we need to fully abort the hangup process.  This requires
2544                  * pulling the END_OF_Q frame out of the channel frame queue if it
2545                  * still happens to be there. */
2546
2547                 fr = AST_LIST_LAST(ast_channel_readq(chan));
2548                 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2549                                 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2550                         AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2551                         ast_frfree(fr);
2552                 }
2553         }
2554
2555         ast_channel_unlock(chan);
2556 }
2557
2558 /*! \brief Softly hangup a channel, don't lock */
2559 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2560 {
2561         ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2562         /* Inform channel driver that we need to be hung up, if it cares */
2563         ast_channel_softhangup_internal_flag_add(chan, cause);
2564         ast_queue_frame(chan, &ast_null_frame);
2565         /* Interrupt any poll call or such */
2566         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2567                 pthread_kill(ast_channel_blocker(chan), SIGURG);
2568         return 0;
2569 }
2570
2571 /*! \brief Softly hangup a channel, lock */
2572 int ast_softhangup(struct ast_channel *chan, int cause)
2573 {
2574         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
2575         int res;
2576
2577         ast_channel_lock(chan);
2578         res = ast_softhangup_nolock(chan, cause);
2579         blob = ast_json_pack("{s: i, s: b}",
2580                              "cause", cause,
2581                              "soft", 1);
2582         ast_channel_publish_blob(chan, ast_channel_hangup_request_type(), blob);
2583         ast_channel_unlock(chan);
2584
2585         return res;
2586 }
2587
2588 static void free_translation(struct ast_channel *clonechan)
2589 {
2590         if (ast_channel_writetrans(clonechan))
2591                 ast_translator_free_path(ast_channel_writetrans(clonechan));
2592         if (ast_channel_readtrans(clonechan))
2593                 ast_translator_free_path(ast_channel_readtrans(clonechan));
2594         ast_channel_writetrans_set(clonechan, NULL);
2595         ast_channel_readtrans_set(clonechan, NULL);
2596         if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2597                 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2598                 ast_format_clear(ast_channel_rawreadformat(clonechan));
2599         } else {
2600                 struct ast_format tmpfmt;
2601                 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2602                 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2603                 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2604         }
2605 }
2606
2607 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2608 {
2609         struct ast_channel *bridge;
2610
2611         ast_channel_lock(chan);
2612         if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2613                 ast_channel_hangupsource_set(chan, source);
2614         }
2615         bridge = ast_bridged_channel(chan);
2616         if (bridge) {
2617                 ast_channel_ref(bridge);
2618         }
2619         ast_channel_unlock(chan);
2620
2621         if (bridge) {
2622                 ast_channel_lock(bridge);
2623                 if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
2624                         ast_channel_hangupsource_set(bridge, source);
2625                 }
2626                 ast_channel_unlock(bridge);
2627                 ast_channel_unref(bridge);
2628         }
2629 }
2630
2631 int ast_channel_has_audio_frame_or_monitor(struct ast_channel *chan)
2632 {
2633         return ast_channel_monitor(chan)
2634                 || !ast_audiohook_write_list_empty(ast_channel_audiohooks(chan))
2635                 || !ast_framehook_list_contains_no_active(ast_channel_framehooks(chan));
2636 }
2637
2638 static void destroy_hooks(struct ast_channel *chan)
2639 {
2640         if (ast_channel_audiohooks(chan)) {
2641                 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2642                 ast_channel_audiohooks_set(chan, NULL);
2643         }
2644
2645         ast_framehook_list_destroy(chan);
2646 }
2647
2648 /*! \brief Hangup a channel */
2649 void ast_hangup(struct ast_channel *chan)
2650 {
2651         /* Be NULL safe for RAII_VAR() usage. */
2652         if (!chan) {
2653                 return;
2654         }
2655
2656         ast_autoservice_stop(chan);
2657
2658         ast_channel_lock(chan);
2659
2660         /*
2661          * Do the masquerade if someone is setup to masquerade into us.
2662          *
2663          * NOTE: We must hold the channel lock after testing for a
2664          * pending masquerade and setting the channel as a zombie to
2665          * prevent ast_channel_masquerade() from setting up a
2666          * masquerade with a dead channel.
2667          */
2668         while (ast_channel_masq(chan)) {
2669                 ast_channel_unlock(chan);
2670                 ast_do_masquerade(chan);
2671                 ast_channel_lock(chan);
2672         }
2673
2674         if (ast_channel_masqr(chan)) {
2675                 /*
2676                  * This channel is one which will be masqueraded into something.
2677                  * Mark it as a zombie already so ast_do_masquerade() will know
2678                  * to free it later.
2679                  */
2680                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2681                 destroy_hooks(chan);
2682                 ast_channel_unlock(chan);
2683                 return;
2684         }
2685
2686         /* Mark as a zombie so a masquerade cannot be setup on this channel. */
2687         ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2688
2689         ast_channel_unlock(chan);
2690
2691         /*
2692          * XXX if running the hangup handlers here causes problems
2693          * because the handlers take too long to execute, we could move
2694          * the meat of this function into another thread.  A thread
2695          * where channels go to die.
2696          *
2697          * If this is done, ast_autoservice_chan_hangup_peer() will no
2698          * longer be needed.
2699          */
2700         ast_pbx_hangup_handler_run(chan);
2701         ao2_unlink(channels, chan);
2702         ast_channel_lock(chan);
2703
2704         destroy_hooks(chan);
2705
2706         free_translation(chan);
2707         /* Close audio stream */
2708         if (ast_channel_stream(chan)) {
2709                 ast_closestream(ast_channel_stream(chan));
2710                 ast_channel_stream_set(chan, NULL);
2711         }
2712         /* Close video stream */
2713         if (ast_channel_vstream(chan)) {
2714                 ast_closestream(ast_channel_vstream(chan));
2715                 ast_channel_vstream_set(chan, NULL);
2716         }
2717         if (ast_channel_sched(chan)) {
2718                 ast_sched_context_destroy(ast_channel_sched(chan));
2719                 ast_channel_sched_set(chan, NULL);
2720         }
2721
2722         if (ast_channel_generatordata(chan)) {  /* Clear any tone stuff remaining */
2723                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2724                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2725                 }
2726         }
2727         ast_channel_generatordata_set(chan, NULL);
2728         ast_channel_generator_set(chan, NULL);
2729
2730         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2731                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2732                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
2733                         (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2734                 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2735         }
2736
2737         ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2738         if (ast_channel_tech(chan)->hangup) {
2739                 ast_channel_tech(chan)->hangup(chan);
2740         }
2741
2742         ast_channel_unlock(chan);
2743
2744         ast_cc_offer(chan);
2745
2746         ast_channel_unref(chan);
2747 }
2748
2749 int ast_raw_answer(struct ast_channel *chan)
2750 {
2751         int res = 0;
2752         struct timeval answertime;
2753
2754         ast_channel_lock(chan);
2755
2756         /* You can't answer an outbound call */
2757         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2758                 ast_channel_unlock(chan);
2759                 return 0;
2760         }
2761
2762         /* Stop if we're a zombie or need a soft hangup */
2763         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2764                 ast_channel_unlock(chan);
2765                 return -1;
2766         }
2767
2768         answertime = ast_tvnow();
2769         ast_channel_answertime_set(chan, &answertime);
2770
2771         ast_channel_unlock(chan);
2772
2773         switch (ast_channel_state(chan)) {
2774         case AST_STATE_RINGING:
2775         case AST_STATE_RING:
2776                 ast_channel_lock(chan);
2777                 if (ast_channel_tech(chan)->answer) {
2778                         res = ast_channel_tech(chan)->answer(chan);
2779                 }
2780                 ast_setstate(chan, AST_STATE_UP);
2781                 ast_channel_unlock(chan);
2782                 break;
2783         case AST_STATE_UP:
2784                 break;
2785         default:
2786                 break;
2787         }
2788
2789         ast_indicate(chan, -1);
2790
2791         return res;
2792 }
2793
2794 int __ast_answer(struct ast_channel *chan, unsigned int delay)
2795 {
2796         int res = 0;
2797         enum ast_channel_state old_state;
2798
2799         old_state = ast_channel_state(chan);
2800         if ((res = ast_raw_answer(chan))) {
2801                 return res;
2802         }
2803
2804         switch (old_state) {
2805         case AST_STATE_RINGING:
2806         case AST_STATE_RING:
2807                 /* wait for media to start flowing, but don't wait any longer
2808                  * than 'delay' or 500 milliseconds, whichever is longer
2809                  */
2810                 do {
2811                         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2812                         struct ast_frame *cur;
2813                         struct ast_frame *new_frame;
2814                         int timeout_ms = MAX(delay, 500);
2815                         unsigned int done = 0;
2816                         struct timeval start;
2817
2818                         AST_LIST_HEAD_INIT_NOLOCK(&frames);
2819
2820                         start = ast_tvnow();
2821                         for (;;) {
2822                                 int ms = ast_remaining_ms(start, timeout_ms);
2823                                 ms = ast_waitfor(chan, ms);
2824                                 if (ms < 0) {
2825                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2826                                         res = -1;
2827                                         break;
2828                                 }
2829                                 if (ms == 0) {
2830                                         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));
2831                                         break;
2832                                 }
2833                                 cur = ast_read(chan);
2834                                 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2835                                              (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2836                                         if (cur) {
2837                                                 ast_frfree(cur);
2838                                         }
2839                                         res = -1;
2840                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2841                                         break;
2842                                 }
2843
2844                                 if ((new_frame = ast_frisolate(cur)) != cur) {
2845                                         ast_frfree(cur);
2846                                 }
2847
2848                                 AST_LIST_INSERT_HEAD(&frames, new_frame, frame_list);
2849
2850                                 /* if a specific delay period was requested, continue
2851                                  * until that delay has passed. don't stop just because
2852                                  * incoming media has arrived.
2853                                  */
2854                                 if (delay) {
2855                                         continue;
2856                                 }
2857
2858                                 switch (new_frame->frametype) {
2859                                         /* all of these frametypes qualify as 'media' */
2860                                 case AST_FRAME_VOICE:
2861                                 case AST_FRAME_VIDEO:
2862                                 case AST_FRAME_TEXT:
2863                                 case AST_FRAME_DTMF_BEGIN:
2864                                 case AST_FRAME_DTMF_END:
2865                                 case AST_FRAME_IMAGE:
2866                                 case AST_FRAME_HTML:
2867                                 case AST_FRAME_MODEM:
2868                                         done = 1;
2869                                         break;
2870                                 case AST_FRAME_CONTROL:
2871                                 case AST_FRAME_IAX:
2872                                 case AST_FRAME_BRIDGE_ACTION:
2873                                 case AST_FRAME_NULL:
2874                                 case AST_FRAME_CNG:
2875                                         break;
2876                                 }
2877
2878                                 if (done) {
2879                                         break;
2880                                 }
2881                         }
2882
2883                         if (res == 0) {
2884                                 ast_channel_lock(chan);
2885                                 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2886                                         ast_queue_frame_head(chan, cur);
2887                                         ast_frfree(cur);
2888                                 }
2889                                 ast_channel_unlock(chan);
2890                         }
2891                 } while (0);
2892                 break;
2893         default:
2894                 break;
2895         }
2896
2897         return res;
2898 }
2899
2900 int ast_answer(struct ast_channel *chan)
2901 {
2902         return __ast_answer(chan, 0);
2903 }
2904
2905 inline int ast_auto_answer(struct ast_channel *chan)
2906 {
2907         if (ast_channel_state(chan) == AST_STATE_UP) {
2908                 /* Already answered */
2909                 return 0;
2910         }
2911         return ast_answer(chan);
2912 }
2913
2914 int ast_channel_get_duration(struct ast_channel *chan)
2915 {
2916         ast_assert(NULL != chan);
2917
2918         if (ast_tvzero(ast_channel_creationtime(chan))) {
2919                 return 0;
2920         }
2921         return (ast_tvdiff_ms(ast_tvnow(), ast_channel_creationtime(chan)) / 1000);
2922 }
2923
2924 int ast_channel_get_up_time(struct ast_channel *chan)
2925 {
2926         ast_assert(NULL != chan);
2927
2928         if (ast_tvzero(ast_channel_answertime(chan))) {
2929                 return 0;
2930         }
2931         return (ast_tvdiff_ms(ast_tvnow(), ast_channel_answertime(chan)) / 1000);
2932 }
2933
2934 void ast_deactivate_generator(struct ast_channel *chan)
2935 {
2936         ast_channel_lock(chan);
2937         if (ast_channel_generatordata(chan)) {
2938                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2939                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2940                 }
2941                 ast_channel_generatordata_set(chan, NULL);
2942                 ast_channel_generator_set(chan, NULL);
2943                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2944                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
2945                 ast_settimeout(chan, 0, NULL, NULL);
2946         }
2947         ast_channel_unlock(chan);
2948 }
2949
2950 static void generator_write_format_change(struct ast_channel *chan)
2951 {
2952         ast_channel_lock(chan);
2953         if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
2954                 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
2955         }
2956         ast_channel_unlock(chan);
2957 }
2958
2959 static int generator_force(const void *data)
2960 {
2961         /* Called if generator doesn't have data */
2962         void *tmp;
2963         int res;
2964         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2965         struct ast_channel *chan = (struct ast_channel *)data;
2966
2967         ast_channel_lock(chan);
2968         tmp = ast_channel_generatordata(chan);
2969         ast_channel_generatordata_set(chan, NULL);
2970         if (ast_channel_generator(chan))
2971                 generate = ast_channel_generator(chan)->generate;
2972         ast_channel_unlock(chan);
2973
2974         if (!tmp || !generate)
2975                 return 0;
2976
2977         res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
2978
2979         ast_channel_lock(chan);
2980         if (ast_channel_generator(chan) && generate == ast_channel_generator(chan)->generate) {
2981                 ast_channel_generatordata_set(chan, tmp);
2982         }
2983         ast_channel_unlock(chan);
2984
2985         if (res) {
2986                 ast_debug(1, "Auto-deactivating generator\n");
2987                 ast_deactivate_generator(chan);
2988         }
2989
2990         return 0;
2991 }
2992
2993 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2994 {
2995         int res = 0;
2996         void *generatordata = NULL;
2997
2998         ast_channel_lock(chan);
2999         if (ast_channel_generatordata(chan)) {
3000                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
3001                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
3002                 }
3003         }
3004         if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
3005                 res = -1;
3006         }
3007         ast_channel_generatordata_set(chan, generatordata);
3008         if (!res) {
3009                 ast_settimeout(chan, 50, generator_force, chan);
3010                 ast_channel_generator_set(chan, gen);
3011         }
3012         ast_channel_unlock(chan);
3013
3014         ast_prod(chan);
3015
3016         return res;
3017 }
3018
3019 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
3020 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
3021 {
3022         int winner = -1;
3023         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
3024         return winner;
3025 }
3026
3027 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
3028 #ifdef HAVE_EPOLL
3029 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
3030                                         int *exception, int *outfd, int *ms)
3031 #else
3032 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3033                                         int *exception, int *outfd, int *ms)
3034 #endif
3035 {
3036         struct timeval start = { 0 , 0 };
3037         struct pollfd *pfds = NULL;
3038         int res;
3039         long rms;
3040         int x, y, max;
3041         int sz;
3042         struct timeval now = { 0, 0 };
3043         struct timeval whentohangup = { 0, 0 }, diff;
3044         struct ast_channel *winner = NULL;
3045         struct fdmap {
3046                 int chan;
3047                 int fdno;
3048         } *fdmap = NULL;
3049
3050         if (outfd) {
3051                 *outfd = -99999;
3052         }
3053         if (exception) {
3054                 *exception = 0;
3055         }
3056
3057         if ((sz = n * AST_MAX_FDS + nfds)) {
3058                 pfds = ast_alloca(sizeof(*pfds) * sz);
3059                 fdmap = ast_alloca(sizeof(*fdmap) * sz);
3060         } else {
3061                 /* nothing to allocate and no FDs to check */
3062                 return NULL;
3063         }
3064
3065         /* Perform any pending masquerades */
3066         for (x = 0; x < n; x++) {
3067                 while (ast_channel_masq(c[x])) {
3068                         ast_do_masquerade(c[x]);
3069                 }
3070
3071                 ast_channel_lock(c[x]);
3072                 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
3073                         if (ast_tvzero(whentohangup))
3074                                 now = ast_tvnow();
3075                         diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
3076                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3077                                 ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3078                                 /* Should already be hungup */
3079                                 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3080                                 ast_channel_unlock(c[x]);
3081                                 return c[x];
3082                         }
3083                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3084                                 whentohangup = diff;
3085                 }
3086                 ast_channel_unlock(c[x]);
3087         }
3088         /* Wait full interval */
3089         rms = *ms;
3090         /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3091         if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3092                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
3093                 if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
3094                         rms =  *ms;
3095                 }
3096         } else if (!ast_tvzero(whentohangup) && rms < 0) {
3097                 /* Tiny corner case... call would need to last >24 days */
3098                 rms = INT_MAX;
3099         }
3100         /*
3101          * Build the pollfd array, putting the channels' fds first,
3102          * followed by individual fds. Order is important because
3103          * individual fd's must have priority over channel fds.
3104          */
3105         max = 0;
3106         for (x = 0; x < n; x++) {
3107                 for (y = 0; y < AST_MAX_FDS; y++) {
3108                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
3109                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
3110                         max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3111                 }
3112                 CHECK_BLOCKING(c[x]);
3113         }
3114         /* Add the individual fds */
3115         for (x = 0; x < nfds; x++) {
3116                 fdmap[max].chan = -1;
3117                 max += ast_add_fd(&pfds[max], fds[x]);
3118         }
3119
3120         if (*ms > 0) {
3121                 start = ast_tvnow();
3122         }
3123
3124         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3125                 do {
3126                         int kbrms = rms;
3127                         if (kbrms > 600000) {
3128                                 kbrms = 600000;
3129                         }
3130                         res = ast_poll(pfds, max, kbrms);
3131                         if (!res) {
3132                                 rms -= kbrms;
3133                         }
3134                 } while (!res && (rms > 0));
3135         } else {
3136                 res = ast_poll(pfds, max, rms);
3137         }
3138         for (x = 0; x < n; x++) {
3139                 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3140         }
3141         if (res < 0) { /* Simulate a timeout if we were interrupted */
3142                 if (errno != EINTR) {
3143                         *ms = -1;
3144                 }
3145                 return NULL;
3146         }
3147         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
3148                 now = ast_tvnow();
3149                 for (x = 0; x < n; x++) {
3150                         if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3151                                 ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
3152                                 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3153                                 if (winner == NULL) {
3154                                         winner = c[x];
3155                                 }
3156                         }
3157                 }
3158         }
3159         if (res == 0) { /* no fd ready, reset timeout and done */
3160                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
3161                 return winner;
3162         }
3163         /*
3164          * Then check if any channel or fd has a pending event.
3165          * Remember to check channels first and fds last, as they
3166          * must have priority on setting 'winner'
3167          */
3168         for (x = 0; x < max; x++) {
3169                 res = pfds[x].revents;
3170                 if (res == 0) {
3171                         continue;
3172                 }
3173                 if (fdmap[x].chan >= 0) {       /* this is a channel */
3174                         winner = c[fdmap[x].chan];      /* override previous winners */
3175                         if (res & POLLPRI) {
3176                                 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3177                         } else {
3178                                 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3179                         }
3180                         ast_channel_fdno_set(winner, fdmap[x].fdno);
3181                 } else {                        /* this is an fd */
3182                         if (outfd) {
3183                                 *outfd = pfds[x].fd;
3184                         }
3185                         if (exception) {
3186                                 *exception = (res & POLLPRI) ? -1 : 0;
3187                         }
3188                         winner = NULL;
3189                 }
3190         }
3191         if (*ms > 0) {
3192                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3193                 if (*ms < 0) {
3194                         *ms = 0;
3195                 }
3196         }
3197         return winner;
3198 }
3199
3200 #ifdef HAVE_EPOLL
3201 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3202 {
3203         struct timeval start = { 0 , 0 };
3204         int res = 0;
3205         struct epoll_event ev[1];
3206         long diff, rms = *ms;
3207         struct ast_channel *winner = NULL;
3208         struct ast_epoll_data *aed = NULL;
3209
3210
3211         /* See if this channel needs to be masqueraded */
3212         while (ast_channel_masq(chan)) {
3213                 ast_do_masquerade(chan);
3214         }
3215
3216         ast_channel_lock(chan);
3217         /* Figure out their timeout */
3218         if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3219                 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow())) < 0) {
3220                         /* They should already be hungup! */
3221                         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3222                         ast_channel_unlock(chan);
3223                         return NULL;
3224                 }
3225                 /* If this value is smaller then the current one... make it priority */
3226                 if (rms > diff) {
3227                         rms = diff;
3228                 }
3229         }
3230
3231         ast_channel_unlock(chan);
3232
3233         /* Time to make this channel block... */
3234         CHECK_BLOCKING(chan);
3235
3236         if (*ms > 0) {
3237                 start = ast_tvnow();
3238         }
3239
3240         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3241         res = epoll_wait(ast_channel_epfd(chan), ev, 1, rms);
3242
3243         /* Stop blocking */
3244         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
3245
3246         /* Simulate a timeout if we were interrupted */
3247         if (res < 0) {
3248                 if (errno != EINTR) {
3249                         *ms = -1;
3250                 }
3251                 return NULL;
3252         }
3253
3254         /* If this channel has a timeout see if it expired */
3255         if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3256                 if (ast_tvdiff_ms(ast_tvnow(), *ast_channel_whentohangup(chan)) >= 0) {
3257                         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3258                         winner = chan;
3259                 }
3260         }
3261
3262         /* No fd ready, reset timeout and be done for now */
3263         if (!res) {
3264                 *ms = 0;
3265                 return winner;
3266         }
3267
3268         /* See what events are pending */
3269         aed = ev[0].data.ptr;
3270         ast_channel_fdno_set(chan, aed->which);
3271         if (ev[0].events & EPOLLPRI) {
3272                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3273         } else {
3274                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3275         }
3276
3277         if (*ms > 0) {
3278                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3279                 if (*ms < 0) {
3280                         *ms = 0;
3281                 }
3282         }
3283
3284         return chan;
3285 }
3286
3287 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3288 {
3289         struct timeval start = { 0 , 0 };
3290         int res = 0, i;
3291         struct epoll_event ev[25] = { { 0, } };
3292         struct timeval now = { 0, 0 };
3293         long whentohangup = 0, diff = 0, rms = *ms;
3294         struct ast_channel *winner = NULL;
3295
3296         for (i = 0; i < n; i++) {
3297                 while (ast_channel_masq(c[i])) {
3298                         ast_do_masquerade(c[i]);
3299                 }
3300
3301                 ast_channel_lock(c[i]);
3302                 if (!ast_tvzero(*ast_channel_whentohangup(c[i]))) {
3303                         if (whentohangup == 0) {
3304                                 now = ast_tvnow();
3305                         }
3306                         if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(c[i]), now)) < 0) {
3307                                 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3308                                 ast_channel_unlock(c[i]);
3309                                 return c[i];
3310                         }
3311                         if (!whentohangup || whentohangup > diff) {
3312                                 whentohangup = diff;
3313                         }
3314                 }
3315                 ast_channel_unlock(c[i]);
3316                 CHECK_BLOCKING(c[i]);
3317         }
3318
3319         rms = *ms;
3320         if (whentohangup) {
3321                 rms = whentohangup;
3322                 if (*ms >= 0 && *ms < rms) {
3323                         rms = *ms;
3324                 }
3325         }
3326
3327         if (*ms > 0) {
3328                 start = ast_tvnow();
3329         }
3330
3331         res = epoll_wait(ast_channel_epfd(c[0]), ev, 25, rms);
3332
3333         for (i = 0; i < n; i++) {
3334                 ast_clear_flag(ast_channel_flags(c[i]), AST_FLAG_BLOCKING);
3335         }
3336
3337         if (res < 0) {
3338                 if (errno != EINTR) {
3339                         *ms = -1;
3340                 }
3341                 return NULL;
3342         }
3343
3344         if (whentohangup) {
3345                 now = ast_tvnow();
3346                 for (i = 0; i < n; i++) {
3347                         if (!ast_tvzero(*ast_channel_whentohangup(c[i])) && ast_tvdiff_ms(now, *ast_channel_whentohangup(c[i])) >= 0) {
3348                                 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3349                                 if (!winner) {
3350                                         winner = c[i];
3351                                 }
3352                         }
3353                 }
3354         }
3355
3356         if (!res) {
3357                 *ms = 0;
3358                 return winner;
3359         }
3360
3361         for (i = 0; i < res; i++) {
3362                 struct ast_epoll_data *aed = ev[i].data.ptr;
3363
3364                 if (!ev[i].events || !aed) {
3365                         continue;
3366                 }
3367
3368                 winner = aed->chan;
3369                 if (ev[i].events & EPOLLPRI) {
3370                         ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3371                 } else {
3372                         ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3373                 }
3374                 ast_channel_fdno_set(winner, aed->which);
3375         }
3376
3377         if (*ms > 0) {
3378                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3379                 if (*ms < 0) {
3380                         *ms = 0;
3381                 }
3382         }
3383
3384         return winner;
3385 }
3386
3387 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3388                                         int *exception, int *outfd, int *ms)
3389 {
3390         /* Clear all provided values in one place. */
3391         if (outfd) {
3392                 *outfd = -99999;
3393         }
3394         if (exception) {
3395                 *exception = 0;
3396         }
3397
3398         /* If no epoll file descriptor is available resort to classic nandfds */
3399         if (!n || nfds || ast_channel_epfd(c[0]) == -1) {
3400                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3401         } else if (!nfds && n == 1) {
3402                 return ast_waitfor_nandfds_simple(c[0], ms);
3403         } else {
3404                 return ast_waitfor_nandfds_complex(c, n, ms);
3405         }
3406 }
3407 #endif
3408
3409 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3410 {
3411         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3412 }
3413
3414 int ast_waitfor(struct ast_channel *c, int ms)
3415 {
3416         if (ms < 0) {
3417                 do {
3418                         ms = 100000;
3419                         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3420                 } while (!ms);
3421         } else {
3422                 ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3423         }
3424         return ms;
3425 }
3426
3427 int ast_waitfordigit(struct ast_channel *c, int ms)
3428 {
3429         return ast_waitfordigit_full(c, ms, -1, -1);
3430 }
3431
3432 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3433 {
3434         int res;
3435         unsigned int real_rate = rate, max_rate;
3436
3437         ast_channel_lock(c);
3438
3439         if (ast_channel_timingfd(c) == -1) {
3440                 ast_channel_unlock(c);
3441                 return -1;
3442         }
3443
3444         if (!func) {
3445                 rate = 0;
3446                 data = NULL;
3447         }
3448
3449         if (rate && rate > (max_rate = ast_timer_get_max_rate(ast_channel_timer(c)))) {
3450                 real_rate = max_rate;
3451         }
3452
3453         ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3454
3455         res = ast_timer_set_rate(ast_channel_timer(c), real_rate);
3456
3457         ast_channel_timingfunc_set(c, func);
3458         ast_channel_timingdata_set(c, data);
3459
3460         if (func == NULL && rate == 0 && ast_channel_fdno(c) == AST_TIMING_FD) {
3461                 /* Clearing the timing func and setting the rate to 0
3462                  * means that we don't want to be reading from the timingfd
3463                  * any more. Setting c->fdno to -1 means we won't have any
3464                  * errant reads from the timingfd, meaning we won't potentially
3465                  * miss any important frames.
3466                  */
3467                 ast_channel_fdno_set(c, -1);
3468         }
3469
3470         ast_channel_unlock(c);
3471
3472         return res;
3473 }
3474
3475 int ast_waitfordigit_full(struct ast_channel *c, int timeout_ms, int audiofd, int cmdfd)
3476 {
3477         struct timeval start = ast_tvnow();
3478         int ms;
3479
3480         /* Stop if we're a zombie or need a soft hangup */
3481         if (ast_test_flag(ast_channel_flags(c), AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3482                 return -1;
3483
3484         /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3485         ast_set_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3486
3487         /* Wait for a digit, no more than timeout_ms milliseconds total.
3488          * Or, wait indefinitely if timeout_ms is <0.
3489          */
3490         while ((ms = ast_remaining_ms(start, timeout_ms))) {
3491                 struct ast_channel *rchan;
3492                 int outfd = -1;
3493
3494                 errno = 0;
3495                 /* While ast_waitfor_nandfds tries to help by reducing the timeout by how much was waited,
3496                  * it is unhelpful if it waited less than a millisecond.
3497                  */
3498                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3499
3500                 if (!rchan && outfd < 0 && ms) {
3501                         if (errno == 0 || errno == EINTR)
3502                                 continue;
3503                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
3504                         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3505                         return -1;
3506                 } else if (outfd > -1) {
3507                         /* The FD we were watching has something waiting */
3508                         ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
3509                         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3510                         return 1;
3511                 } else if (rchan) {
3512                         int res;
3513                         struct ast_frame *f = ast_read(c);
3514                         if (!f)
3515                                 return -1;
3516
3517                         switch (f->frametype) {
3518                         case AST_FRAME_DTMF_BEGIN:
3519                                 break;
3520                         case AST_FRAME_DTMF_END:
3521                                 res = f->subclass.integer;
3522                                 ast_frfree(f);
3523                                 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3524                                 return res;
3525                         case AST_FRAME_CONTROL:
3526                                 switch (f->subclass.integer) {
3527                                 case AST_CONTROL_HANGUP:
3528                                         ast_frfree(f);
3529                                         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3530                                         return -1;
3531                                 case AST_CONTROL_STREAM_STOP:
3532                                 case AST_CONTROL_STREAM_SUSPEND:
3533                                 case AST_CONTROL_STREAM_RESTART:
3534                                 case AST_CONTROL_STREAM_REVERSE:
3535                                 case AST_CONTROL_STREAM_FORWARD:
3536                                         /* Fall-through and treat as if it were a DTMF signal. Items
3537                                          * that perform stream control will handle this. */
3538                                         res = f->subclass.integer;
3539                                         ast_frfree(f);
3540                                         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3541                                         return res;
3542                                 case AST_CONTROL_PVT_CAUSE_CODE:
3543                                 case AST_CONTROL_RINGING:
3544                                 case AST_CONTROL_ANSWER:
3545                                 case AST_CONTROL_SRCUPDATE:
3546                                 case AST_CONTROL_SRCCHANGE:
3547                                 case AST_CONTROL_CONNECTED_LINE:
3548                                 case AST_CONTROL_REDIRECTING:
3549                                 case AST_CONTROL_UPDATE_RTP_PEER:
3550                                 case AST_CONTROL_HOLD:
3551                                 case AST_CONTROL_UNHOLD:
3552                                 case -1:
3553                                         /* Unimportant */
3554                                         break;
3555                                 default:
3556                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
3557                                         break;
3558                                 }
3559                                 break;
3560                         case AST_FRAME_VOICE:
3561                                 /* Write audio if appropriate */
3562                                 if (audiofd > -1) {
3563                                         if (write(audiofd, f->data.ptr, f->datalen) < 0) {
3564                                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3565                                         }
3566                                 }
3567                         default:
3568                                 /* Ignore */
3569                                 break;
3570                         }
3571                         ast_frfree(f);
3572                 }
3573         }
3574
3575         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
3576
3577         return 0; /* Time is up */
3578 }
3579
3580 enum DtmfDirection {
3581         DTMF_RECEIVED,
3582         DTMF_SENT
3583 };
3584
3585 static const char *dtmf_direction_to_string(enum DtmfDirection direction)
3586 {
3587         switch (direction) {
3588         case DTMF_RECEIVED:
3589                 return "Received";
3590         case DTMF_SENT:
3591                 return "Sent";
3592         }
3593
3594         return "?";
3595 }
3596
3597 static void send_dtmf_begin_event(struct ast_channel *chan,
3598         enum DtmfDirection direction, const char digit)
3599 {
3600         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
3601         char digit_str[] = { digit, '\0' };
3602
3603         blob = ast_json_pack("{ s: s, s: s }",
3604                 "digit", digit_str,
3605                 "direction", dtmf_direction_to_string(direction));
3606         if (!blob) {
3607                 return;
3608         }
3609
3610         ast_channel_publish_blob(chan, ast_channel_dtmf_begin_type(), blob);
3611 }
3612
3613 static void send_dtmf_end_event(struct ast_channel *chan,
3614         enum DtmfDirection direction, const char digit, long duration_ms)
3615 {
3616         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
3617         char digit_str[] = { digit, '\0' };
3618
3619         blob = ast_json_pack("{ s: s, s: s, s: i }",
3620                 "digit", digit_str,
3621                 "direction", dtmf_direction_to_string(direction),
3622                 "duration_ms", duration_ms);
3623         if (!blob) {
3624                 return;
3625         }
3626
3627         ast_channel_publish_blob(chan, ast_channel_dtmf_end_type(), blob);
3628 }
3629
3630 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
3631 {
3632         if (ast_channel_generator(chan) && ast_channel_generator(chan)->generate && ast_channel_generatordata(chan) &&  !ast_internal_timing_enabled(chan)) {
3633                 void *tmp = ast_channel_generatordata(chan);
3634                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = ast_channel_generator(chan)->generate;
3635                 int res;
3636                 int samples;
3637
3638                 if (ast_channel_timingfunc(chan)) {
3639                         ast_debug(1, "Generator got voice, switching to phase locked mode\n");
3640                         ast_settimeout(chan, 0, NULL, NULL);
3641                 }
3642
3643                 ast_channel_generatordata_set(chan, NULL);     /* reset, to let writes go through */
3644
3645                 if (ast_format_cmp(&f->subclass.format, ast_channel_writeformat(chan)) == AST_FORMAT_CMP_NOT_EQUAL) {
3646                         float factor;
3647                         factor = ((float) ast_format_rate(ast_channel_writeformat(chan))) / ((float) ast_format_rate(&f->subclass.format));
3648                         samples = (int) ( ((float) f->samples) * factor );
3649                 } else {
3650                         samples = f->samples;
3651                 }
3652
3653                 /* This unlock is here based on two assumptions that hold true at this point in the
3654                  * code. 1) this function is only called from within __ast_read() and 2) all generators
3655                  * call ast_write() in their generate callback.
3656                  *
3657                  * The reason this is added is so that when ast_write is called, the lock that occurs
3658                  * there will not recursively lock the channel. Doing this will cause intended deadlock
3659                  * avoidance not to work in deeper functions
3660                  */
3661                 ast_channel_unlock(chan);
3662                 res = generate(chan, tmp, f->datalen, samples);
3663                 ast_channel_lock(chan);
3664                 ast_channel_generatordata_set(chan, tmp);
3665                 if (res) {
3666                         ast_debug(1, "Auto-deactivating generator\n");
3667                         ast_deactivate_generator(chan);
3668                 }
3669
3670         } else if (f->frametype == AST_FRAME_CNG) {
3671                 if (ast_channel_generator(chan) && !ast_channel_timingfunc(chan) && (ast_channel_timingfd(chan) > -1)) {
3672                         ast_debug(1, "Generator got CNG, switching to timed mode\n");
3673                         ast_settimeout(chan, 50, generator_force, chan);
3674                 }
3675         }
3676 }
3677
3678 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3679 {
3680         struct ast_frame *fr = ast_channel_dtmff(chan);
3681
3682         fr->frametype = AST_FRAME_DTMF_END;
3683         fr->subclass.integer = f->subclass.integer;
3684         fr->len = f->len;
3685
3686         /* The only time this function will be called is for a frame that just came
3687          * out of the channel driver.  So, we want to stick it on the tail of the
3688          * readq. */
3689
3690         ast_queue_frame(chan, fr);
3691 }
3692
3693 /*!
3694  * \brief Determine whether or not we should ignore DTMF in the readq
3695  */
3696 static inline int should_skip_dtmf(struct ast_channel *chan)
3697 {
3698         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
3699                 /* We're in the middle of emulating a digit, or DTMF has been
3700                  * explicitly deferred.  Skip this digit, then. */
3701                 return 1;
3702         }
3703
3704         if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
3705                         ast_tvdiff_ms(ast_tvnow(), *ast_channel_dtmf_tv(chan)) < AST_MIN_DTMF_GAP) {
3706                 /* We're not in the middle of a digit, but it hasn't been long enough
3707                  * since the last digit, so we'll have to skip DTMF for now. */
3708                 return 1;
3709         }
3710
3711         return 0;
3712 }
3713
3714 /*!
3715  * \brief calculates the number of samples to jump forward with in a monitor stream.
3716
3717  * \note When using ast_seekstream() with the read and write streams of a monitor,
3718  * the number of samples to seek forward must be of the same sample rate as the stream
3719  * or else the jump will not be calculated correctly.
3720  *
3721  * \retval number of samples to seek forward after rate conversion.
3722  */
3723 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
3724 {
3725         int diff = sample_rate - seek_rate;
3726
3727         if (diff > 0) {
3728                 samples = samples / (float) (sample_rate / seek_rate);
3729         } else if (diff < 0) {
3730                 samples = samples * (float) (seek_rate / sample_rate);
3731         }
3732
3733         return samples;
3734 }
3735
3736 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
3737 {
3738         struct ast_frame *f = NULL;     /* the return value */
3739         int prestate;
3740         int cause = 0;
3741
3742         /* this function is very long so make sure there is only one return
3743          * point at the end (there are only two exceptions to this).
3744          */
3745
3746         if (ast_channel_masq(chan)) {
3747                 ast_do_masquerade(chan);
3748                 return &ast_null_frame;
3749         }
3750
3751         /* if here, no masq has happened, lock the channel and proceed */
3752         ast_channel_lock(chan);
3753
3754         /* Stop if we're a zombie or need a soft hangup */
3755         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
3756                 if (ast_channel_generator(chan))
3757                         ast_deactivate_generator(chan);
3758
3759                 /*
3760                  * It is possible for chan->_softhangup to be set and there
3761                  * still be control frames that need to be read.  Instead of
3762                  * just going to 'done' in the case of ast_check_hangup(), we
3763                  * need to queue the end-of-Q frame so that it can mark the end
3764                  * of the read queue.  If there are frames to be read,
3765                  * ast_queue_control() will be called repeatedly, but will only
3766                  * queue the first end-of-Q frame.
3767                  */
3768                 if (ast_channel_softhangup_internal_flag(chan)) {
3769                         ast_queue_control(chan, AST_CONTROL_END_OF_Q);
3770                 } else {
3771                         goto done;
3772                 }
3773         } else {
3774 #ifdef AST_DEVMODE
3775                 /*
3776                  * The ast_waitfor() code records which of the channel's file
3777                  * descriptors reported that data is available.  In theory,
3778                  * ast_read() should only be called after ast_waitfor() reports
3779                  * that a channel has data available for reading.  However,
3780                  * there still may be some edge cases throughout the code where
3781                  * ast_read() is called improperly.  This can potentially cause
3782                  * problems, so if this is a developer build, make a lot of
3783                  * noise if this happens so that it can be addressed.
3784                  *
3785                  * One of the potential problems is blocking on a dead channel.
3786                  */
3787                 if (ast_channel_fdno(chan) == -1) {
3788                         ast_log(LOG_ERROR,
3789                                 "ast_read() on chan '%s' called with no recorded file descriptor.\n",
3790                                 ast_channel_name(chan));
3791                 }
3792 #endif
3793         }
3794
3795         prestate = ast_channel_state(chan);
3796
3797         if (ast_channel_timingfd(chan) > -1 && ast_channel_fdno(chan) == AST_TIMING_FD) {
3798                 enum ast_timer_event res;
3799
3800                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3801
3802                 res = ast_timer_get_event(ast_channel_timer(chan));
3803
3804                 switch (res) {
3805                 case AST_TIMING_EVENT_EXPIRED:
3806                         if (ast_timer_ack(ast_channel_timer(chan), 1) < 0) {
3807                                 ast_log(LOG_ERROR, "Failed to acknoweldge timer in ast_read\n");
3808                                 goto done;
3809                         }
3810
3811                         if (ast_channel_timingfunc(chan)) {
3812                                 /* save a copy of func/data before unlocking the channel */
3813                                 ast_timing_func_t func = ast_channel_timingfunc(chan);
3814                                 void *data = ast_channel_timingdata(chan);
3815                                 ast_channel_fdno_set(chan, -1);
3816                                 ast_channel_unlock(chan);
3817                                 func(data);
3818                         } else {
3819                                 ast_timer_set_rate(ast_channel_timer(chan), 0);
3820                                 ast_channel_fdno_set(chan, -1);
3821                                 ast_channel_unlock(chan);
3822                         }
3823
3824                         /* cannot 'goto done' because the channel is already unlocked */
3825                         return &ast_null_frame;
3826
3827                 case AST_TIMING_EVENT_CONTINUOUS:
3828                         if (AST_LIST_EMPTY(ast_channel_readq(chan)) ||
3829                                 !AST_LIST_NEXT(AST_LIST_FIRST(ast_channel_readq(chan)), frame_list)) {
3830                                 ast_timer_disable_continuous(ast_channel_timer(chan));
3831                         }
3832                         break;
3833                 }
3834
3835         } else if (ast_channel_fd_isset(chan, AST_GENERATOR_FD) && ast_channel_fdno(chan) == AST_GENERATOR_FD) {
3836                 /* if the AST_GENERATOR_FD is set, call the generator with args
3837                  * set to -1 so it can do whatever it needs to.
3838                  */
3839                 void *tmp = ast_channel_generatordata(chan);
3840                 ast_channel_generatordata_set(chan, NULL);     /* reset to let ast_write get through */
3841                 ast_channel_generator(chan)->generate(chan, tmp, -1, -1);
3842                 ast_channel_generatordata_set(chan, tmp);
3843                 f = &ast_null_frame;
3844                 ast_channel_fdno_set(chan, -1);
3845                 goto done;
3846         } else if (ast_channel_fd_isset(chan, AST_JITTERBUFFER_FD) && ast_channel_fdno(chan) == AST_JITTERBUFFER_FD) {
3847                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3848         }
3849
3850         /* Read and ignore anything on the alertpipe, but read only
3851            one sizeof(blah) per frame that we send from it */
3852         if (ast_channel_internal_alert_read(chan) == AST_ALERT_READ_FATAL) {
3853                 f = &ast_null_frame;
3854                 goto done;
3855         }
3856
3857         /* Check for pending read queue */
3858         if (!AST_LIST_EMPTY(ast_channel_readq(chan))) {
3859                 int skip_dtmf = should_skip_dtmf(chan);
3860
3861                 AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), f, frame_list) {
3862                         /* We have to be picky about which frame we pull off of the readq because
3863                          * there are cases where we want to leave DTMF frames on the queue until
3864                          * some later time. */
3865
3866                         if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
3867                                 continue;
3868                         }
3869
3870                         AST_LIST_REMOVE_CURRENT(frame_list);
3871  &