Opaquify char * and char[] in ast_channel
[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         chan->tech_pvt = 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 = chan->priority;
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
924         /* If shutting down, don't allocate any new channels */
925         if (shutting_down) {
926                 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
927                 return NULL;
928         }
929
930 #if defined(REF_DEBUG)
931         tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
932                 function, 1);
933 #elif defined(__AST_DEBUG_MALLOC)
934         tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
935                 function, 0);
936 #else
937         tmp = ao2_alloc(sizeof(*tmp), ast_channel_destructor);
938 #endif
939         if (!tmp) {
940                 /* Channel structure allocation failure. */
941                 return NULL;
942         }
943         if (!(tmp->nativeformats = ast_format_cap_alloc())) {
944                 ao2_ref(tmp, -1);
945                 /* format capabilities structure allocation failure */
946                 return NULL;
947         }
948
949         /*
950          * Init file descriptors to unopened state so
951          * the destructor can know not to close them.
952          */
953         tmp->timingfd = -1;
954         for (x = 0; x < ARRAY_LEN(tmp->alertpipe); ++x) {
955                 tmp->alertpipe[x] = -1;
956         }
957         for (x = 0; x < ARRAY_LEN(tmp->fds); ++x) {
958                 tmp->fds[x] = -1;
959         }
960 #ifdef HAVE_EPOLL
961         tmp->epfd = epoll_create(25);
962 #endif
963
964         if (!(tmp->sched = ast_sched_context_create())) {
965                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
966                 return ast_channel_unref(tmp);
967         }
968         
969         ast_party_dialed_init(&tmp->dialed);
970         ast_party_caller_init(&tmp->caller);
971         ast_party_connected_line_init(&tmp->connected);
972         ast_party_redirecting_init(&tmp->redirecting);
973
974         if (cid_name) {
975                 tmp->caller.id.name.valid = 1;
976                 tmp->caller.id.name.str = ast_strdup(cid_name);
977                 if (!tmp->caller.id.name.str) {
978                         return ast_channel_unref(tmp);
979                 }
980         }
981         if (cid_num) {
982                 tmp->caller.id.number.valid = 1;
983                 tmp->caller.id.number.str = ast_strdup(cid_num);
984                 if (!tmp->caller.id.number.str) {
985                         return ast_channel_unref(tmp);
986                 }
987         }
988
989         if ((tmp->timer = ast_timer_open())) {
990                 if (strcmp(ast_timer_get_name(tmp->timer), "timerfd")) {
991                         needqueue = 0;
992                 }
993                 tmp->timingfd = ast_timer_fd(tmp->timer);
994         }
995
996         if (needqueue) {
997                 if (pipe(tmp->alertpipe)) {
998                         ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
999                         return ast_channel_unref(tmp);
1000                 } else {
1001                         flags = fcntl(tmp->alertpipe[0], F_GETFL);
1002                         if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
1003                                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1004                                 return ast_channel_unref(tmp);
1005                         }
1006                         flags = fcntl(tmp->alertpipe[1], F_GETFL);
1007                         if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
1008                                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1009                                 return ast_channel_unref(tmp);
1010                         }
1011                 }
1012         }
1013
1014         /*
1015          * This is the last place the channel constructor can fail.
1016          *
1017          * The destructor takes advantage of this fact to ensure that the
1018          * AST_CEL_CHANNEL_END is not posted if we have not posted the
1019          * AST_CEL_CHANNEL_START yet.
1020          */
1021         if ((ast_string_field_init(tmp, 128))) {
1022                 return ast_channel_unref(tmp);
1023         }
1024
1025         /* Always watch the alertpipe */
1026         ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
1027         /* And timing pipe */
1028         ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
1029
1030         /* Initial state */
1031         tmp->_state = state;
1032
1033         tmp->streamid = -1;
1034         
1035         tmp->fin = global_fin;
1036         tmp->fout = global_fout;
1037
1038         if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1039                 ast_channel_uniqueid_build(tmp, "%li.%d", (long) time(NULL), 
1040                         ast_atomic_fetchadd_int(&uniqueint, 1));
1041         } else {
1042                 ast_channel_uniqueid_build(tmp, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, 
1043                         (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1044         }
1045
1046         if (!ast_strlen_zero(linkedid)) {
1047                 ast_channel_linkedid_set(tmp, linkedid);
1048         } else {
1049                 ast_channel_linkedid_set(tmp, ast_channel_uniqueid(tmp));
1050         }
1051
1052         if (!ast_strlen_zero(name_fmt)) {
1053                 char *slash, *slash2;
1054                 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1055                  * And they all use slightly different formats for their name string.
1056                  * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1057                  * This means, that the stringfields must have a routine that takes the va_lists directly, and 
1058                  * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1059                  * This new function was written so this can be accomplished.
1060                  */
1061                 ast_channel_name_build_va(tmp, name_fmt, ap);
1062                 tech = ast_strdupa(ast_channel_name(tmp));
1063                 if ((slash = strchr(tech, '/'))) {
1064                         if ((slash2 = strchr(slash + 1, '/'))) {
1065                                 tech2 = slash + 1;
1066                                 *slash2 = '\0';
1067                         }
1068                         *slash = '\0';
1069                 }
1070         } else {
1071                 /*
1072                  * Start the string with '-' so it becomes an empty string
1073                  * in the destructor.
1074                  */
1075                 ast_channel_name_set(tmp, "-**Unknown**");
1076         }
1077
1078         /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1079
1080         /* These 4 variables need to be set up for the cdr_init() to work right */
1081         if (amaflag)
1082                 tmp->amaflags = amaflag;
1083         else
1084                 tmp->amaflags = ast_default_amaflags;
1085         
1086         if (!ast_strlen_zero(acctcode))
1087                 ast_channel_accountcode_set(tmp, acctcode);
1088         else
1089                 ast_channel_accountcode_set(tmp, ast_default_accountcode);
1090                 
1091         ast_channel_context_set(tmp, S_OR(context, "default"));
1092         ast_channel_exten_set(tmp, S_OR(exten, "s"));
1093         tmp->priority = 1;
1094
1095         tmp->cdr = ast_cdr_alloc();
1096         ast_cdr_init(tmp->cdr, tmp);
1097         ast_cdr_start(tmp->cdr);
1098
1099         ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1100
1101         headp = &tmp->varshead;
1102         AST_LIST_HEAD_INIT_NOLOCK(headp);
1103         
1104         AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
1105
1106         AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
1107         
1108         ast_channel_language_set(tmp, defaultlanguage);
1109
1110         tmp->tech = &null_tech;
1111
1112         ao2_link(channels, tmp);
1113
1114         /*
1115          * And now, since the channel structure is built, and has its name, let's
1116          * call the manager event generator with this Newchannel event. This is the
1117          * proper and correct place to make this call, but you sure do have to pass
1118          * a lot of data into this func to do it here!
1119          */
1120         if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1121                 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1122                         "Channel: %s\r\n"
1123                         "ChannelState: %d\r\n"
1124                         "ChannelStateDesc: %s\r\n"
1125                         "CallerIDNum: %s\r\n"
1126                         "CallerIDName: %s\r\n"
1127                         "AccountCode: %s\r\n"
1128                         "Exten: %s\r\n"
1129                         "Context: %s\r\n"
1130                         "Uniqueid: %s\r\n",
1131                         ast_channel_name(tmp), 
1132                         state, 
1133                         ast_state2str(state),
1134                         S_OR(cid_num, ""),
1135                         S_OR(cid_name, ""),
1136                         ast_channel_accountcode(tmp),
1137                         S_OR(exten, ""),
1138                         S_OR(context, ""),
1139                         ast_channel_uniqueid(tmp));
1140         }
1141
1142         return tmp;
1143 }
1144
1145 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1146                                         const char *cid_name, const char *acctcode,
1147                                         const char *exten, const char *context,
1148                                         const char *linkedid, const int amaflag,
1149                                         const char *file, int line, const char *function,
1150                                         const char *name_fmt, ...)
1151 {
1152         va_list ap;
1153         struct ast_channel *result;
1154
1155         va_start(ap, name_fmt);
1156         result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1157                                         linkedid, amaflag, file, line, function, name_fmt, ap);
1158         va_end(ap);
1159
1160         return result;
1161 }
1162
1163 /* only do the minimum amount of work needed here to make a channel
1164  * structure that can be used to expand channel vars */
1165 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1166 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1167 #else
1168 struct ast_channel *ast_dummy_channel_alloc(void)
1169 #endif
1170 {
1171         struct ast_channel *tmp;
1172         struct varshead *headp;
1173
1174 #if defined(REF_DEBUG)
1175         tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1176                 file, line, function, 1);
1177 #elif defined(__AST_DEBUG_MALLOC)
1178         tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1179                 file, line, function, 0);
1180 #else
1181         tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor);
1182 #endif
1183         if (!tmp) {
1184                 /* Dummy channel structure allocation failure. */
1185                 return NULL;
1186         }
1187
1188         if ((ast_string_field_init(tmp, 128))) {
1189                 return ast_channel_unref(tmp);
1190         }
1191
1192         headp = &tmp->varshead;
1193         AST_LIST_HEAD_INIT_NOLOCK(headp);
1194
1195         return tmp;
1196 }
1197
1198 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1199 {
1200         struct ast_frame *f;
1201         struct ast_frame *cur;
1202         unsigned int new_frames = 0;
1203         unsigned int new_voice_frames = 0;
1204         unsigned int queued_frames = 0;
1205         unsigned int queued_voice_frames = 0;
1206         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1207
1208         ast_channel_lock(chan);
1209
1210         /*
1211          * Check the last frame on the queue if we are queuing the new
1212          * frames after it.
1213          */
1214         cur = AST_LIST_LAST(&chan->readq);
1215         if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1216                 switch (cur->subclass.integer) {
1217                 case AST_CONTROL_END_OF_Q:
1218                         if (fin->frametype == AST_FRAME_CONTROL
1219                                 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1220                                 /*
1221                                  * Destroy the end-of-Q marker frame so we can queue the hangup
1222                                  * frame in its place.
1223                                  */
1224                                 AST_LIST_REMOVE(&chan->readq, cur, frame_list);
1225                                 ast_frfree(cur);
1226
1227                                 /*
1228                                  * This has degenerated to a normal queue append anyway.  Since
1229                                  * we just destroyed the last frame in the queue we must make
1230                                  * sure that "after" is NULL or bad things will happen.
1231                                  */
1232                                 after = NULL;
1233                                 break;
1234                         }
1235                         /* Fall through */
1236                 case AST_CONTROL_HANGUP:
1237                         /* Don't queue anything. */
1238                         ast_channel_unlock(chan);
1239                         return 0;
1240                 default:
1241                         break;
1242                 }
1243         }
1244
1245         /* Build copies of all the new frames and count them */
1246         AST_LIST_HEAD_INIT_NOLOCK(&frames);
1247         for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1248                 if (!(f = ast_frdup(cur))) {
1249                         if (AST_LIST_FIRST(&frames)) {
1250                                 ast_frfree(AST_LIST_FIRST(&frames));
1251                         }
1252                         ast_channel_unlock(chan);
1253                         return -1;
1254                 }
1255
1256                 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1257                 new_frames++;
1258                 if (f->frametype == AST_FRAME_VOICE) {
1259                         new_voice_frames++;
1260                 }
1261         }
1262
1263         /* Count how many frames exist on the queue */
1264         AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1265                 queued_frames++;
1266                 if (cur->frametype == AST_FRAME_VOICE) {
1267                         queued_voice_frames++;
1268                 }
1269         }
1270
1271         if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1272                 int count = 0;
1273                 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1274                 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
1275                         /* Save the most recent frame */
1276                         if (!AST_LIST_NEXT(cur, frame_list)) {
1277                                 break;
1278                         } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1279                                 if (++count > 64) {
1280                                         break;
1281                                 }
1282                                 AST_LIST_REMOVE_CURRENT(frame_list);
1283                                 ast_frfree(cur);
1284                         }
1285                 }
1286                 AST_LIST_TRAVERSE_SAFE_END;
1287         }
1288
1289         if (after) {
1290                 AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1291         } else {
1292                 if (head) {
1293                         AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1294                         AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1295                 }
1296                 AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1297         }
1298
1299         if (chan->alertpipe[1] > -1) {
1300                 int blah[new_frames];
1301
1302                 memset(blah, 1, sizeof(blah));
1303                 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != (sizeof(blah))) {
1304                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1305                                 ast_channel_name(chan), queued_frames, strerror(errno));
1306                 }
1307         } else if (chan->timingfd > -1) {
1308                 ast_timer_enable_continuous(chan->timer);
1309         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1310                 pthread_kill(chan->blocker, SIGURG);
1311         }
1312
1313         ast_channel_unlock(chan);
1314
1315         return 0;
1316 }
1317
1318 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1319 {
1320         return __ast_queue_frame(chan, fin, 0, NULL);
1321 }
1322
1323 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1324 {
1325         return __ast_queue_frame(chan, fin, 1, NULL);
1326 }
1327
1328 /*! \brief Queue a hangup frame for channel */
1329 int ast_queue_hangup(struct ast_channel *chan)
1330 {
1331         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1332         /* Yeah, let's not change a lock-critical value without locking */
1333         if (!ast_channel_trylock(chan)) {
1334                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1335                 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1336                         "Channel: %s\r\n"
1337                         "Uniqueid: %s\r\n",
1338                         ast_channel_name(chan),
1339                         ast_channel_uniqueid(chan));
1340                 ast_channel_unlock(chan);
1341         }
1342         return ast_queue_frame(chan, &f);
1343 }
1344
1345 /*! \brief Queue a hangup frame for channel */
1346 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1347 {
1348         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1349
1350         if (cause >= 0)
1351                 f.data.uint32 = cause;
1352
1353         /* Yeah, let's not change a lock-critical value without locking */
1354         if (!ast_channel_trylock(chan)) {
1355                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1356                 if (cause < 0)
1357                         f.data.uint32 = chan->hangupcause;
1358
1359                 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1360                         "Channel: %s\r\n"
1361                         "Uniqueid: %s\r\n"
1362                         "Cause: %d\r\n",
1363                         ast_channel_name(chan),
1364                         ast_channel_uniqueid(chan),
1365                         cause);
1366                 ast_channel_unlock(chan);
1367         }
1368
1369         return ast_queue_frame(chan, &f);
1370 }
1371
1372 /*! \brief Queue a control frame */
1373 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1374 {
1375         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1376         return ast_queue_frame(chan, &f);
1377 }
1378
1379 /*! \brief Queue a control frame with payload */
1380 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1381                            const void *data, size_t datalen)
1382 {
1383         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1384         return ast_queue_frame(chan, &f);
1385 }
1386
1387 /*! \brief Set defer DTMF flag on channel */
1388 int ast_channel_defer_dtmf(struct ast_channel *chan)
1389 {
1390         int pre = 0;
1391
1392         if (chan) {
1393                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1394                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1395         }
1396         return pre;
1397 }
1398
1399 /*! \brief Unset defer DTMF flag on channel */
1400 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1401 {
1402         if (chan)
1403                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1404 }
1405
1406 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1407                 void *data, int ao2_flags)
1408 {
1409         return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1410 }
1411
1412 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1413 {
1414         struct ast_channel *chan = obj;
1415         const char *name = arg;
1416         size_t name_len = *(size_t *) data;
1417         int ret = CMP_MATCH;
1418
1419         if (ast_strlen_zero(name)) {
1420                 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1421                 return CMP_STOP;
1422         }
1423
1424         ast_channel_lock(chan);
1425         if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1426                 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1427                 ret = 0; /* name match failed, keep looking */
1428         }
1429         ast_channel_unlock(chan);
1430
1431         return ret;
1432 }
1433
1434 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1435 {
1436         struct ast_channel *chan = obj;
1437         char *context = arg;
1438         char *exten = data;
1439         int ret = CMP_MATCH;
1440
1441         if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1442                 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1443                 return CMP_STOP;
1444         }
1445
1446         ast_channel_lock(chan);
1447         if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
1448                 ret = 0; /* Context match failed, continue */
1449         } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
1450                 ret = 0; /* Extension match failed, continue */
1451         }
1452         ast_channel_unlock(chan);
1453
1454         return ret;
1455 }
1456
1457 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1458 {
1459         struct ast_channel *chan = obj;
1460         char *uniqueid = arg;
1461         size_t id_len = *(size_t *) data;
1462         int ret = CMP_MATCH;
1463
1464         if (ast_strlen_zero(uniqueid)) {
1465                 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1466                 return CMP_STOP;
1467         }
1468
1469         ast_channel_lock(chan);
1470         if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1471                 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1472                 ret = 0; /* uniqueid match failed, keep looking */
1473         }
1474         ast_channel_unlock(chan);
1475
1476         return ret;
1477 }
1478
1479 struct ast_channel_iterator {
1480         /* storage for non-dynamically allocated iterator */
1481         struct ao2_iterator simple_iterator;
1482         /* pointer to the actual iterator (simple_iterator or a dynamically
1483          * allocated iterator)
1484          */
1485         struct ao2_iterator *active_iterator;
1486 };
1487
1488 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1489 {
1490         ao2_iterator_destroy(i->active_iterator);
1491         ast_free(i);
1492
1493         return NULL;
1494 }
1495
1496 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1497 {
1498         struct ast_channel_iterator *i;
1499         char *l_exten = (char *) exten;
1500         char *l_context = (char *) context;
1501
1502         if (!(i = ast_calloc(1, sizeof(*i)))) {
1503                 return NULL;
1504         }
1505
1506         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1507                 l_context, l_exten, OBJ_MULTIPLE);
1508         if (!i->active_iterator) {
1509                 ast_free(i);
1510                 return NULL;
1511         }
1512
1513         return i;
1514 }
1515
1516 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1517 {
1518         struct ast_channel_iterator *i;
1519         char *l_name = (char *) name;
1520
1521         if (!(i = ast_calloc(1, sizeof(*i)))) {
1522                 return NULL;
1523         }
1524
1525         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1526                 l_name, &name_len,
1527                 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1528         if (!i->active_iterator) {
1529                 ast_free(i);
1530                 return NULL;
1531         }
1532
1533         return i;
1534 }
1535
1536 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1537 {
1538         struct ast_channel_iterator *i;
1539
1540         if (!(i = ast_calloc(1, sizeof(*i)))) {
1541                 return NULL;
1542         }
1543
1544         i->simple_iterator = ao2_iterator_init(channels, 0);
1545         i->active_iterator = &i->simple_iterator;
1546
1547         return i;
1548 }
1549
1550 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1551 {
1552         return ao2_iterator_next(i->active_iterator);
1553 }
1554
1555 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1556 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1557 {
1558         ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1559         return CMP_STOP;
1560 }
1561
1562 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1563 {
1564         struct ast_channel *chan;
1565         char *l_name = (char *) name;
1566
1567         chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1568                 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1569         if (chan) {
1570                 return chan;
1571         }
1572
1573         if (ast_strlen_zero(l_name)) {
1574                 /* We didn't have a name to search for so quit. */
1575                 return NULL;
1576         }
1577
1578         /* Now try a search for uniqueid. */
1579         return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1580 }
1581
1582 struct ast_channel *ast_channel_get_by_name(const char *name)
1583 {
1584         return ast_channel_get_by_name_prefix(name, 0);
1585 }
1586
1587 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1588 {
1589         char *l_exten = (char *) exten;
1590         char *l_context = (char *) context;
1591
1592         return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1593 }
1594
1595 int ast_is_deferrable_frame(const struct ast_frame *frame)
1596 {
1597         /* Do not add a default entry in this switch statement.  Each new
1598          * frame type should be addressed directly as to whether it should
1599          * be queued up or not.
1600          */
1601         switch (frame->frametype) {
1602         case AST_FRAME_CONTROL:
1603         case AST_FRAME_TEXT:
1604         case AST_FRAME_IMAGE:
1605         case AST_FRAME_HTML:
1606                 return 1;
1607
1608         case AST_FRAME_DTMF_END:
1609         case AST_FRAME_DTMF_BEGIN:
1610         case AST_FRAME_VOICE:
1611         case AST_FRAME_VIDEO:
1612         case AST_FRAME_NULL:
1613         case AST_FRAME_IAX:
1614         case AST_FRAME_CNG:
1615         case AST_FRAME_MODEM:
1616                 return 0;
1617         }
1618         return 0;
1619 }
1620
1621 /*! \brief Wait, look for hangups and condition arg */
1622 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1623 {
1624         struct ast_frame *f;
1625         struct ast_silence_generator *silgen = NULL;
1626         int res = 0;
1627         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1628
1629         AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1630
1631         /* If no other generator is present, start silencegen while waiting */
1632         if (ast_opt_transmit_silence && !chan->generatordata) {
1633                 silgen = ast_channel_start_silence_generator(chan);
1634         }
1635
1636         while (ms > 0) {
1637                 struct ast_frame *dup_f = NULL;
1638                 if (cond && ((*cond)(data) == 0)) {
1639                         break;
1640                 }
1641                 ms = ast_waitfor(chan, ms);
1642                 if (ms < 0) {
1643                         res = -1;
1644                         break;
1645                 }
1646                 if (ms > 0) {
1647                         f = ast_read(chan);
1648                         if (!f) {
1649                                 res = -1;
1650                                 break;
1651                         }
1652
1653                         if (!ast_is_deferrable_frame(f)) {
1654                                 ast_frfree(f);
1655                                 continue;
1656                         }
1657                         
1658                         if ((dup_f = ast_frisolate(f))) {
1659                                 if (dup_f != f) {
1660                                         ast_frfree(f);
1661                                 }
1662                                 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1663                         }
1664                 }
1665         }
1666
1667         /* stop silgen if present */
1668         if (silgen) {
1669                 ast_channel_stop_silence_generator(chan, silgen);
1670         }
1671
1672         /* We need to free all the deferred frames, but we only need to
1673          * queue the deferred frames if there was no error and no
1674          * hangup was received
1675          */
1676         ast_channel_lock(chan);
1677         while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1678                 if (!res) {
1679                         ast_queue_frame_head(chan, f);
1680                 }
1681                 ast_frfree(f);
1682         }
1683         ast_channel_unlock(chan);
1684
1685         return res;
1686 }
1687
1688 /*! \brief Wait, look for hangups */
1689 int ast_safe_sleep(struct ast_channel *chan, int ms)
1690 {
1691         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1692 }
1693
1694 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1695 {
1696         /* Safe, even if already unlinked. */
1697         ao2_unlink(channels, chan);
1698         return ast_channel_unref(chan);
1699 }
1700
1701 void ast_party_name_init(struct ast_party_name *init)
1702 {
1703         init->str = NULL;
1704         init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1705         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1706         init->valid = 0;
1707 }
1708
1709 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1710 {
1711         if (dest == src) {
1712                 /* Don't copy to self */
1713                 return;
1714         }
1715
1716         ast_free(dest->str);
1717         dest->str = ast_strdup(src->str);
1718         dest->char_set = src->char_set;
1719         dest->presentation = src->presentation;
1720         dest->valid = src->valid;
1721 }
1722
1723 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1724 {
1725         init->str = NULL;
1726         init->char_set = guide->char_set;
1727         init->presentation = guide->presentation;
1728         init->valid = guide->valid;
1729 }
1730
1731 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1732 {
1733         if (dest == src) {
1734                 /* Don't set to self */
1735                 return;
1736         }
1737
1738         if (src->str && src->str != dest->str) {
1739                 ast_free(dest->str);
1740                 dest->str = ast_strdup(src->str);
1741         }
1742
1743         dest->char_set = src->char_set;
1744         dest->presentation = src->presentation;
1745         dest->valid = src->valid;
1746 }
1747
1748 void ast_party_name_free(struct ast_party_name *doomed)
1749 {
1750         ast_free(doomed->str);
1751         doomed->str = NULL;
1752 }
1753
1754 void ast_party_number_init(struct ast_party_number *init)
1755 {
1756         init->str = NULL;
1757         init->plan = 0;/* Unknown */
1758         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1759         init->valid = 0;
1760 }
1761
1762 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1763 {
1764         if (dest == src) {
1765                 /* Don't copy to self */
1766                 return;
1767         }
1768
1769         ast_free(dest->str);
1770         dest->str = ast_strdup(src->str);
1771         dest->plan = src->plan;
1772         dest->presentation = src->presentation;
1773         dest->valid = src->valid;
1774 }
1775
1776 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1777 {
1778         init->str = NULL;
1779         init->plan = guide->plan;
1780         init->presentation = guide->presentation;
1781         init->valid = guide->valid;
1782 }
1783
1784 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1785 {
1786         if (dest == src) {
1787                 /* Don't set to self */
1788                 return;
1789         }
1790
1791         if (src->str && src->str != dest->str) {
1792                 ast_free(dest->str);
1793                 dest->str = ast_strdup(src->str);
1794         }
1795
1796         dest->plan = src->plan;
1797         dest->presentation = src->presentation;
1798         dest->valid = src->valid;
1799 }
1800
1801 void ast_party_number_free(struct ast_party_number *doomed)
1802 {
1803         ast_free(doomed->str);
1804         doomed->str = NULL;
1805 }
1806
1807 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1808 {
1809         init->str = NULL;
1810         init->type = 0;
1811         init->odd_even_indicator = 0;
1812         init->valid = 0;
1813 }
1814
1815 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1816 {
1817         if (dest == src) {
1818                 /* Don't copy to self */
1819                 return;
1820         }
1821
1822         ast_free(dest->str);
1823         dest->str = ast_strdup(src->str);
1824         dest->type = src->type;
1825         dest->odd_even_indicator = src->odd_even_indicator;
1826         dest->valid = src->valid;
1827 }
1828
1829 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1830 {
1831         init->str = NULL;
1832         init->type = guide->type;
1833         init->odd_even_indicator = guide->odd_even_indicator;
1834         init->valid = guide->valid;
1835 }
1836
1837 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1838 {
1839         if (dest == src) {
1840                 /* Don't set to self */
1841                 return;
1842         }
1843
1844         if (src->str && src->str != dest->str) {
1845                 ast_free(dest->str);
1846                 dest->str = ast_strdup(src->str);
1847         }
1848
1849         dest->type = src->type;
1850         dest->odd_even_indicator = src->odd_even_indicator;
1851         dest->valid = src->valid;
1852 }
1853
1854 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1855 {
1856         ast_free(doomed->str);
1857         doomed->str = NULL;
1858 }
1859
1860 void ast_party_id_init(struct ast_party_id *init)
1861 {
1862         ast_party_name_init(&init->name);
1863         ast_party_number_init(&init->number);
1864         ast_party_subaddress_init(&init->subaddress);
1865         init->tag = NULL;
1866 }
1867
1868 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1869 {
1870         if (dest == src) {
1871                 /* Don't copy to self */
1872                 return;
1873         }
1874
1875         ast_party_name_copy(&dest->name, &src->name);
1876         ast_party_number_copy(&dest->number, &src->number);
1877         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1878
1879         ast_free(dest->tag);
1880         dest->tag = ast_strdup(src->tag);
1881 }
1882
1883 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1884 {
1885         ast_party_name_set_init(&init->name, &guide->name);
1886         ast_party_number_set_init(&init->number, &guide->number);
1887         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1888         init->tag = NULL;
1889 }
1890
1891 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1892 {
1893         if (dest == src) {
1894                 /* Don't set to self */
1895                 return;
1896         }
1897
1898         if (!update || update->name) {
1899                 ast_party_name_set(&dest->name, &src->name);
1900         }
1901         if (!update || update->number) {
1902                 ast_party_number_set(&dest->number, &src->number);
1903         }
1904         if (!update || update->subaddress) {
1905                 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1906         }
1907
1908         if (src->tag && src->tag != dest->tag) {
1909                 ast_free(dest->tag);
1910                 dest->tag = ast_strdup(src->tag);
1911         }
1912 }
1913
1914 void ast_party_id_free(struct ast_party_id *doomed)
1915 {
1916         ast_party_name_free(&doomed->name);
1917         ast_party_number_free(&doomed->number);
1918         ast_party_subaddress_free(&doomed->subaddress);
1919
1920         ast_free(doomed->tag);
1921         doomed->tag = NULL;
1922 }
1923
1924 int ast_party_id_presentation(const struct ast_party_id *id)
1925 {
1926         int number_priority;
1927         int number_value;
1928         int number_screening;
1929         int name_priority;
1930         int name_value;
1931
1932         /* Determine name presentation priority. */
1933         if (!id->name.valid) {
1934                 name_value = AST_PRES_UNAVAILABLE;
1935                 name_priority = 3;
1936         } else {
1937                 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1938                 switch (name_value) {
1939                 case AST_PRES_RESTRICTED:
1940                         name_priority = 0;
1941                         break;
1942                 case AST_PRES_ALLOWED:
1943                         name_priority = 1;
1944                         break;
1945                 case AST_PRES_UNAVAILABLE:
1946                         name_priority = 2;
1947                         break;
1948                 default:
1949                         name_value = AST_PRES_UNAVAILABLE;
1950                         name_priority = 3;
1951                         break;
1952                 }
1953         }
1954
1955         /* Determine number presentation priority. */
1956         if (!id->number.valid) {
1957                 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1958                 number_value = AST_PRES_UNAVAILABLE;
1959                 number_priority = 3;
1960         } else {
1961                 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1962                 number_value = id->number.presentation & AST_PRES_RESTRICTION;
1963                 switch (number_value) {
1964                 case AST_PRES_RESTRICTED:
1965                         number_priority = 0;
1966                         break;
1967                 case AST_PRES_ALLOWED:
1968                         number_priority = 1;
1969                         break;
1970                 case AST_PRES_UNAVAILABLE:
1971                         number_priority = 2;
1972                         break;
1973                 default:
1974                         number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1975                         number_value = AST_PRES_UNAVAILABLE;
1976                         number_priority = 3;
1977                         break;
1978                 }
1979         }
1980
1981         /* Select the wining presentation value. */
1982         if (name_priority < number_priority) {
1983                 number_value = name_value;
1984         }
1985
1986         return number_value | number_screening;
1987 }
1988
1989 void ast_party_dialed_init(struct ast_party_dialed *init)
1990 {
1991         init->number.str = NULL;
1992         init->number.plan = 0;/* Unknown */
1993         ast_party_subaddress_init(&init->subaddress);
1994         init->transit_network_select = 0;
1995 }
1996
1997 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
1998 {
1999         if (dest == src) {
2000                 /* Don't copy to self */
2001                 return;
2002         }
2003
2004         ast_free(dest->number.str);
2005         dest->number.str = ast_strdup(src->number.str);
2006         dest->number.plan = src->number.plan;
2007         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2008         dest->transit_network_select = src->transit_network_select;
2009 }
2010
2011 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2012 {
2013         init->number.str = NULL;
2014         init->number.plan = guide->number.plan;
2015         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2016         init->transit_network_select = guide->transit_network_select;
2017 }
2018
2019 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2020 {
2021         if (src->number.str && src->number.str != dest->number.str) {
2022                 ast_free(dest->number.str);
2023                 dest->number.str = ast_strdup(src->number.str);
2024         }
2025         dest->number.plan = src->number.plan;
2026
2027         ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2028
2029         dest->transit_network_select = src->transit_network_select;
2030 }
2031
2032 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2033 {
2034         ast_free(doomed->number.str);
2035         doomed->number.str = NULL;
2036         ast_party_subaddress_free(&doomed->subaddress);
2037 }
2038
2039 void ast_party_caller_init(struct ast_party_caller *init)
2040 {
2041         ast_party_id_init(&init->id);
2042         ast_party_id_init(&init->ani);
2043         init->ani2 = 0;
2044 }
2045
2046 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2047 {
2048         if (dest == src) {
2049                 /* Don't copy to self */
2050                 return;
2051         }
2052
2053         ast_party_id_copy(&dest->id, &src->id);
2054         ast_party_id_copy(&dest->ani, &src->ani);
2055         dest->ani2 = src->ani2;
2056 }
2057
2058 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2059 {
2060         ast_party_id_set_init(&init->id, &guide->id);
2061         ast_party_id_set_init(&init->ani, &guide->ani);
2062         init->ani2 = guide->ani2;
2063 }
2064
2065 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2066 {
2067         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2068         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2069         dest->ani2 = src->ani2;
2070 }
2071
2072 void ast_party_caller_free(struct ast_party_caller *doomed)
2073 {
2074         ast_party_id_free(&doomed->id);
2075         ast_party_id_free(&doomed->ani);
2076 }
2077
2078 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2079 {
2080         ast_party_id_init(&init->id);
2081         ast_party_id_init(&init->ani);
2082         init->ani2 = 0;
2083         init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2084 }
2085
2086 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2087 {
2088         if (dest == src) {
2089                 /* Don't copy to self */
2090                 return;
2091         }
2092
2093         ast_party_id_copy(&dest->id, &src->id);
2094         ast_party_id_copy(&dest->ani, &src->ani);
2095         dest->ani2 = src->ani2;
2096         dest->source = src->source;
2097 }
2098
2099 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2100 {
2101         ast_party_id_set_init(&init->id, &guide->id);
2102         ast_party_id_set_init(&init->ani, &guide->ani);
2103         init->ani2 = guide->ani2;
2104         init->source = guide->source;
2105 }
2106
2107 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)
2108 {
2109         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2110         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2111         dest->ani2 = src->ani2;
2112         dest->source = src->source;
2113 }
2114
2115 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2116 {
2117         connected->id = caller->id;
2118         connected->ani = caller->ani;
2119         connected->ani2 = caller->ani2;
2120         connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2121 }
2122
2123 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2124 {
2125         ast_party_id_free(&doomed->id);
2126         ast_party_id_free(&doomed->ani);
2127 }
2128
2129 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2130 {
2131         ast_party_id_init(&init->from);
2132         ast_party_id_init(&init->to);
2133         init->count = 0;
2134         init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2135 }
2136
2137 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2138 {
2139         if (dest == src) {
2140                 /* Don't copy to self */
2141                 return;
2142         }
2143
2144         ast_party_id_copy(&dest->from, &src->from);
2145         ast_party_id_copy(&dest->to, &src->to);
2146         dest->count = src->count;
2147         dest->reason = src->reason;
2148 }
2149
2150 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2151 {
2152         ast_party_id_set_init(&init->from, &guide->from);
2153         ast_party_id_set_init(&init->to, &guide->to);
2154         init->count = guide->count;
2155         init->reason = guide->reason;
2156 }
2157
2158 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2159 {
2160         ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2161         ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2162         dest->reason = src->reason;
2163         dest->count = src->count;
2164 }
2165
2166 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2167 {
2168         ast_party_id_free(&doomed->from);
2169         ast_party_id_free(&doomed->to);
2170 }
2171
2172 /*! \brief Free a channel structure */
2173 static void ast_channel_destructor(void *obj)
2174 {
2175         struct ast_channel *chan = obj;
2176         int fd;
2177 #ifdef HAVE_EPOLL
2178         int i;
2179 #endif
2180         struct ast_var_t *vardata;
2181         struct ast_frame *f;
2182         struct varshead *headp;
2183         struct ast_datastore *datastore;
2184         char device_name[AST_CHANNEL_NAME];
2185
2186         if (ast_channel_name(chan)) {
2187                 /* The string fields were initialized. */
2188                 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2189                 ast_cel_check_retire_linkedid(chan);
2190         }
2191
2192         /* Get rid of each of the data stores on the channel */
2193         ast_channel_lock(chan);
2194         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
2195                 /* Free the data store */
2196                 ast_datastore_free(datastore);
2197         ast_channel_unlock(chan);
2198
2199         /* Lock and unlock the channel just to be sure nobody has it locked still
2200            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2201         ast_channel_lock(chan);
2202         ast_channel_unlock(chan);
2203
2204         if (chan->tech_pvt) {
2205                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2206                 ast_free(chan->tech_pvt);
2207         }
2208
2209         if (chan->sched) {
2210                 ast_sched_context_destroy(chan->sched);
2211         }
2212
2213         if (ast_channel_name(chan)) {
2214                 char *dashptr;
2215
2216                 /* The string fields were initialized. */
2217                 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2218                 if ((dashptr = strrchr(device_name, '-'))) {
2219                         *dashptr = '\0';
2220                 }
2221         } else {
2222                 device_name[0] = '\0';
2223         }
2224
2225         /* Stop monitoring */
2226         if (chan->monitor)
2227                 chan->monitor->stop( chan, 0 );
2228
2229         /* If there is native format music-on-hold state, free it */
2230         if (chan->music_state)
2231                 ast_moh_cleanup(chan);
2232
2233         /* Free translators */
2234         if (chan->readtrans)
2235                 ast_translator_free_path(chan->readtrans);
2236         if (chan->writetrans)
2237                 ast_translator_free_path(chan->writetrans);
2238         if (chan->pbx)
2239                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2240
2241         ast_party_dialed_free(&chan->dialed);
2242         ast_party_caller_free(&chan->caller);
2243         ast_party_connected_line_free(&chan->connected);
2244         ast_party_redirecting_free(&chan->redirecting);
2245
2246         /* Close pipes if appropriate */
2247         if ((fd = chan->alertpipe[0]) > -1)
2248                 close(fd);
2249         if ((fd = chan->alertpipe[1]) > -1)
2250                 close(fd);
2251         if (chan->timer) {
2252                 ast_timer_close(chan->timer);
2253         }
2254 #ifdef HAVE_EPOLL
2255         for (i = 0; i < AST_MAX_FDS; i++) {
2256                 if (chan->epfd_data[i])
2257                         free(chan->epfd_data[i]);
2258         }
2259         close(chan->epfd);
2260 #endif
2261         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
2262                 ast_frfree(f);
2263         
2264         /* loop over the variables list, freeing all data and deleting list items */
2265         /* no need to lock the list, as the channel is already locked */
2266         headp = &chan->varshead;
2267         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2268                 ast_var_delete(vardata);
2269
2270         ast_app_group_discard(chan);
2271
2272         /* Destroy the jitterbuffer */
2273         ast_jb_destroy(chan);
2274
2275         if (chan->cdr) {
2276                 ast_cdr_discard(chan->cdr);
2277                 chan->cdr = NULL;
2278         }
2279
2280         if (chan->zone) {
2281                 chan->zone = ast_tone_zone_unref(chan->zone);
2282         }
2283
2284         ast_string_field_free_memory(chan);
2285
2286         if (device_name[0]) {
2287                 /*
2288                  * We have a device name to notify of a new state.
2289                  *
2290                  * Queue an unknown state, because, while we know that this particular
2291                  * instance is dead, we don't know the state of all other possible
2292                  * instances.
2293                  */
2294                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2295         }
2296
2297         chan->nativeformats = ast_format_cap_destroy(chan->nativeformats);
2298 }
2299
2300 /*! \brief Free a dummy channel structure */
2301 static void ast_dummy_channel_destructor(void *obj)
2302 {
2303         struct ast_channel *chan = obj;
2304         struct ast_var_t *vardata;
2305         struct varshead *headp;
2306
2307         headp = &chan->varshead;
2308
2309         ast_party_dialed_free(&chan->dialed);
2310         ast_party_caller_free(&chan->caller);
2311         ast_party_connected_line_free(&chan->connected);
2312         ast_party_redirecting_free(&chan->redirecting);
2313
2314         /* loop over the variables list, freeing all data and deleting list items */
2315         /* no need to lock the list, as the channel is already locked */
2316         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2317                 ast_var_delete(vardata);
2318
2319         if (chan->cdr) {
2320                 ast_cdr_discard(chan->cdr);
2321                 chan->cdr = NULL;
2322         }
2323
2324         ast_string_field_free_memory(chan);
2325 }
2326
2327 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2328 {
2329         return ast_datastore_alloc(info, uid);
2330 }
2331
2332 int ast_channel_datastore_free(struct ast_datastore *datastore)
2333 {
2334         return ast_datastore_free(datastore);
2335 }
2336
2337 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2338 {
2339         struct ast_datastore *datastore = NULL, *datastore2;
2340
2341         AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
2342                 if (datastore->inheritance > 0) {
2343                         datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2344                         if (datastore2) {
2345                                 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2346                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2347                                 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
2348                         }
2349                 }
2350         }
2351         return 0;
2352 }
2353
2354 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2355 {
2356         int res = 0;
2357
2358         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
2359
2360         return res;
2361 }
2362
2363 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2364 {
2365         return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
2366 }
2367
2368 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2369 {
2370         struct ast_datastore *datastore = NULL;
2371         
2372         if (info == NULL)
2373                 return NULL;
2374
2375         AST_LIST_TRAVERSE(&chan->datastores, datastore, entry) {
2376                 if (datastore->info != info) {
2377                         continue;
2378                 }
2379
2380                 if (uid == NULL) {
2381                         /* matched by type only */
2382                         break;
2383                 }
2384
2385                 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2386                         /* Matched by type AND uid */
2387                         break;
2388                 }
2389         }
2390
2391         return datastore;
2392 }
2393
2394 /*! Set the file descriptor on the channel */
2395 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2396 {
2397 #ifdef HAVE_EPOLL
2398         struct epoll_event ev;
2399         struct ast_epoll_data *aed = NULL;
2400
2401         if (chan->fds[which] > -1) {
2402                 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2403                 aed = chan->epfd_data[which];
2404         }
2405
2406         /* If this new fd is valid, add it to the epoll */
2407         if (fd > -1) {
2408                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2409                         return;
2410                 
2411                 chan->epfd_data[which] = aed;
2412                 aed->chan = chan;
2413                 aed->which = which;
2414                 
2415                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2416                 ev.data.ptr = aed;
2417                 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2418         } else if (aed) {
2419                 /* We don't have to keep around this epoll data structure now */
2420                 free(aed);
2421                 chan->epfd_data[which] = NULL;
2422         }
2423 #endif
2424         chan->fds[which] = fd;
2425         return;
2426 }
2427
2428 /*! Add a channel to an optimized waitfor */
2429 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2430 {
2431 #ifdef HAVE_EPOLL
2432         struct epoll_event ev;
2433         int i = 0;
2434
2435         if (chan0->epfd == -1)
2436                 return;
2437
2438         /* Iterate through the file descriptors on chan1, adding them to chan0 */
2439         for (i = 0; i < AST_MAX_FDS; i++) {
2440                 if (chan1->fds[i] == -1)
2441                         continue;
2442                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2443                 ev.data.ptr = chan1->epfd_data[i];
2444                 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2445         }
2446
2447 #endif
2448         return;
2449 }
2450
2451 /*! Delete a channel from an optimized waitfor */
2452 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2453 {
2454 #ifdef HAVE_EPOLL
2455         struct epoll_event ev;
2456         int i = 0;
2457
2458         if (chan0->epfd == -1)
2459                 return;
2460
2461         for (i = 0; i < AST_MAX_FDS; i++) {
2462                 if (chan1->fds[i] == -1)
2463                         continue;
2464                 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2465         }
2466
2467 #endif
2468         return;
2469 }
2470
2471 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2472 {
2473         ast_channel_lock(chan);
2474
2475         chan->_softhangup &= ~flag;
2476
2477         if (!chan->_softhangup) {
2478                 struct ast_frame *fr;
2479
2480                 /* If we have completely cleared the softhangup flag,
2481                  * then we need to fully abort the hangup process.  This requires
2482                  * pulling the END_OF_Q frame out of the channel frame queue if it
2483                  * still happens to be there. */
2484
2485                 fr = AST_LIST_LAST(&chan->readq);
2486                 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2487                                 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2488                         AST_LIST_REMOVE(&chan->readq, fr, frame_list);
2489                         ast_frfree(fr);
2490                 }
2491         }
2492
2493         ast_channel_unlock(chan);
2494 }
2495
2496 /*! \brief Softly hangup a channel, don't lock */
2497 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2498 {
2499         ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2500         /* Inform channel driver that we need to be hung up, if it cares */
2501         chan->_softhangup |= cause;
2502         ast_queue_frame(chan, &ast_null_frame);
2503         /* Interrupt any poll call or such */
2504         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2505                 pthread_kill(chan->blocker, SIGURG);
2506         return 0;
2507 }
2508
2509 /*! \brief Softly hangup a channel, lock */
2510 int ast_softhangup(struct ast_channel *chan, int cause)
2511 {
2512         int res;
2513
2514         ast_channel_lock(chan);
2515         res = ast_softhangup_nolock(chan, cause);
2516         manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2517                 "Channel: %s\r\n"
2518                 "Uniqueid: %s\r\n"
2519                 "Cause: %d\r\n",
2520                 ast_channel_name(chan),
2521                 ast_channel_uniqueid(chan),
2522                 cause);
2523         ast_channel_unlock(chan);
2524
2525         return res;
2526 }
2527
2528 static void free_translation(struct ast_channel *clonechan)
2529 {
2530         if (clonechan->writetrans)
2531                 ast_translator_free_path(clonechan->writetrans);
2532         if (clonechan->readtrans)
2533                 ast_translator_free_path(clonechan->readtrans);
2534         clonechan->writetrans = NULL;
2535         clonechan->readtrans = NULL;
2536         if (ast_format_cap_is_empty(clonechan->nativeformats)) {
2537                 ast_format_clear(&clonechan->rawwriteformat);
2538                 ast_format_clear(&clonechan->rawreadformat);
2539         } else {
2540                 struct ast_format tmpfmt;
2541                 ast_best_codec(clonechan->nativeformats, &tmpfmt);
2542                 ast_format_copy(&clonechan->rawwriteformat, &tmpfmt);
2543                 ast_format_copy(&clonechan->rawreadformat, &tmpfmt);
2544         }
2545 }
2546
2547 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2548 {
2549         struct ast_channel *bridge;
2550
2551         ast_channel_lock(chan);
2552         if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2553                 ast_channel_hangupsource_set(chan, source);
2554         }
2555         bridge = ast_bridged_channel(chan);
2556         ast_channel_unlock(chan);
2557
2558         if (bridge && (force || ast_strlen_zero(ast_channel_hangupsource(bridge)))) {
2559                 ast_channel_lock(bridge);
2560                 ast_channel_hangupsource_set(chan, source);
2561                 ast_channel_unlock(bridge);
2562         }
2563 }
2564
2565 static void destroy_hooks(struct ast_channel *chan)
2566 {
2567         if (chan->audiohooks) {
2568                 ast_audiohook_detach_list(chan->audiohooks);
2569                 chan->audiohooks = NULL;
2570         }
2571
2572         ast_framehook_list_destroy(chan);
2573 }
2574
2575 /*! \brief Hangup a channel */
2576 int ast_hangup(struct ast_channel *chan)
2577 {
2578         char extra_str[64]; /* used for cel logging below */
2579         int was_zombie;
2580
2581         ast_autoservice_stop(chan);
2582
2583         ast_channel_lock(chan);
2584
2585         /*
2586          * Do the masquerade if someone is setup to masquerade into us.
2587          *
2588          * NOTE: We must hold the channel lock after testing for a
2589          * pending masquerade and setting the channel as a zombie to
2590          * prevent __ast_channel_masquerade() from setting up a
2591          * masquerade with a dead channel.
2592          */
2593         while (chan->masq) {
2594                 ast_channel_unlock(chan);
2595                 if (ast_do_masquerade(chan)) {
2596                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2597
2598                         /* Abort the loop or we might never leave. */
2599                         ast_channel_lock(chan);
2600                         break;
2601                 }
2602                 ast_channel_lock(chan);
2603         }
2604
2605         if (chan->masqr) {
2606                 /*
2607                  * This channel is one which will be masqueraded into something.
2608                  * Mark it as a zombie already so ast_do_masquerade() will know
2609                  * to free it later.
2610                  */
2611                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2612                 destroy_hooks(chan);
2613                 ast_channel_unlock(chan);
2614                 return 0;
2615         }
2616
2617         if (!(was_zombie = ast_test_flag(chan, AST_FLAG_ZOMBIE))) {
2618                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2619         }
2620
2621         ast_channel_unlock(chan);
2622         ao2_unlink(channels, chan);
2623         ast_channel_lock(chan);
2624
2625         destroy_hooks(chan);
2626
2627         free_translation(chan);
2628         /* Close audio stream */
2629         if (chan->stream) {
2630                 ast_closestream(chan->stream);
2631                 chan->stream = NULL;
2632         }
2633         /* Close video stream */
2634         if (chan->vstream) {
2635                 ast_closestream(chan->vstream);
2636                 chan->vstream = NULL;
2637         }
2638         if (chan->sched) {
2639                 ast_sched_context_destroy(chan->sched);
2640                 chan->sched = NULL;
2641         }
2642
2643         if (chan->generatordata) {      /* Clear any tone stuff remaining */
2644                 if (chan->generator && chan->generator->release) {
2645                         chan->generator->release(chan, chan->generatordata);
2646                 }
2647         }
2648         chan->generatordata = NULL;
2649         chan->generator = NULL;
2650
2651         snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, ast_channel_hangupsource(chan), S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2652         ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2653
2654         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2655                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2656                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
2657                         (long) pthread_self(), ast_channel_name(chan), (long)chan->blocker, ast_channel_blockproc(chan));
2658                 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2659         }
2660         if (!was_zombie) {
2661                 ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2662
2663                 if (chan->tech->hangup) {
2664                         chan->tech->hangup(chan);
2665                 }
2666         } else {
2667                 ast_debug(1, "Hanging up zombie '%s'\n", ast_channel_name(chan));
2668         }
2669
2670         ast_channel_unlock(chan);
2671
2672         ast_cc_offer(chan);
2673         ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2674                 "Channel: %s\r\n"
2675                 "Uniqueid: %s\r\n"
2676                 "CallerIDNum: %s\r\n"
2677                 "CallerIDName: %s\r\n"
2678                 "ConnectedLineNum: %s\r\n"
2679                 "ConnectedLineName: %s\r\n"
2680                 "Cause: %d\r\n"
2681                 "Cause-txt: %s\r\n",
2682                 ast_channel_name(chan),
2683                 ast_channel_uniqueid(chan),
2684                 S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<unknown>"),
2685                 S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, "<unknown>"),
2686                 S_COR(chan->connected.id.number.valid, chan->connected.id.number.str, "<unknown>"),
2687                 S_COR(chan->connected.id.name.valid, chan->connected.id.name.str, "<unknown>"),
2688                 chan->hangupcause,
2689                 ast_cause2str(chan->hangupcause)
2690                 );
2691
2692         if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
2693                 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
2694                 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2695                 ast_channel_lock(chan);
2696                 ast_cdr_end(chan->cdr);
2697                 ast_cdr_detach(chan->cdr);
2698                 chan->cdr = NULL;
2699                 ast_channel_unlock(chan);
2700         }
2701
2702         ast_channel_unref(chan);
2703
2704         return 0;
2705 }
2706
2707 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2708 {
2709         int res = 0;
2710
2711         ast_channel_lock(chan);
2712
2713         /* You can't answer an outbound call */
2714         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2715                 ast_channel_unlock(chan);
2716                 return 0;
2717         }
2718
2719         /* Stop if we're a zombie or need a soft hangup */
2720         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2721                 ast_channel_unlock(chan);
2722                 return -1;
2723         }
2724
2725         ast_channel_unlock(chan);
2726
2727         switch (chan->_state) {
2728         case AST_STATE_RINGING:
2729         case AST_STATE_RING:
2730                 ast_channel_lock(chan);
2731                 if (chan->tech->answer) {
2732                         res = chan->tech->answer(chan);
2733                 }
2734                 ast_setstate(chan, AST_STATE_UP);
2735                 if (cdr_answer) {
2736                         ast_cdr_answer(chan->cdr);
2737                 }
2738                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2739                 ast_channel_unlock(chan);
2740                 break;
2741         case AST_STATE_UP:
2742                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2743                 /* Calling ast_cdr_answer when it it has previously been called
2744                  * is essentially a no-op, so it is safe.
2745                  */
2746                 if (cdr_answer) {
2747                         ast_cdr_answer(chan->cdr);
2748                 }
2749                 break;
2750         default:
2751                 break;
2752         }
2753
2754         ast_indicate(chan, -1);
2755
2756         return res;
2757 }
2758
2759 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2760 {
2761         int res = 0;
2762         enum ast_channel_state old_state;
2763
2764         old_state = chan->_state;
2765         if ((res = ast_raw_answer(chan, cdr_answer))) {
2766                 return res;
2767         }
2768
2769         switch (old_state) {
2770         case AST_STATE_RINGING:
2771         case AST_STATE_RING:
2772                 /* wait for media to start flowing, but don't wait any longer
2773                  * than 'delay' or 500 milliseconds, whichever is longer
2774                  */
2775                 do {
2776                         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2777                         struct ast_frame *cur, *new;
2778                         int ms = MAX(delay, 500);
2779                         unsigned int done = 0;
2780
2781                         AST_LIST_HEAD_INIT_NOLOCK(&frames);
2782
2783                         for (;;) {
2784                                 ms = ast_waitfor(chan, ms);
2785                                 if (ms < 0) {
2786                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2787                                         res = -1;
2788                                         break;
2789                                 }
2790                                 if (ms == 0) {
2791                                         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));
2792                                         break;
2793                                 }
2794                                 cur = ast_read(chan);
2795                                 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2796                                              (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2797                                         if (cur) {
2798                                                 ast_frfree(cur);
2799                                         }
2800                                         res = -1;
2801                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2802                                         break;
2803                                 }
2804
2805                                 if ((new = ast_frisolate(cur)) != cur) {
2806                                         ast_frfree(cur);
2807                                 }
2808
2809                                 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2810
2811                                 /* if a specific delay period was requested, continue
2812                                  * until that delay has passed. don't stop just because
2813                                  * incoming media has arrived.
2814                                  */
2815                                 if (delay) {
2816                                         continue;
2817                                 }
2818
2819                                 switch (new->frametype) {
2820                                         /* all of these frametypes qualify as 'media' */
2821                                 case AST_FRAME_VOICE:
2822                                 case AST_FRAME_VIDEO:
2823                                 case AST_FRAME_TEXT:
2824                                 case AST_FRAME_DTMF_BEGIN:
2825                                 case AST_FRAME_DTMF_END:
2826                                 case AST_FRAME_IMAGE:
2827                                 case AST_FRAME_HTML:
2828                                 case AST_FRAME_MODEM:
2829                                         done = 1;
2830                                         break;
2831                                 case AST_FRAME_CONTROL:
2832                                 case AST_FRAME_IAX:
2833                                 case AST_FRAME_NULL:
2834                                 case AST_FRAME_CNG:
2835                                         break;
2836                                 }
2837
2838                                 if (done) {
2839                                         break;
2840                                 }
2841                         }
2842
2843                         if (res == 0) {
2844                                 ast_channel_lock(chan);
2845                                 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2846                                         ast_queue_frame_head(chan, cur);
2847                                         ast_frfree(cur);
2848                                 }
2849                                 ast_channel_unlock(chan);
2850                         }
2851                 } while (0);
2852                 break;
2853         default:
2854                 break;
2855         }
2856
2857         return res;
2858 }
2859
2860 int ast_answer(struct ast_channel *chan)
2861 {
2862         return __ast_answer(chan, 0, 1);
2863 }
2864
2865 void ast_deactivate_generator(struct ast_channel *chan)
2866 {
2867         ast_channel_lock(chan);
2868         if (chan->generatordata) {
2869                 if (chan->generator && chan->generator->release)
2870                         chan->generator->release(chan, chan->generatordata);
2871                 chan->generatordata = NULL;
2872                 chan->generator = NULL;
2873                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2874                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2875                 ast_settimeout(chan, 0, NULL, NULL);
2876         }
2877         ast_channel_unlock(chan);
2878 }
2879
2880 static void generator_write_format_change(struct ast_channel *chan)
2881 {
2882         ast_channel_lock(chan);
2883         if (chan->generator && chan->generator->write_format_change) {
2884                 chan->generator->write_format_change(chan, chan->generatordata);
2885         }
2886         ast_channel_unlock(chan);
2887 }
2888
2889 static int generator_force(const void *data)
2890 {
2891         /* Called if generator doesn't have data */
2892         void *tmp;
2893         int res;
2894         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2895         struct ast_channel *chan = (struct ast_channel *)data;
2896
2897         ast_channel_lock(chan);
2898         tmp = chan->generatordata;
2899         chan->generatordata = NULL;
2900         if (chan->generator)
2901                 generate = chan->generator->generate;
2902         ast_channel_unlock(chan);
2903
2904         if (!tmp || !generate)
2905                 return 0;
2906
2907         res = generate(chan, tmp, 0, ast_format_rate(&chan->writeformat) / 50);
2908
2909         chan->generatordata = tmp;
2910
2911         if (res) {
2912                 ast_debug(1, "Auto-deactivating generator\n");
2913                 ast_deactivate_generator(chan);
2914         }
2915
2916         return 0;
2917 }
2918
2919 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2920 {
2921         int res = 0;
2922
2923         ast_channel_lock(chan);
2924         if (chan->generatordata) {
2925                 if (chan->generator && chan->generator->release)
2926                         chan->generator->release(chan, chan->generatordata);
2927                 chan->generatordata = NULL;
2928         }
2929         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2930                 res = -1;
2931         }
2932         if (!res) {
2933                 ast_settimeout(chan, 50, generator_force, chan);
2934                 chan->generator = gen;
2935         }
2936         ast_channel_unlock(chan);
2937
2938         ast_prod(chan);
2939
2940         return res;
2941 }
2942
2943 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
2944 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2945 {
2946         int winner = -1;
2947         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2948         return winner;
2949 }
2950
2951 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
2952 #ifdef HAVE_EPOLL
2953 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2954                                         int *exception, int *outfd, int *ms)
2955 #else
2956 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2957                                         int *exception, int *outfd, int *ms)
2958 #endif
2959 {
2960         struct timeval start = { 0 , 0 };
2961         struct pollfd *pfds = NULL;
2962         int res;
2963         long rms;
2964         int x, y, max;
2965         int sz;
2966         struct timeval now = { 0, 0 };
2967         struct timeval whentohangup = { 0, 0 }, diff;
2968         struct ast_channel *winner = NULL;
2969         struct fdmap {
2970                 int chan;
2971                 int fdno;
2972         } *fdmap = NULL;
2973
2974         if ((sz = n * AST_MAX_FDS + nfds)) {
2975                 pfds = alloca(sizeof(*pfds) * sz);
2976                 fdmap = alloca(sizeof(*fdmap) * sz);
2977         }
2978
2979         if (outfd)
2980                 *outfd = -99999;
2981         if (exception)
2982                 *exception = 0;
2983         
2984         /* Perform any pending masquerades */
2985         for (x = 0; x < n; x++) {
2986                 if (c[x]->masq && ast_do_masquerade(c[x])) {
2987                         ast_log(LOG_WARNING, "Masquerade failed\n");
2988                         *ms = -1;
2989                         return NULL;
2990                 }
2991
2992                 ast_channel_lock(c[x]);
2993                 if (!ast_tvzero(c[x]->whentohangup)) {
2994                         if (ast_tvzero(whentohangup))
2995                                 now = ast_tvnow();
2996                         diff = ast_tvsub(c[x]->whentohangup, now);
2997                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
2998                                 /* Should already be hungup */
2999                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3000                                 ast_channel_unlock(c[x]);
3001                                 return c[x];
3002                         }
3003                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3004                                 whentohangup = diff;
3005                 }
3006                 ast_channel_unlock(c[x]);
3007         }
3008         /* Wait full interval */
3009         rms = *ms;
3010         /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3011         if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3012                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
3013                 if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
3014                         rms =  *ms;
3015                 }
3016         } else if (!ast_tvzero(whentohangup) && rms < 0) {
3017                 /* Tiny corner case... call would need to last >24 days */
3018                 rms = INT_MAX;
3019         }
3020         /*
3021          * Build the pollfd array, putting the channels' fds first,
3022          * followed by individual fds. Order is important because
3023          * individual fd's must have priority over channel fds.
3024          */
3025         max = 0;
3026         for (x = 0; x < n; x++) {
3027                 for (y = 0; y < AST_MAX_FDS; y++) {
3028                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
3029                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
3030                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
3031                 }
3032                 CHECK_BLOCKING(c[x]);
3033         }
3034         /* Add the individual fds */
3035         for (x = 0; x < nfds; x++) {
3036                 fdmap[max].chan = -1;
3037                 max += ast_add_fd(&pfds[max], fds[x]);
3038         }
3039
3040         if (*ms > 0)
3041                 start = ast_tvnow();
3042         
3043         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3044                 do {
3045                         int kbrms = rms;
3046                         if (kbrms > 600000)
3047                                 kbrms = 600000;
3048                         res = ast_poll(pfds, max, kbrms);
3049                         if (!res)
3050                                 rms -= kbrms;
3051                 } while (!res && (rms > 0));
3052         } else {
3053                 res = ast_poll(pfds, max, rms);
3054         }
3055         for (x = 0; x < n; x++)
3056                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
3057         if (res < 0) { /* Simulate a timeout if we were interrupted */
3058                 if (errno != EINTR)
3059                         *ms = -1;
3060                 return NULL;
3061         }
3062         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
3063                 now = ast_tvnow();
3064                 for (x = 0; x < n; x++) {
3065                         if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
3066                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3067                                 if (winner == NULL)
3068                                         winner = c[x];
3069                         }
3070                 }
3071         }
3072         if (res == 0) { /* no fd ready, reset timeout and done */
3073                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
3074                 return winner;
3075         }
3076         /*
3077          * Then check if any channel or fd has a pending event.
3078          * Remember to check channels first and fds last, as they
3079          * must have priority on setting 'winner'
3080          */
3081         for (x = 0; x < max; x++) {
3082                 res = pfds[x].revents;
3083                 if (res == 0)
3084                         continue;
3085                 if (fdmap[x].chan >= 0) {       /* this is a channel */
3086                         winner = c[fdmap[x].chan];      /* override previous winners */
3087                         if (res & POLLPRI)
3088                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
3089                         else
3090                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3091                         winner->fdno = fdmap[x].fdno;
3092                 } else {                        /* this is an fd */
3093                         if (outfd)
3094                                 *outfd = pfds[x].fd;
3095                         if (exception)
3096                                 *exception = (res & POLLPRI) ? -1 : 0;
3097                         winner = NULL;
3098                 }
3099         }
3100         if (*ms > 0) {
3101                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3102                 if (*ms < 0)
3103                         *ms = 0;
3104         }
3105         return winner;
3106 }
3107
3108 #ifdef HAVE_EPOLL
3109 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3110 {
3111         struct timeval start = { 0 , 0 };
3112         int res = 0;
3113         struct epoll_event ev[1];
3114         long diff, rms = *ms;
3115         struct ast_channel *winner = NULL;
3116         struct ast_epoll_data *aed = NULL;
3117
3118
3119         /* See if this channel needs to be masqueraded */
3120         if (chan->masq && ast_do_masquerade(chan)) {
3121                 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", ast_channel_name(chan));
3122                 *ms = -1;
3123                 return NULL;
3124         }
3125
3126         ast_channel_lock(chan);
3127         /* Figure out their timeout */
3128         if (!ast_tvzero(chan->whentohangup)) {
3129                 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
3130                         /* They should already be hungup! */
3131                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3132                         ast_channel_unlock(chan);
3133                         return NULL;
3134                 }
3135                 /* If this value is smaller then the current one... make it priority */
3136                 if (rms > diff)
3137                         rms = diff;
3138         }
3139
3140         ast_channel_unlock(chan);
3141
3142         /* Time to make this channel block... */
3143         CHECK_BLOCKING(chan);
3144
3145         if (*ms > 0)
3146                 start = ast_tvnow();
3147
3148         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3149         res = epoll_wait(chan->epfd, ev, 1, rms);
3150
3151         /* Stop blocking */
3152         ast_clear_flag(chan, AST_FLAG_BLOCKING);
3153
3154         /* Simulate a timeout if we were interrupted */
3155         if (res < 0) {
3156                 if (errno != EINTR)
3157                         *ms = -1;
3158                 return NULL;
3159         }
3160
3161         /* If this channel has a timeout see if it expired */
3162         if (!ast_tvzero(chan->whentohangup)) {
3163                 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
3164                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3165                         winner = chan;
3166                 }
3167         }
3168
3169         /* No fd ready, reset timeout and be done for now */
3170         if (!res) {
3171                 *ms = 0;
3172                 return winner;
3173         }
3174
3175         /* See what events are pending */
3176         aed = ev[0].data.ptr;
3177         chan->fdno = aed->which;
3178         if (ev[0].events & EPOLLPRI)
3179                 ast_set_flag(chan, AST_FLAG_EXCEPTION);
3180         else
3181                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3182
3183         if (*ms > 0) {
3184                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3185                 if (*ms < 0)
3186                         *ms = 0;
3187         }
3188
3189         return chan;
3190 }
3191
3192 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3193 {
3194         struct timeval start = { 0 , 0 };
3195         int res = 0, i;
3196         struct epoll_event ev[25] = { { 0, } };
3197         struct timeval now = { 0, 0 };
3198         long whentohangup = 0, diff = 0, rms = *ms;
3199         struct ast_channel *winner = NULL;
3200
3201         for (i = 0; i < n; i++) {
3202                 if (c[i]->masq && ast_do_masquerade(c[i])) {
3203                         ast_log(LOG_WARNING, "Masquerade failed\n");
3204                         *ms = -1;
3205                         return NULL;
3206                 }
3207
3208                 ast_channel_lock(c[i]);
3209                 if (!ast_tvzero(c[i]->whentohangup)) {
3210                         if (whentohangup == 0)
3211                                 now = ast_tvnow();
3212                         if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
3213                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3214                                 ast_channel_unlock(c[i]);
3215                                 return c[i];
3216                         }
3217                         if (!whentohangup || whentohangup > diff)
3218                                 whentohangup = diff;
3219                 }
3220                 ast_channel_unlock(c[i]);
3221                 CHECK_BLOCKING(c[i]);
3222         }
3223
3224         rms = *ms;
3225         if (whentohangup) {
3226                 rms = whentohangup;
3227                 if (*ms >= 0 && *ms < rms)
3228                         rms = *ms;
3229         }
3230
3231         if (*ms > 0)
3232                 start = ast_tvnow();
3233
3234         res = epoll_wait(c[0]->epfd, ev, 25, rms);
3235
3236         for (i = 0; i < n; i++)
3237                 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
3238
3239         if (res < 0) {
3240                 if (errno != EINTR)
3241                         *ms = -1;
3242                 return NULL;
3243         }
3244
3245         if (whentohangup) {
3246                 now = ast_tvnow();
3247                 for (i = 0; i < n; i++) {
3248                         if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
3249                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3250                                 if (!winner)
3251                                         winner = c[i];
3252                         }
3253                 }
3254         }
3255
3256         if (!res) {
3257                 *ms = 0;
3258                 return winner;
3259         }
3260
3261         for (i = 0; i < res; i++) {
3262                 struct ast_epoll_data *aed = ev[i].data.ptr;
3263
3264                 if (!ev[i].events || !aed)
3265                         continue;
3266
3267                 winner = aed->chan;
3268                 if (ev[i].events & EPOLLPRI)
3269                         ast_set_flag(winner, AST_FLAG_EXCEPTION);
3270                 else
3271                         ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3272                 winner->fdno = aed->which;
3273         }
3274
3275         if (*ms > 0) {
3276                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3277                 if (*ms < 0)
3278                         *ms = 0;
3279         }
3280
3281         return winner;
3282 }
3283
3284 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3285                                         int *exception, int *outfd, int *ms)
3286 {
3287         /* Clear all provided values in one place. */
3288         if (outfd)
3289                 *outfd = -99999;
3290         if (exception)
3291                 *exception = 0;
3292
3293         /* If no epoll file descriptor is available resort to classic nandfds */
3294         if (!n || nfds || c[0]->epfd == -1)
3295                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3296         else if (!nfds && n == 1)
3297                 return ast_waitfor_nandfds_simple(c[0], ms);
3298         else
3299                 return ast_waitfor_nandfds_complex(c, n, ms);
3300 }
3301 #endif
3302
3303 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3304 {
3305         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3306 }
3307
3308 int ast_waitfor(struct ast_channel *c, int ms)
3309 {
3310         int oldms = ms; /* -1 if no timeout */
3311
3312         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3313         if ((ms < 0) && (oldms < 0))
3314                 ms = 0;
3315         return ms;
3316 }
3317
3318 /* XXX never to be called with ms = -1 */
3319 int ast_waitfordigit(struct ast_channel *c, int ms)
3320 {
3321         return ast_waitfordigit_full(c, ms, -1, -1);
3322 }
3323
3324 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3325 {
3326         int res;
3327         unsigned int real_rate = rate, max_rate;
3328
3329         ast_channel_lock(c);
3330
3331         if (c->timingfd == -1) {
3332                 ast_channel_unlock(c);
3333                 return -1;
3334         }
3335
3336         if (!func) {
3337                 rate = 0;
3338                 data = NULL;
3339         }
3340
3341         if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
3342                 real_rate = max_rate;
3343         }
3344
3345         ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3346
3347         res = ast_timer_set_rate(c->timer, real_rate);
3348
3349         c->timingfunc = func;
3350         c->timingdata = data;
3351
3352         ast_channel_unlock(c);
3353
3354         return res;