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