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