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