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