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