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