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