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