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