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