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