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