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