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