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