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