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