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