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