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