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