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