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