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