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