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