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