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