469e97bad0419f359c5864c8eb4b686f05b94f2e
[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         /* Yeah, let's not change a lock-critical value without locking */
1317         if (!ast_channel_trylock(chan)) {
1318                 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1319                 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1320                         "Channel: %s\r\n"
1321                         "Uniqueid: %s\r\n",
1322                         ast_channel_name(chan),
1323                         ast_channel_uniqueid(chan));
1324                 ast_channel_unlock(chan);
1325         }
1326         return ast_queue_frame(chan, &f);
1327 }
1328
1329 /*! \brief Queue a hangup frame for channel */
1330 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1331 {
1332         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1333
1334         if (cause >= 0)
1335                 f.data.uint32 = cause;
1336
1337         /* Yeah, let's not change a lock-critical value without locking */
1338         if (!ast_channel_trylock(chan)) {
1339                 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1340                 if (cause < 0)
1341                         f.data.uint32 = ast_channel_hangupcause(chan);
1342
1343                 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1344                         "Channel: %s\r\n"
1345                         "Uniqueid: %s\r\n"
1346                         "Cause: %d\r\n",
1347                         ast_channel_name(chan),
1348                         ast_channel_uniqueid(chan),
1349                         cause);
1350                 ast_channel_unlock(chan);
1351         }
1352
1353         return ast_queue_frame(chan, &f);
1354 }
1355
1356 /*! \brief Queue a control frame */
1357 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1358 {
1359         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1360         return ast_queue_frame(chan, &f);
1361 }
1362
1363 /*! \brief Queue a control frame with payload */
1364 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1365                            const void *data, size_t datalen)
1366 {
1367         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1368         return ast_queue_frame(chan, &f);
1369 }
1370
1371 /*! \brief Set defer DTMF flag on channel */
1372 int ast_channel_defer_dtmf(struct ast_channel *chan)
1373 {
1374         int pre = 0;
1375
1376         if (chan) {
1377                 pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1378                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1379         }
1380         return pre;
1381 }
1382
1383 /*! \brief Unset defer DTMF flag on channel */
1384 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1385 {
1386         if (chan)
1387                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
1388 }
1389
1390 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1391                 void *data, int ao2_flags)
1392 {
1393         return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1394 }
1395
1396 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1397 {
1398         struct ast_channel *chan = obj;
1399         const char *name = arg;
1400         size_t name_len = *(size_t *) data;
1401         int ret = CMP_MATCH;
1402
1403         if (ast_strlen_zero(name)) {
1404                 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1405                 return CMP_STOP;
1406         }
1407
1408         ast_channel_lock(chan);
1409         if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1410                 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1411                 ret = 0; /* name match failed, keep looking */
1412         }
1413         ast_channel_unlock(chan);
1414
1415         return ret;
1416 }
1417
1418 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1419 {
1420         struct ast_channel *chan = obj;
1421         char *context = arg;
1422         char *exten = data;
1423         int ret = CMP_MATCH;
1424
1425         if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1426                 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1427                 return CMP_STOP;
1428         }
1429
1430         ast_channel_lock(chan);
1431         if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1432                 ret = 0; /* Context match failed, continue */
1433         } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1434                 ret = 0; /* Extension match failed, continue */
1435         }
1436         ast_channel_unlock(chan);
1437
1438         return ret;
1439 }
1440
1441 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1442 {
1443         struct ast_channel *chan = obj;
1444         char *uniqueid = arg;
1445         size_t id_len = *(size_t *) data;
1446         int ret = CMP_MATCH;
1447
1448         if (ast_strlen_zero(uniqueid)) {
1449                 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1450                 return CMP_STOP;
1451         }
1452
1453         ast_channel_lock(chan);
1454         if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1455                 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1456                 ret = 0; /* uniqueid match failed, keep looking */
1457         }
1458         ast_channel_unlock(chan);
1459
1460         return ret;
1461 }
1462
1463 struct ast_channel_iterator {
1464         /* storage for non-dynamically allocated iterator */
1465         struct ao2_iterator simple_iterator;
1466         /* pointer to the actual iterator (simple_iterator or a dynamically
1467          * allocated iterator)
1468          */
1469         struct ao2_iterator *active_iterator;
1470 };
1471
1472 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1473 {
1474         ao2_iterator_destroy(i->active_iterator);
1475         ast_free(i);
1476
1477         return NULL;
1478 }
1479
1480 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1481 {
1482         struct ast_channel_iterator *i;
1483         char *l_exten = (char *) exten;
1484         char *l_context = (char *) context;
1485
1486         if (!(i = ast_calloc(1, sizeof(*i)))) {
1487                 return NULL;
1488         }
1489
1490         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1491                 l_context, l_exten, OBJ_MULTIPLE);
1492         if (!i->active_iterator) {
1493                 ast_free(i);
1494                 return NULL;
1495         }
1496
1497         return i;
1498 }
1499
1500 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1501 {
1502         struct ast_channel_iterator *i;
1503         char *l_name = (char *) name;
1504
1505         if (!(i = ast_calloc(1, sizeof(*i)))) {
1506                 return NULL;
1507         }
1508
1509         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1510                 l_name, &name_len,
1511                 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1512         if (!i->active_iterator) {
1513                 ast_free(i);
1514                 return NULL;
1515         }
1516
1517         return i;
1518 }
1519
1520 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1521 {
1522         struct ast_channel_iterator *i;
1523
1524         if (!(i = ast_calloc(1, sizeof(*i)))) {
1525                 return NULL;
1526         }
1527
1528         i->simple_iterator = ao2_iterator_init(channels, 0);
1529         i->active_iterator = &i->simple_iterator;
1530
1531         return i;
1532 }
1533
1534 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1535 {
1536         return ao2_iterator_next(i->active_iterator);
1537 }
1538
1539 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1540 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1541 {
1542         ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1543         return CMP_STOP;
1544 }
1545
1546 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1547 {
1548         struct ast_channel *chan;
1549         char *l_name = (char *) name;
1550
1551         chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1552                 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1553         if (chan) {
1554                 return chan;
1555         }
1556
1557         if (ast_strlen_zero(l_name)) {
1558                 /* We didn't have a name to search for so quit. */
1559                 return NULL;
1560         }
1561
1562         /* Now try a search for uniqueid. */
1563         return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1564 }
1565
1566 struct ast_channel *ast_channel_get_by_name(const char *name)
1567 {
1568         return ast_channel_get_by_name_prefix(name, 0);
1569 }
1570
1571 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1572 {
1573         char *l_exten = (char *) exten;
1574         char *l_context = (char *) context;
1575
1576         return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1577 }
1578
1579 int ast_is_deferrable_frame(const struct ast_frame *frame)
1580 {
1581         /* Do not add a default entry in this switch statement.  Each new
1582          * frame type should be addressed directly as to whether it should
1583          * be queued up or not.
1584          */
1585         switch (frame->frametype) {
1586         case AST_FRAME_CONTROL:
1587         case AST_FRAME_TEXT:
1588         case AST_FRAME_IMAGE:
1589         case AST_FRAME_HTML:
1590                 return 1;
1591
1592         case AST_FRAME_DTMF_END:
1593         case AST_FRAME_DTMF_BEGIN:
1594         case AST_FRAME_VOICE:
1595         case AST_FRAME_VIDEO:
1596         case AST_FRAME_NULL:
1597         case AST_FRAME_IAX:
1598         case AST_FRAME_CNG:
1599         case AST_FRAME_MODEM:
1600                 return 0;
1601         }
1602         return 0;
1603 }
1604
1605 /*! \brief Wait, look for hangups and condition arg */
1606 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1607 {
1608         struct ast_frame *f;
1609         struct ast_silence_generator *silgen = NULL;
1610         int res = 0;
1611         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1612
1613         AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1614
1615         /* If no other generator is present, start silencegen while waiting */
1616         if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
1617                 silgen = ast_channel_start_silence_generator(chan);
1618         }
1619
1620         while (ms > 0) {
1621                 struct ast_frame *dup_f = NULL;
1622                 if (cond && ((*cond)(data) == 0)) {
1623                         break;
1624                 }
1625                 ms = ast_waitfor(chan, ms);
1626                 if (ms < 0) {
1627                         res = -1;
1628                         break;
1629                 }
1630                 if (ms > 0) {
1631                         f = ast_read(chan);
1632                         if (!f) {
1633                                 res = -1;
1634                                 break;
1635                         }
1636
1637                         if (!ast_is_deferrable_frame(f)) {
1638                                 ast_frfree(f);
1639                                 continue;
1640                         }
1641
1642                         if ((dup_f = ast_frisolate(f))) {
1643                                 if (dup_f != f) {
1644                                         ast_frfree(f);
1645                                 }
1646                                 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1647                         }
1648                 }
1649         }
1650
1651         /* stop silgen if present */
1652         if (silgen) {
1653                 ast_channel_stop_silence_generator(chan, silgen);
1654         }
1655
1656         /* We need to free all the deferred frames, but we only need to
1657          * queue the deferred frames if there was no error and no
1658          * hangup was received
1659          */
1660         ast_channel_lock(chan);
1661         while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1662                 if (!res) {
1663                         ast_queue_frame_head(chan, f);
1664                 }
1665                 ast_frfree(f);
1666         }
1667         ast_channel_unlock(chan);
1668
1669         return res;
1670 }
1671
1672 /*! \brief Wait, look for hangups */
1673 int ast_safe_sleep(struct ast_channel *chan, int ms)
1674 {
1675         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1676 }
1677
1678 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1679 {
1680         /* Safe, even if already unlinked. */
1681         ao2_unlink(channels, chan);
1682         return ast_channel_unref(chan);
1683 }
1684
1685 void ast_party_name_init(struct ast_party_name *init)
1686 {
1687         init->str = NULL;
1688         init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1689         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1690         init->valid = 0;
1691 }
1692
1693 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1694 {
1695         if (dest == src) {
1696                 /* Don't copy to self */
1697                 return;
1698         }
1699
1700         ast_free(dest->str);
1701         dest->str = ast_strdup(src->str);
1702         dest->char_set = src->char_set;
1703         dest->presentation = src->presentation;
1704         dest->valid = src->valid;
1705 }
1706
1707 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1708 {
1709         init->str = NULL;
1710         init->char_set = guide->char_set;
1711         init->presentation = guide->presentation;
1712         init->valid = guide->valid;
1713 }
1714
1715 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1716 {
1717         if (dest == src) {
1718                 /* Don't set to self */
1719                 return;
1720         }
1721
1722         if (src->str && src->str != dest->str) {
1723                 ast_free(dest->str);
1724                 dest->str = ast_strdup(src->str);
1725         }
1726
1727         dest->char_set = src->char_set;
1728         dest->presentation = src->presentation;
1729         dest->valid = src->valid;
1730 }
1731
1732 void ast_party_name_free(struct ast_party_name *doomed)
1733 {
1734         ast_free(doomed->str);
1735         doomed->str = NULL;
1736 }
1737
1738 void ast_party_number_init(struct ast_party_number *init)
1739 {
1740         init->str = NULL;
1741         init->plan = 0;/* Unknown */
1742         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1743         init->valid = 0;
1744 }
1745
1746 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1747 {
1748         if (dest == src) {
1749                 /* Don't copy to self */
1750                 return;
1751         }
1752
1753         ast_free(dest->str);
1754         dest->str = ast_strdup(src->str);
1755         dest->plan = src->plan;
1756         dest->presentation = src->presentation;
1757         dest->valid = src->valid;
1758 }
1759
1760 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1761 {
1762         init->str = NULL;
1763         init->plan = guide->plan;
1764         init->presentation = guide->presentation;
1765         init->valid = guide->valid;
1766 }
1767
1768 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1769 {
1770         if (dest == src) {
1771                 /* Don't set to self */
1772                 return;
1773         }
1774
1775         if (src->str && src->str != dest->str) {
1776                 ast_free(dest->str);
1777                 dest->str = ast_strdup(src->str);
1778         }
1779
1780         dest->plan = src->plan;
1781         dest->presentation = src->presentation;
1782         dest->valid = src->valid;
1783 }
1784
1785 void ast_party_number_free(struct ast_party_number *doomed)
1786 {
1787         ast_free(doomed->str);
1788         doomed->str = NULL;
1789 }
1790
1791 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1792 {
1793         init->str = NULL;
1794         init->type = 0;
1795         init->odd_even_indicator = 0;
1796         init->valid = 0;
1797 }
1798
1799 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1800 {
1801         if (dest == src) {
1802                 /* Don't copy to self */
1803                 return;
1804         }
1805
1806         ast_free(dest->str);
1807         dest->str = ast_strdup(src->str);
1808         dest->type = src->type;
1809         dest->odd_even_indicator = src->odd_even_indicator;
1810         dest->valid = src->valid;
1811 }
1812
1813 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1814 {
1815         init->str = NULL;
1816         init->type = guide->type;
1817         init->odd_even_indicator = guide->odd_even_indicator;
1818         init->valid = guide->valid;
1819 }
1820
1821 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1822 {
1823         if (dest == src) {
1824                 /* Don't set to self */
1825                 return;
1826         }
1827
1828         if (src->str && src->str != dest->str) {
1829                 ast_free(dest->str);
1830                 dest->str = ast_strdup(src->str);
1831         }
1832
1833         dest->type = src->type;
1834         dest->odd_even_indicator = src->odd_even_indicator;
1835         dest->valid = src->valid;
1836 }
1837
1838 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1839 {
1840         ast_free(doomed->str);
1841         doomed->str = NULL;
1842 }
1843
1844 void ast_party_id_init(struct ast_party_id *init)
1845 {
1846         ast_party_name_init(&init->name);
1847         ast_party_number_init(&init->number);
1848         ast_party_subaddress_init(&init->subaddress);
1849         init->tag = NULL;
1850 }
1851
1852 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1853 {
1854         if (dest == src) {
1855                 /* Don't copy to self */
1856                 return;
1857         }
1858
1859         ast_party_name_copy(&dest->name, &src->name);
1860         ast_party_number_copy(&dest->number, &src->number);
1861         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1862
1863         ast_free(dest->tag);
1864         dest->tag = ast_strdup(src->tag);
1865 }
1866
1867 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1868 {
1869         ast_party_name_set_init(&init->name, &guide->name);
1870         ast_party_number_set_init(&init->number, &guide->number);
1871         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1872         init->tag = NULL;
1873 }
1874
1875 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1876 {
1877         if (dest == src) {
1878                 /* Don't set to self */
1879                 return;
1880         }
1881
1882         if (!update || update->name) {
1883                 ast_party_name_set(&dest->name, &src->name);
1884         }
1885         if (!update || update->number) {
1886                 ast_party_number_set(&dest->number, &src->number);
1887         }
1888         if (!update || update->subaddress) {
1889                 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1890         }
1891
1892         if (src->tag && src->tag != dest->tag) {
1893                 ast_free(dest->tag);
1894                 dest->tag = ast_strdup(src->tag);
1895         }
1896 }
1897
1898 void ast_party_id_free(struct ast_party_id *doomed)
1899 {
1900         ast_party_name_free(&doomed->name);
1901         ast_party_number_free(&doomed->number);
1902         ast_party_subaddress_free(&doomed->subaddress);
1903
1904         ast_free(doomed->tag);
1905         doomed->tag = NULL;
1906 }
1907
1908 int ast_party_id_presentation(const struct ast_party_id *id)
1909 {
1910         int number_priority;
1911         int number_value;
1912         int number_screening;
1913         int name_priority;
1914         int name_value;
1915
1916         /* Determine name presentation priority. */
1917         if (!id->name.valid) {
1918                 name_value = AST_PRES_UNAVAILABLE;
1919                 name_priority = 3;
1920         } else {
1921                 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1922                 switch (name_value) {
1923                 case AST_PRES_RESTRICTED:
1924                         name_priority = 0;
1925                         break;
1926                 case AST_PRES_ALLOWED:
1927                         name_priority = 1;
1928                         break;
1929                 case AST_PRES_UNAVAILABLE:
1930                         name_priority = 2;
1931                         break;
1932                 default:
1933                         name_value = AST_PRES_UNAVAILABLE;
1934                         name_priority = 3;
1935                         break;
1936                 }
1937         }
1938
1939         /* Determine number presentation priority. */
1940         if (!id->number.valid) {
1941                 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1942                 number_value = AST_PRES_UNAVAILABLE;
1943                 number_priority = 3;
1944         } else {
1945                 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1946                 number_value = id->number.presentation & AST_PRES_RESTRICTION;
1947                 switch (number_value) {
1948                 case AST_PRES_RESTRICTED:
1949                         number_priority = 0;
1950                         break;
1951                 case AST_PRES_ALLOWED:
1952                         number_priority = 1;
1953                         break;
1954                 case AST_PRES_UNAVAILABLE:
1955                         number_priority = 2;
1956                         break;
1957                 default:
1958                         number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1959                         number_value = AST_PRES_UNAVAILABLE;
1960                         number_priority = 3;
1961                         break;
1962                 }
1963         }
1964
1965         /* Select the wining presentation value. */
1966         if (name_priority < number_priority) {
1967                 number_value = name_value;
1968         }
1969         if (number_value == AST_PRES_UNAVAILABLE) {
1970                 return AST_PRES_NUMBER_NOT_AVAILABLE;
1971         }
1972
1973         return number_value | number_screening;
1974 }
1975
1976 void ast_party_dialed_init(struct ast_party_dialed *init)
1977 {
1978         init->number.str = NULL;
1979         init->number.plan = 0;/* Unknown */
1980         ast_party_subaddress_init(&init->subaddress);
1981         init->transit_network_select = 0;
1982 }
1983
1984 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1985 {
1986         if (dest == src) {
1987                 /* Don't copy to self */
1988                 return;
1989         }
1990
1991         ast_free(dest->number.str);
1992         dest->number.str = ast_strdup(src->number.str);
1993         dest->number.plan = src->number.plan;
1994         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1995         dest->transit_network_select = src->transit_network_select;
1996 }
1997
1998 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
1999 {
2000         init->number.str = NULL;
2001         init->number.plan = guide->number.plan;
2002         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2003         init->transit_network_select = guide->transit_network_select;
2004 }
2005
2006 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2007 {
2008         if (src->number.str && src->number.str != dest->number.str) {
2009                 ast_free(dest->number.str);
2010                 dest->number.str = ast_strdup(src->number.str);
2011         }
2012         dest->number.plan = src->number.plan;
2013
2014         ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2015
2016         dest->transit_network_select = src->transit_network_select;
2017 }
2018
2019 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2020 {
2021         ast_free(doomed->number.str);
2022         doomed->number.str = NULL;
2023         ast_party_subaddress_free(&doomed->subaddress);
2024 }
2025
2026 void ast_party_caller_init(struct ast_party_caller *init)
2027 {
2028         ast_party_id_init(&init->id);
2029         ast_party_id_init(&init->ani);
2030         init->ani2 = 0;
2031 }
2032
2033 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2034 {
2035         if (dest == src) {
2036                 /* Don't copy to self */
2037                 return;
2038         }
2039
2040         ast_party_id_copy(&dest->id, &src->id);
2041         ast_party_id_copy(&dest->ani, &src->ani);
2042         dest->ani2 = src->ani2;
2043 }
2044
2045 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2046 {
2047         ast_party_id_set_init(&init->id, &guide->id);
2048         ast_party_id_set_init(&init->ani, &guide->ani);
2049         init->ani2 = guide->ani2;
2050 }
2051
2052 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2053 {
2054         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2055         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2056         dest->ani2 = src->ani2;
2057 }
2058
2059 void ast_party_caller_free(struct ast_party_caller *doomed)
2060 {
2061         ast_party_id_free(&doomed->id);
2062         ast_party_id_free(&doomed->ani);
2063 }
2064
2065 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2066 {
2067         ast_party_id_init(&init->id);
2068         ast_party_id_init(&init->ani);
2069         init->ani2 = 0;
2070         init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2071 }
2072
2073 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2074 {
2075         if (dest == src) {
2076                 /* Don't copy to self */
2077                 return;
2078         }
2079
2080         ast_party_id_copy(&dest->id, &src->id);
2081         ast_party_id_copy(&dest->ani, &src->ani);
2082         dest->ani2 = src->ani2;
2083         dest->source = src->source;
2084 }
2085
2086 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2087 {
2088         ast_party_id_set_init(&init->id, &guide->id);
2089         ast_party_id_set_init(&init->ani, &guide->ani);
2090         init->ani2 = guide->ani2;
2091         init->source = guide->source;
2092 }
2093
2094 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)
2095 {
2096         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2097         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2098         dest->ani2 = src->ani2;
2099         dest->source = src->source;
2100 }
2101
2102 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2103 {
2104         connected->id = caller->id;
2105         connected->ani = caller->ani;
2106         connected->ani2 = caller->ani2;
2107         connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2108 }
2109
2110 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2111 {
2112         ast_party_id_free(&doomed->id);
2113         ast_party_id_free(&doomed->ani);
2114 }
2115
2116 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2117 {
2118         ast_party_id_init(&init->orig);
2119         ast_party_id_init(&init->from);
2120         ast_party_id_init(&init->to);
2121         init->count = 0;
2122         init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2123         init->orig_reason = AST_REDIRECTING_REASON_UNKNOWN;
2124 }
2125
2126 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2127 {
2128         if (dest == src) {
2129                 /* Don't copy to self */
2130                 return;
2131         }
2132
2133         ast_party_id_copy(&dest->orig, &src->orig);
2134         ast_party_id_copy(&dest->from, &src->from);
2135         ast_party_id_copy(&dest->to, &src->to);
2136         dest->count = src->count;
2137         dest->reason = src->reason;
2138         dest->orig_reason = src->orig_reason;
2139 }
2140
2141 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2142 {
2143         ast_party_id_set_init(&init->orig, &guide->orig);
2144         ast_party_id_set_init(&init->from, &guide->from);
2145         ast_party_id_set_init(&init->to, &guide->to);
2146         init->count = guide->count;
2147         init->reason = guide->reason;
2148         init->orig_reason = guide->orig_reason;
2149 }
2150
2151 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2152 {
2153         ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
2154         ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2155         ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2156         dest->count = src->count;
2157         dest->reason = src->reason;
2158         dest->orig_reason = src->orig_reason;
2159 }
2160
2161 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2162 {
2163         ast_party_id_free(&doomed->orig);
2164         ast_party_id_free(&doomed->from);
2165         ast_party_id_free(&doomed->to);
2166 }
2167
2168 /*! \brief Free a channel structure */
2169 static void ast_channel_destructor(void *obj)
2170 {
2171         struct ast_channel *chan = obj;
2172 #ifdef HAVE_EPOLL
2173         int i;
2174 #endif
2175         struct ast_var_t *vardata;
2176         struct ast_frame *f;
2177         struct varshead *headp;
2178         struct ast_datastore *datastore;
2179         char device_name[AST_CHANNEL_NAME];
2180         struct ast_callid *callid;
2181
2182         if (ast_channel_internal_is_finalized(chan)) {
2183                 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2184                 ast_cel_check_retire_linkedid(chan);
2185         }
2186
2187         /* Get rid of each of the data stores on the channel */
2188         ast_channel_lock(chan);
2189         while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
2190                 /* Free the data store */
2191                 ast_datastore_free(datastore);
2192
2193         /* While the channel is locked, take the reference to its callid while we tear down the call. */
2194         callid = ast_channel_callid(chan);
2195         ast_channel_callid_cleanup(chan);
2196
2197         ast_channel_unlock(chan);
2198
2199         /* Lock and unlock the channel just to be sure nobody has it locked still
2200            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2201         ast_channel_lock(chan);
2202         ast_channel_unlock(chan);
2203
2204         if (ast_channel_tech_pvt(chan)) {
2205                 ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2206                 ast_free(ast_channel_tech_pvt(chan));
2207         }
2208
2209         if (ast_channel_sched(chan)) {
2210                 ast_sched_context_destroy(ast_channel_sched(chan));
2211         }
2212
2213         if (ast_channel_internal_is_finalized(chan)) {
2214                 char *dashptr;
2215
2216                 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2217                 if ((dashptr = strrchr(device_name, '-'))) {
2218                         *dashptr = '\0';
2219                 }
2220         } else {
2221                 device_name[0] = '\0';
2222         }
2223
2224         /* Stop monitoring */
2225         if (ast_channel_monitor(chan))
2226                 ast_channel_monitor(chan)->stop( chan, 0 );
2227
2228         /* If there is native format music-on-hold state, free it */
2229         if (ast_channel_music_state(chan))
2230                 ast_moh_cleanup(chan);
2231
2232         /* Free translators */
2233         if (ast_channel_readtrans(chan))
2234                 ast_translator_free_path(ast_channel_readtrans(chan));
2235         if (ast_channel_writetrans(chan))
2236                 ast_translator_free_path(ast_channel_writetrans(chan));
2237         if (ast_channel_pbx(chan))
2238                 ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2239
2240         ast_party_dialed_free(ast_channel_dialed(chan));
2241         ast_party_caller_free(ast_channel_caller(chan));
2242         ast_party_connected_line_free(ast_channel_connected(chan));
2243         ast_party_redirecting_free(ast_channel_redirecting(chan));
2244
2245         /* Close pipes if appropriate */
2246         ast_channel_internal_alertpipe_close(chan);
2247         if (ast_channel_timer(chan)) {
2248                 ast_timer_close(ast_channel_timer(chan));
2249         }
2250 #ifdef HAVE_EPOLL
2251         for (i = 0; i < AST_MAX_FDS; i++) {
2252                 if (ast_channel_internal_epfd_data(chan, i)) {
2253                         ast_free(ast_channel_internal_epfd_data(chan, i));
2254                 }
2255         }
2256         close(ast_channel_epfd(chan));
2257 #endif
2258         while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
2259                 ast_frfree(f);
2260
2261         /* loop over the variables list, freeing all data and deleting list items */
2262         /* no need to lock the list, as the channel is already locked */
2263         headp = ast_channel_varshead(chan);
2264         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2265                 ast_var_delete(vardata);
2266
2267         ast_app_group_discard(chan);
2268
2269         /* Destroy the jitterbuffer */
2270         ast_jb_destroy(chan);
2271
2272         if (ast_channel_cdr(chan)) {
2273                 ast_cdr_discard(ast_channel_cdr(chan));
2274                 ast_channel_cdr_set(chan, NULL);
2275         }
2276
2277         if (ast_channel_zone(chan)) {
2278                 ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
2279         }
2280
2281         ast_channel_internal_cleanup(chan);
2282
2283         if (device_name[0]) {
2284                 /*
2285                  * We have a device name to notify of a new state.
2286                  *
2287                  * Queue an unknown state, because, while we know that this particular
2288                  * instance is dead, we don't know the state of all other possible
2289                  * instances.
2290                  */
2291                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2292         }
2293
2294         ast_channel_nativeformats_set(chan, ast_format_cap_destroy(ast_channel_nativeformats(chan)));
2295         if (callid) {
2296                 ast_callid_unref(callid);
2297         }
2298 }
2299
2300 /*! \brief Free a dummy channel structure */
2301 static void ast_dummy_channel_destructor(void *obj)
2302 {
2303         struct ast_channel *chan = obj;
2304         struct ast_var_t *vardata;
2305         struct varshead *headp;
2306
2307         headp = ast_channel_varshead(chan);
2308
2309         ast_party_dialed_free(ast_channel_dialed(chan));
2310         ast_party_caller_free(ast_channel_caller(chan));
2311         ast_party_connected_line_free(ast_channel_connected(chan));
2312         ast_party_redirecting_free(ast_channel_redirecting(chan));
2313
2314         /* loop over the variables list, freeing all data and deleting list items */
2315         /* no need to lock the list, as the channel is already locked */
2316         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2317                 ast_var_delete(vardata);
2318
2319         if (ast_channel_cdr(chan)) {
2320                 ast_cdr_discard(ast_channel_cdr(chan));
2321                 ast_channel_cdr_set(chan, NULL);
2322         }
2323
2324         ast_channel_internal_cleanup(chan);
2325 }
2326
2327 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2328 {
2329         return ast_datastore_alloc(info, uid);
2330 }
2331
2332 int ast_channel_datastore_free(struct ast_datastore *datastore)
2333 {
2334         return ast_datastore_free(datastore);
2335 }
2336
2337 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2338 {
2339         struct ast_datastore *datastore = NULL, *datastore2;
2340
2341         AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
2342                 if (datastore->inheritance > 0) {
2343                         datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2344                         if (datastore2) {
2345                                 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2346                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2347                                 AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
2348                         }
2349                 }
2350         }
2351         return 0;
2352 }
2353
2354 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2355 {
2356         int res = 0;
2357
2358         AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
2359
2360         return res;
2361 }
2362
2363 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2364 {
2365         return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
2366 }
2367
2368 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2369 {
2370         struct ast_datastore *datastore = NULL;
2371
2372         if (info == NULL)
2373                 return NULL;
2374
2375         AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
2376                 if (datastore->info != info) {
2377                         continue;
2378                 }
2379
2380                 if (uid == NULL) {
2381                         /* matched by type only */
2382                         break;
2383                 }
2384
2385                 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2386                         /* Matched by type AND uid */
2387                         break;
2388                 }
2389         }
2390
2391         return datastore;
2392 }
2393
2394 /*! Set the file descriptor on the channel */
2395 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2396 {
2397 #ifdef HAVE_EPOLL
2398         struct epoll_event ev;
2399         struct ast_epoll_data *aed = NULL;
2400
2401         if (ast_channel_fd_isset(chan, which)) {
2402                 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
2403                 aed = ast_channel_internal_epfd_data(chan, which);
2404         }
2405
2406         /* If this new fd is valid, add it to the epoll */
2407         if (fd > -1) {
2408                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2409                         return;
2410
2411                 ast_channel_internal_epfd_data_set(chan, which, aed);
2412                 aed->chan = chan;
2413                 aed->which = which;
2414
2415                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2416                 ev.data.ptr = aed;
2417                 epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
2418         } else if (aed) {
2419                 /* We don't have to keep around this epoll data structure now */
2420                 ast_free(aed);
2421                 ast_channel_epfd_data_set(chan, which, NULL);
2422         }
2423 #endif
2424         ast_channel_internal_fd_set(chan, which, fd);
2425         return;
2426 }
2427
2428 /*! Add a channel to an optimized waitfor */
2429 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2430 {
2431 #ifdef HAVE_EPOLL
2432         struct epoll_event ev;
2433         int i = 0;
2434
2435         if (ast_channel_epfd(chan0) == -1)
2436                 return;
2437
2438         /* Iterate through the file descriptors on chan1, adding them to chan0 */
2439         for (i = 0; i < AST_MAX_FDS; i++) {
2440                 if (!ast_channel_fd_isset(chan1, i)) {
2441                         continue;
2442                 }
2443                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2444                 ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
2445                 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
2446         }
2447
2448 #endif
2449         return;
2450 }
2451
2452 /*! Delete a channel from an optimized waitfor */
2453 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2454 {
2455 #ifdef HAVE_EPOLL
2456         struct epoll_event ev;
2457         int i = 0;
2458
2459         if (ast_channel_epfd(chan0) == -1)
2460                 return;
2461
2462         for (i = 0; i < AST_MAX_FDS; i++) {
2463                 if (!ast_channel_fd_isset(chan1, i)) {
2464                         continue;
2465                 }
2466                 epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
2467         }
2468
2469 #endif
2470         return;
2471 }
2472
2473 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2474 {
2475         ast_channel_lock(chan);
2476
2477         ast_channel_softhangup_internal_flag_clear(chan, flag);
2478
2479         if (!ast_channel_softhangup_internal_flag(chan)) {
2480                 struct ast_frame *fr;
2481
2482                 /* If we have completely cleared the softhangup flag,
2483                  * then we need to fully abort the hangup process.  This requires
2484                  * pulling the END_OF_Q frame out of the channel frame queue if it
2485                  * still happens to be there. */
2486
2487                 fr = AST_LIST_LAST(ast_channel_readq(chan));
2488                 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2489                                 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2490                         AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
2491                         ast_frfree(fr);
2492                 }
2493         }
2494
2495         ast_channel_unlock(chan);
2496 }
2497
2498 /*! \brief Softly hangup a channel, don't lock */
2499 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2500 {
2501         ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2502         /* Inform channel driver that we need to be hung up, if it cares */
2503         ast_channel_softhangup_internal_flag_add(chan, cause);
2504         ast_queue_frame(chan, &ast_null_frame);
2505         /* Interrupt any poll call or such */
2506         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
2507                 pthread_kill(ast_channel_blocker(chan), SIGURG);
2508         return 0;
2509 }
2510
2511 /*! \brief Softly hangup a channel, lock */
2512 int ast_softhangup(struct ast_channel *chan, int cause)
2513 {
2514         int res;
2515
2516         ast_channel_lock(chan);
2517         res = ast_softhangup_nolock(chan, cause);
2518         manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2519                 "Channel: %s\r\n"
2520                 "Uniqueid: %s\r\n"
2521                 "Cause: %d\r\n",
2522                 ast_channel_name(chan),
2523                 ast_channel_uniqueid(chan),
2524                 cause);
2525         ast_channel_unlock(chan);
2526
2527         return res;
2528 }
2529
2530 static void free_translation(struct ast_channel *clonechan)
2531 {
2532         if (ast_channel_writetrans(clonechan))
2533                 ast_translator_free_path(ast_channel_writetrans(clonechan));
2534         if (ast_channel_readtrans(clonechan))
2535                 ast_translator_free_path(ast_channel_readtrans(clonechan));
2536         ast_channel_writetrans_set(clonechan, NULL);
2537         ast_channel_readtrans_set(clonechan, NULL);
2538         if (ast_format_cap_is_empty(ast_channel_nativeformats(clonechan))) {
2539                 ast_format_clear(ast_channel_rawwriteformat(clonechan));
2540                 ast_format_clear(ast_channel_rawreadformat(clonechan));
2541         } else {
2542                 struct ast_format tmpfmt;
2543                 ast_best_codec(ast_channel_nativeformats(clonechan), &tmpfmt);
2544                 ast_format_copy(ast_channel_rawwriteformat(clonechan), &tmpfmt);
2545                 ast_format_copy(ast_channel_rawreadformat(clonechan), &tmpfmt);
2546         }
2547 }
2548
2549 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2550 {
2551         struct ast_channel *bridge;
2552
2553         ast_channel_lock(chan);
2554         if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2555                 ast_channel_hangupsource_set(chan, source);
2556         }
2557         bridge = ast_bridged_channel(chan);
2558         ast_channel_unlock(chan);
2559
2560         if (bridge && (force || ast_strlen_zero(ast_channel_hangupsource(bridge)))) {
2561                 ast_channel_lock(bridge);
2562                 ast_channel_hangupsource_set(chan, source);
2563                 ast_channel_unlock(bridge);
2564         }
2565 }
2566
2567 static void destroy_hooks(struct ast_channel *chan)
2568 {
2569         if (ast_channel_audiohooks(chan)) {
2570                 ast_audiohook_detach_list(ast_channel_audiohooks(chan));
2571                 ast_channel_audiohooks_set(chan, NULL);
2572         }
2573
2574         ast_framehook_list_destroy(chan);
2575 }
2576
2577 /*! \brief Hangup a channel */
2578 int ast_hangup(struct ast_channel *chan)
2579 {
2580         char extra_str[64]; /* used for cel logging below */
2581         int was_zombie;
2582
2583         ast_autoservice_stop(chan);
2584
2585         ast_channel_lock(chan);
2586
2587         /*
2588          * Do the masquerade if someone is setup to masquerade into us.
2589          *
2590          * NOTE: We must hold the channel lock after testing for a
2591          * pending masquerade and setting the channel as a zombie to
2592          * prevent __ast_channel_masquerade() from setting up a
2593          * masquerade with a dead channel.
2594          */
2595         while (ast_channel_masq(chan)) {
2596                 ast_channel_unlock(chan);
2597                 if (ast_do_masquerade(chan)) {
2598                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2599
2600                         /* Abort the loop or we might never leave. */
2601                         ast_channel_lock(chan);
2602                         break;
2603                 }
2604                 ast_channel_lock(chan);
2605         }
2606
2607         if (ast_channel_masqr(chan)) {
2608                 /*
2609                  * This channel is one which will be masqueraded into something.
2610                  * Mark it as a zombie already so ast_do_masquerade() will know
2611                  * to free it later.
2612                  */
2613                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2614                 destroy_hooks(chan);
2615                 ast_channel_unlock(chan);
2616                 return 0;
2617         }
2618
2619         if (!(was_zombie = ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE))) {
2620                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
2621         }
2622
2623         ast_channel_unlock(chan);
2624         ao2_unlink(channels, chan);
2625         ast_channel_lock(chan);
2626
2627         destroy_hooks(chan);
2628
2629         free_translation(chan);
2630         /* Close audio stream */
2631         if (ast_channel_stream(chan)) {
2632                 ast_closestream(ast_channel_stream(chan));
2633                 ast_channel_stream_set(chan, NULL);
2634         }
2635         /* Close video stream */
2636         if (ast_channel_vstream(chan)) {
2637                 ast_closestream(ast_channel_vstream(chan));
2638                 ast_channel_vstream_set(chan, NULL);
2639         }
2640         if (ast_channel_sched(chan)) {
2641                 ast_sched_context_destroy(ast_channel_sched(chan));
2642                 ast_channel_sched_set(chan, NULL);
2643         }
2644
2645         if (ast_channel_generatordata(chan)) {  /* Clear any tone stuff remaining */
2646                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2647                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2648                 }
2649         }
2650         ast_channel_generatordata_set(chan, NULL);
2651         ast_channel_generator_set(chan, NULL);
2652
2653         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"), ""));
2654         ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2655
2656         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
2657                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2658                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
2659                         (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
2660                 ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
2661         }
2662         if (!was_zombie) {
2663                 ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2664
2665                 if (ast_channel_tech(chan)->hangup) {
2666                         ast_channel_tech(chan)->hangup(chan);
2667                 }
2668         } else {
2669                 ast_debug(1, "Hanging up zombie '%s'\n", ast_channel_name(chan));
2670         }
2671
2672         ast_channel_unlock(chan);
2673
2674         ast_cc_offer(chan);
2675         ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2676                 "Channel: %s\r\n"
2677                 "Uniqueid: %s\r\n"
2678                 "CallerIDNum: %s\r\n"
2679                 "CallerIDName: %s\r\n"
2680                 "ConnectedLineNum: %s\r\n"
2681                 "ConnectedLineName: %s\r\n"
2682                 "Cause: %d\r\n"
2683                 "Cause-txt: %s\r\n",
2684                 ast_channel_name(chan),
2685                 ast_channel_uniqueid(chan),
2686                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
2687                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
2688                 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
2689                 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
2690                 ast_channel_hangupcause(chan),
2691                 ast_cause2str(ast_channel_hangupcause(chan))
2692                 );
2693
2694         if (ast_channel_cdr(chan) && !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_BRIDGED) &&
2695                 !ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_POST_DISABLED) &&
2696                 (ast_channel_cdr(chan)->disposition != AST_CDR_NULL || ast_test_flag(ast_channel_cdr(chan), AST_CDR_FLAG_DIALED))) {
2697                 ast_channel_lock(chan);
2698                 ast_cdr_end(ast_channel_cdr(chan));
2699                 ast_cdr_detach(ast_channel_cdr(chan));
2700                 ast_channel_cdr_set(chan, NULL);
2701                 ast_channel_unlock(chan);
2702         }
2703
2704         ast_channel_unref(chan);
2705
2706         return 0;
2707 }
2708
2709 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2710 {
2711         int res = 0;
2712
2713         ast_channel_lock(chan);
2714
2715         /* You can't answer an outbound call */
2716         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
2717                 ast_channel_unlock(chan);
2718                 return 0;
2719         }
2720
2721         /* Stop if we're a zombie or need a soft hangup */
2722         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2723                 ast_channel_unlock(chan);
2724                 return -1;
2725         }
2726
2727         ast_channel_unlock(chan);
2728
2729         switch (ast_channel_state(chan)) {
2730         case AST_STATE_RINGING:
2731         case AST_STATE_RING:
2732                 ast_channel_lock(chan);
2733                 if (ast_channel_tech(chan)->answer) {
2734                         res = ast_channel_tech(chan)->answer(chan);
2735                 }
2736                 ast_setstate(chan, AST_STATE_UP);
2737                 if (cdr_answer) {
2738                         ast_cdr_answer(ast_channel_cdr(chan));
2739                 }
2740                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2741                 ast_channel_unlock(chan);
2742                 break;
2743         case AST_STATE_UP:
2744                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2745                 /* Calling ast_cdr_answer when it it has previously been called
2746                  * is essentially a no-op, so it is safe.
2747                  */
2748                 if (cdr_answer) {
2749                         ast_cdr_answer(ast_channel_cdr(chan));
2750                 }
2751                 break;
2752         default:
2753                 break;
2754         }
2755
2756         ast_indicate(chan, -1);
2757
2758         return res;
2759 }
2760
2761 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2762 {
2763         int res = 0;
2764         enum ast_channel_state old_state;
2765
2766         old_state = ast_channel_state(chan);
2767         if ((res = ast_raw_answer(chan, cdr_answer))) {
2768                 return res;
2769         }
2770
2771         switch (old_state) {
2772         case AST_STATE_RINGING:
2773         case AST_STATE_RING:
2774                 /* wait for media to start flowing, but don't wait any longer
2775                  * than 'delay' or 500 milliseconds, whichever is longer
2776                  */
2777                 do {
2778                         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2779                         struct ast_frame *cur, *new;
2780                         int ms = MAX(delay, 500);
2781                         unsigned int done = 0;
2782
2783                         AST_LIST_HEAD_INIT_NOLOCK(&frames);
2784
2785                         for (;;) {
2786                                 ms = ast_waitfor(chan, ms);
2787                                 if (ms < 0) {
2788                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2789                                         res = -1;
2790                                         break;
2791                                 }
2792                                 if (ms == 0) {
2793                                         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));
2794                                         break;
2795                                 }
2796                                 cur = ast_read(chan);
2797                                 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2798                                              (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2799                                         if (cur) {
2800                                                 ast_frfree(cur);
2801                                         }
2802                                         res = -1;
2803                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2804                                         break;
2805                                 }
2806
2807                                 if ((new = ast_frisolate(cur)) != cur) {
2808                                         ast_frfree(cur);
2809                                 }
2810
2811                                 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2812
2813                                 /* if a specific delay period was requested, continue
2814                                  * until that delay has passed. don't stop just because
2815                                  * incoming media has arrived.
2816                                  */
2817                                 if (delay) {
2818                                         continue;
2819                                 }
2820
2821                                 switch (new->frametype) {
2822                                         /* all of these frametypes qualify as 'media' */
2823                                 case AST_FRAME_VOICE:
2824                                 case AST_FRAME_VIDEO:
2825                                 case AST_FRAME_TEXT:
2826                                 case AST_FRAME_DTMF_BEGIN:
2827                                 case AST_FRAME_DTMF_END:
2828                                 case AST_FRAME_IMAGE:
2829                                 case AST_FRAME_HTML:
2830                                 case AST_FRAME_MODEM:
2831                                         done = 1;
2832                                         break;
2833                                 case AST_FRAME_CONTROL:
2834                                 case AST_FRAME_IAX:
2835                                 case AST_FRAME_NULL:
2836                                 case AST_FRAME_CNG:
2837                                         break;
2838                                 }
2839
2840                                 if (done) {
2841                                         break;
2842                                 }
2843                         }
2844
2845                         if (res == 0) {
2846                                 ast_channel_lock(chan);
2847                                 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2848                                         ast_queue_frame_head(chan, cur);
2849                                         ast_frfree(cur);
2850                                 }
2851                                 ast_channel_unlock(chan);
2852                         }
2853                 } while (0);
2854                 break;
2855         default:
2856                 break;
2857         }
2858
2859         return res;
2860 }
2861
2862 int ast_answer(struct ast_channel *chan)
2863 {
2864         return __ast_answer(chan, 0, 1);
2865 }
2866
2867 void ast_deactivate_generator(struct ast_channel *chan)
2868 {
2869         ast_channel_lock(chan);
2870         if (ast_channel_generatordata(chan)) {
2871                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2872                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2873                 }
2874                 ast_channel_generatordata_set(chan, NULL);
2875                 ast_channel_generator_set(chan, NULL);
2876                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2877                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
2878                 ast_settimeout(chan, 0, NULL, NULL);
2879         }
2880         ast_channel_unlock(chan);
2881 }
2882
2883 static void generator_write_format_change(struct ast_channel *chan)
2884 {
2885         ast_channel_lock(chan);
2886         if (ast_channel_generator(chan) && ast_channel_generator(chan)->write_format_change) {
2887                 ast_channel_generator(chan)->write_format_change(chan, ast_channel_generatordata(chan));
2888         }
2889         ast_channel_unlock(chan);
2890 }
2891
2892 static int generator_force(const void *data)
2893 {
2894         /* Called if generator doesn't have data */
2895         void *tmp;
2896         int res;
2897         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2898         struct ast_channel *chan = (struct ast_channel *)data;
2899
2900         ast_channel_lock(chan);
2901         tmp = ast_channel_generatordata(chan);
2902         ast_channel_generatordata_set(chan, NULL);
2903         if (ast_channel_generator(chan))
2904                 generate = ast_channel_generator(chan)->generate;
2905         ast_channel_unlock(chan);
2906
2907         if (!tmp || !generate)
2908                 return 0;
2909
2910         res = generate(chan, tmp, 0, ast_format_rate(ast_channel_writeformat(chan)) / 50);
2911
2912         ast_channel_generatordata_set(chan, tmp);
2913
2914         if (res) {
2915                 ast_debug(1, "Auto-deactivating generator\n");
2916                 ast_deactivate_generator(chan);
2917         }
2918
2919         return 0;
2920 }
2921
2922 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2923 {
2924         int res = 0;
2925         void *generatordata = NULL;
2926
2927         ast_channel_lock(chan);
2928         if (ast_channel_generatordata(chan)) {
2929                 if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
2930                         ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
2931                 }
2932         }
2933         if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
2934                 res = -1;
2935         }
2936         ast_channel_generatordata_set(chan, generatordata);
2937         if (!res) {
2938                 ast_settimeout(chan, 50, generator_force, chan);
2939                 ast_channel_generator_set(chan, gen);
2940         }
2941         ast_channel_unlock(chan);
2942
2943         ast_prod(chan);
2944
2945         return res;
2946 }
2947
2948 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
2949 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2950 {
2951         int winner = -1;
2952         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2953         return winner;
2954 }
2955
2956 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
2957 #ifdef HAVE_EPOLL
2958 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2959                                         int *exception, int *outfd, int *ms)
2960 #else
2961 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2962                                         int *exception, int *outfd, int *ms)
2963 #endif
2964 {
2965         struct timeval start = { 0 , 0 };
2966         struct pollfd *pfds = NULL;
2967         int res;
2968         long rms;
2969         int x, y, max;
2970         int sz;
2971         struct timeval now = { 0, 0 };
2972         struct timeval whentohangup = { 0, 0 }, diff;
2973         struct ast_channel *winner = NULL;
2974         struct fdmap {
2975                 int chan;
2976                 int fdno;
2977         } *fdmap = NULL;
2978
2979         if (outfd) {
2980                 *outfd = -99999;
2981         }
2982         if (exception) {
2983                 *exception = 0;
2984         }
2985
2986         if ((sz = n * AST_MAX_FDS + nfds)) {
2987                 pfds = alloca(sizeof(*pfds) * sz);
2988                 fdmap = alloca(sizeof(*fdmap) * sz);
2989         } else {
2990                 /* nothing to allocate and no FDs to check */
2991                 return NULL;
2992         }
2993
2994         /* Perform any pending masquerades */
2995         for (x = 0; x < n; x++) {
2996                 if (ast_channel_masq(c[x]) && ast_do_masquerade(c[x])) {
2997                         ast_log(LOG_WARNING, "Masquerade failed\n");
2998                         *ms = -1;
2999                         return NULL;
3000                 }
3001
3002                 ast_channel_lock(c[x]);
3003                 if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
3004                         if (ast_tvzero(whentohangup))
3005                                 now = ast_tvnow();
3006                         diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
3007                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3008                                 /* Should already be hungup */
3009                                 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3010                                 ast_channel_unlock(c[x]);
3011                                 return c[x];
3012                         }
3013                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3014                                 whentohangup = diff;
3015                 }
3016                 ast_channel_unlock(c[x]);
3017         }
3018         /* Wait full interval */
3019         rms = *ms;
3020         /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3021         if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3022                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
3023                 if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
3024                         rms =  *ms;
3025                 }
3026         } else if (!ast_tvzero(whentohangup) && rms < 0) {
3027                 /* Tiny corner case... call would need to last >24 days */
3028                 rms = INT_MAX;
3029         }
3030         /*
3031          * Build the pollfd array, putting the channels' fds first,
3032          * followed by individual fds. Order is important because
3033          * individual fd's must have priority over channel fds.
3034          */
3035         max = 0;
3036         for (x = 0; x < n; x++) {
3037                 for (y = 0; y < AST_MAX_FDS; y++) {
3038                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
3039                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
3040                         max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
3041                 }
3042                 CHECK_BLOCKING(c[x]);
3043         }
3044         /* Add the individual fds */
3045         for (x = 0; x < nfds; x++) {
3046                 fdmap[max].chan = -1;
3047                 max += ast_add_fd(&pfds[max], fds[x]);
3048         }
3049
3050         if (*ms > 0) {
3051                 start = ast_tvnow();
3052         }
3053
3054         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3055                 do {
3056                         int kbrms = rms;
3057                         if (kbrms > 600000) {
3058                                 kbrms = 600000;
3059                         }
3060                         res = ast_poll(pfds, max, kbrms);
3061                         if (!res) {
3062                                 rms -= kbrms;
3063                         }
3064                 } while (!res && (rms > 0));
3065         } else {
3066                 res = ast_poll(pfds, max, rms);
3067         }
3068         for (x = 0; x < n; x++) {
3069                 ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
3070         }
3071         if (res < 0) { /* Simulate a timeout if we were interrupted */
3072                 if (errno != EINTR) {
3073                         *ms = -1;
3074                 }
3075                 return NULL;
3076         }
3077         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
3078                 now = ast_tvnow();
3079                 for (x = 0; x < n; x++) {
3080                         if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
3081                                 ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
3082                                 if (winner == NULL) {
3083                                         winner = c[x];
3084                                 }
3085                         }
3086                 }
3087         }
3088         if (res == 0) { /* no fd ready, reset timeout and done */
3089                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
3090                 return winner;
3091         }
3092         /*
3093          * Then check if any channel or fd has a pending event.
3094          * Remember to check channels first and fds last, as they
3095          * must have priority on setting 'winner'
3096          */
3097         for (x = 0; x < max; x++) {
3098                 res = pfds[x].revents;
3099                 if (res == 0) {
3100                         continue;
3101                 }
3102                 if (fdmap[x].chan >= 0) {       /* this is a channel */
3103                         winner = c[fdmap[x].chan];      /* override previous winners */
3104                         if (res & POLLPRI) {
3105                                 ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3106                         } else {
3107                                 ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3108                         }
3109                         ast_channel_fdno_set(winner, fdmap[x].fdno);
3110                 } else {                        /* this is an fd */
3111                         if (outfd) {
3112                                 *outfd = pfds[x].fd;
3113                         }
3114                         if (exception) {
3115                                 *exception = (res & POLLPRI) ? -1 : 0;
3116                         }
3117                         winner = NULL;
3118                 }
3119         }
3120         if (*ms > 0) {
3121                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3122                 if (*ms < 0) {
3123                         *ms = 0;
3124                 }
3125         }
3126         return winner;
3127 }
3128
3129 #ifdef HAVE_EPOLL
3130 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3131 {
3132         struct timeval start = { 0 , 0 };
3133         int res = 0;
3134         struct epoll_event ev[1];
3135         long diff, rms = *ms;
3136         struct ast_channel *winner = NULL;
3137         struct ast_epoll_data *aed = NULL;
3138
3139
3140         /* See if this channel needs to be masqueraded */
3141         if (ast_channel_masq(chan) && ast_do_masquerade(chan)) {
3142                 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", ast_channel_name(chan));
3143                 *ms = -1;
3144                 return NULL;
3145         }
3146
3147         ast_channel_lock(chan);
3148         /* Figure out their timeout */
3149         if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3150                 if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow())) < 0) {
3151                         /* They should already be hungup! */
3152                         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3153                         ast_channel_unlock(chan);
3154                         return NULL;
3155                 }
3156                 /* If this value is smaller then the current one... make it priority */
3157                 if (rms > diff) {
3158                         rms = diff;
3159                 }
3160         }
3161
3162         ast_channel_unlock(chan);
3163
3164         /* Time to make this channel block... */
3165         CHECK_BLOCKING(chan);
3166
3167         if (*ms > 0) {
3168                 start = ast_tvnow();
3169         }
3170
3171         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3172         res = epoll_wait(ast_channel_epfd(chan), ev, 1, rms);
3173
3174         /* Stop blocking */
3175         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
3176
3177         /* Simulate a timeout if we were interrupted */
3178         if (res < 0) {
3179                 if (errno != EINTR) {
3180                         *ms = -1;
3181                 }
3182                 return NULL;
3183         }
3184
3185         /* If this channel has a timeout see if it expired */
3186         if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
3187                 if (ast_tvdiff_ms(ast_tvnow(), *ast_channel_whentohangup(chan)) >= 0) {
3188                         ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
3189                         winner = chan;
3190                 }
3191         }
3192
3193         /* No fd ready, reset timeout and be done for now */
3194         if (!res) {
3195                 *ms = 0;
3196                 return winner;
3197         }
3198
3199         /* See what events are pending */
3200         aed = ev[0].data.ptr;
3201         ast_channel_fdno_set(chan, aed->which);
3202         if (ev[0].events & EPOLLPRI) {
3203                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3204         } else {
3205                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
3206         }
3207
3208         if (*ms > 0) {
3209                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3210                 if (*ms < 0) {
3211                         *ms = 0;
3212                 }
3213         }
3214
3215         return chan;
3216 }
3217
3218 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3219 {
3220         struct timeval start = { 0 , 0 };
3221         int res = 0, i;
3222         struct epoll_event ev[25] = { { 0, } };
3223         struct timeval now = { 0, 0 };
3224         long whentohangup = 0, diff = 0, rms = *ms;
3225         struct ast_channel *winner = NULL;
3226
3227         for (i = 0; i < n; i++) {
3228                 if (ast_channel_masq(c[i]) && ast_do_masquerade(c[i])) {
3229                         ast_log(LOG_WARNING, "Masquerade failed\n");
3230                         *ms = -1;
3231                         return NULL;
3232                 }
3233
3234                 ast_channel_lock(c[i]);
3235                 if (!ast_tvzero(*ast_channel_whentohangup(c[i]))) {
3236                         if (whentohangup == 0) {
3237                                 now = ast_tvnow();
3238                         }
3239                         if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(c[i]), now)) < 0) {
3240                                 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3241                                 ast_channel_unlock(c[i]);
3242                                 return c[i];
3243                         }
3244                         if (!whentohangup || whentohangup > diff) {
3245                                 whentohangup = diff;
3246                         }
3247                 }
3248                 ast_channel_unlock(c[i]);
3249                 CHECK_BLOCKING(c[i]);
3250         }
3251
3252         rms = *ms;
3253         if (whentohangup) {
3254                 rms = whentohangup;
3255                 if (*ms >= 0 && *ms < rms) {
3256                         rms = *ms;
3257                 }
3258         }
3259
3260         if (*ms > 0) {
3261                 start = ast_tvnow();
3262         }
3263
3264         res = epoll_wait(ast_channel_epfd(c[0]), ev, 25, rms);
3265
3266         for (i = 0; i < n; i++) {
3267                 ast_clear_flag(ast_channel_flags(c[i]), AST_FLAG_BLOCKING);
3268         }
3269
3270         if (res < 0) {
3271                 if (errno != EINTR) {
3272                         *ms = -1;
3273                 }
3274                 return NULL;
3275         }
3276
3277         if (whentohangup) {
3278                 now = ast_tvnow();
3279                 for (i = 0; i < n; i++) {
3280                         if (!ast_tvzero(*ast_channel_whentohangup(c[i])) && ast_tvdiff_ms(now, *ast_channel_whentohangup(c[i])) >= 0) {
3281                                 ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
3282                                 if (!winner) {
3283                                         winner = c[i];
3284                                 }
3285                         }
3286                 }
3287         }
3288
3289         if (!res) {
3290                 *ms = 0;
3291                 return winner;
3292         }
3293
3294         for (i = 0; i < res; i++) {
3295                 struct ast_epoll_data *aed = ev[i].data.ptr;
3296
3297                 if (!ev[i].events || !aed) {
3298                         continue;
3299                 }
3300
3301                 winner = aed->chan;
3302                 if (ev[i].events & EPOLLPRI) {
3303                         ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3304                 } else {
3305                         ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
3306                 }
3307                 ast_channel_fdno_set(winner, aed->which);
3308         }
3309
3310         if (*ms > 0) {
3311                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3312                 if (*ms < 0) {
3313                         *ms = 0;
3314                 }
3315         }
3316
3317         return winner;
3318 }
3319
3320 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3321                                         int *exception, int *outfd, int *ms)
3322 {
3323         /* Clear all provided values in one place. */
3324         if (outfd) {
3325                 *outfd = -99999;
3326         }
3327         if (exception) {
3328                 *exception = 0;
3329         }
3330
3331         /* If no epoll file descriptor is available resort to classic nandfds */
3332         if (!n || nfds || ast_channel_epfd(c[0]) == -1) {
3333                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3334         } else if (!nfds && n == 1) {
3335                 return ast_waitfor_nandfds_simple(c[0], ms);
3336         } else {
3337                 return ast_waitfor_nandfds_complex(c, n, ms);
3338         }
3339 }
3340 #endif
3341
3342 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3343 {
3344         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3345 }
3346
3347 int ast_waitfor(struct ast_channel *c, int ms)
3348 {
3349         int oldms = ms; /* -1 if no timeout */
3350
3351         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3352         if ((ms < 0) && (oldms < 0)) {
3353                 ms = 0;
3354         }
3355         return ms;