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