a37f33ac23b173863877f828b0ada2f138ad15b5
[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, chan->context)) ||
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", chan->context);
525                 else
526                         ast_debug(1, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
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, chan->context, sizeof(trace->context));
533                 ast_copy_string(trace->exten, chan->exten, 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         if (!ast_strlen_zero(context))
1092                 ast_copy_string(tmp->context, context, sizeof(tmp->context));
1093         else
1094                 strcpy(tmp->context, "default");
1095
1096         if (!ast_strlen_zero(exten))
1097                 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
1098         else
1099                 strcpy(tmp->exten, "s");
1100
1101         tmp->priority = 1;
1102
1103         tmp->cdr = ast_cdr_alloc();
1104         ast_cdr_init(tmp->cdr, tmp);
1105         ast_cdr_start(tmp->cdr);
1106
1107         ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1108
1109         headp = &tmp->varshead;
1110         AST_LIST_HEAD_INIT_NOLOCK(headp);
1111         
1112         AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
1113
1114         AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
1115         
1116         ast_channel_language_set(tmp, defaultlanguage);
1117
1118         tmp->tech = &null_tech;
1119
1120         ao2_link(channels, tmp);
1121
1122         /*
1123          * And now, since the channel structure is built, and has its name, let's
1124          * call the manager event generator with this Newchannel event. This is the
1125          * proper and correct place to make this call, but you sure do have to pass
1126          * a lot of data into this func to do it here!
1127          */
1128         if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1129                 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1130                         "Channel: %s\r\n"
1131                         "ChannelState: %d\r\n"
1132                         "ChannelStateDesc: %s\r\n"
1133                         "CallerIDNum: %s\r\n"
1134                         "CallerIDName: %s\r\n"
1135                         "AccountCode: %s\r\n"
1136                         "Exten: %s\r\n"
1137                         "Context: %s\r\n"
1138                         "Uniqueid: %s\r\n",
1139                         ast_channel_name(tmp), 
1140                         state, 
1141                         ast_state2str(state),
1142                         S_OR(cid_num, ""),
1143                         S_OR(cid_name, ""),
1144                         ast_channel_accountcode(tmp),
1145                         S_OR(exten, ""),
1146                         S_OR(context, ""),
1147                         ast_channel_uniqueid(tmp));
1148         }
1149
1150         return tmp;
1151 }
1152
1153 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1154                                         const char *cid_name, const char *acctcode,
1155                                         const char *exten, const char *context,
1156                                         const char *linkedid, const int amaflag,
1157                                         const char *file, int line, const char *function,
1158                                         const char *name_fmt, ...)
1159 {
1160         va_list ap;
1161         struct ast_channel *result;
1162
1163         va_start(ap, name_fmt);
1164         result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1165                                         linkedid, amaflag, file, line, function, name_fmt, ap);
1166         va_end(ap);
1167
1168         return result;
1169 }
1170
1171 /* only do the minimum amount of work needed here to make a channel
1172  * structure that can be used to expand channel vars */
1173 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1174 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1175 #else
1176 struct ast_channel *ast_dummy_channel_alloc(void)
1177 #endif
1178 {
1179         struct ast_channel *tmp;
1180         struct varshead *headp;
1181
1182 #if defined(REF_DEBUG)
1183         tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1184                 file, line, function, 1);
1185 #elif defined(__AST_DEBUG_MALLOC)
1186         tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1187                 file, line, function, 0);
1188 #else
1189         tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor);
1190 #endif
1191         if (!tmp) {
1192                 /* Dummy channel structure allocation failure. */
1193                 return NULL;
1194         }
1195
1196         if ((ast_string_field_init(tmp, 128))) {
1197                 return ast_channel_unref(tmp);
1198         }
1199
1200         headp = &tmp->varshead;
1201         AST_LIST_HEAD_INIT_NOLOCK(headp);
1202
1203         return tmp;
1204 }
1205
1206 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1207 {
1208         struct ast_frame *f;
1209         struct ast_frame *cur;
1210         unsigned int new_frames = 0;
1211         unsigned int new_voice_frames = 0;
1212         unsigned int queued_frames = 0;
1213         unsigned int queued_voice_frames = 0;
1214         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1215
1216         ast_channel_lock(chan);
1217
1218         /*
1219          * Check the last frame on the queue if we are queuing the new
1220          * frames after it.
1221          */
1222         cur = AST_LIST_LAST(&chan->readq);
1223         if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1224                 switch (cur->subclass.integer) {
1225                 case AST_CONTROL_END_OF_Q:
1226                         if (fin->frametype == AST_FRAME_CONTROL
1227                                 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1228                                 /*
1229                                  * Destroy the end-of-Q marker frame so we can queue the hangup
1230                                  * frame in its place.
1231                                  */
1232                                 AST_LIST_REMOVE(&chan->readq, cur, frame_list);
1233                                 ast_frfree(cur);
1234
1235                                 /*
1236                                  * This has degenerated to a normal queue append anyway.  Since
1237                                  * we just destroyed the last frame in the queue we must make
1238                                  * sure that "after" is NULL or bad things will happen.
1239                                  */
1240                                 after = NULL;
1241                                 break;
1242                         }
1243                         /* Fall through */
1244                 case AST_CONTROL_HANGUP:
1245                         /* Don't queue anything. */
1246                         ast_channel_unlock(chan);
1247                         return 0;
1248                 default:
1249                         break;
1250                 }
1251         }
1252
1253         /* Build copies of all the new frames and count them */
1254         AST_LIST_HEAD_INIT_NOLOCK(&frames);
1255         for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1256                 if (!(f = ast_frdup(cur))) {
1257                         if (AST_LIST_FIRST(&frames)) {
1258                                 ast_frfree(AST_LIST_FIRST(&frames));
1259                         }
1260                         ast_channel_unlock(chan);
1261                         return -1;
1262                 }
1263
1264                 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1265                 new_frames++;
1266                 if (f->frametype == AST_FRAME_VOICE) {
1267                         new_voice_frames++;
1268                 }
1269         }
1270
1271         /* Count how many frames exist on the queue */
1272         AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1273                 queued_frames++;
1274                 if (cur->frametype == AST_FRAME_VOICE) {
1275                         queued_voice_frames++;
1276                 }
1277         }
1278
1279         if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1280                 int count = 0;
1281                 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
1282                 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
1283                         /* Save the most recent frame */
1284                         if (!AST_LIST_NEXT(cur, frame_list)) {
1285                                 break;
1286                         } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1287                                 if (++count > 64) {
1288                                         break;
1289                                 }
1290                                 AST_LIST_REMOVE_CURRENT(frame_list);
1291                                 ast_frfree(cur);
1292                         }
1293                 }
1294                 AST_LIST_TRAVERSE_SAFE_END;
1295         }
1296
1297         if (after) {
1298                 AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1299         } else {
1300                 if (head) {
1301                         AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1302                         AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1303                 }
1304                 AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1305         }
1306
1307         if (chan->alertpipe[1] > -1) {
1308                 int blah[new_frames];
1309
1310                 memset(blah, 1, sizeof(blah));
1311                 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != (sizeof(blah))) {
1312                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1313                                 ast_channel_name(chan), queued_frames, strerror(errno));
1314                 }
1315         } else if (chan->timingfd > -1) {
1316                 ast_timer_enable_continuous(chan->timer);
1317         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1318                 pthread_kill(chan->blocker, SIGURG);
1319         }
1320
1321         ast_channel_unlock(chan);
1322
1323         return 0;
1324 }
1325
1326 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1327 {
1328         return __ast_queue_frame(chan, fin, 0, NULL);
1329 }
1330
1331 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1332 {
1333         return __ast_queue_frame(chan, fin, 1, NULL);
1334 }
1335
1336 /*! \brief Queue a hangup frame for channel */
1337 int ast_queue_hangup(struct ast_channel *chan)
1338 {
1339         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1340         /* Yeah, let's not change a lock-critical value without locking */
1341         if (!ast_channel_trylock(chan)) {
1342                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1343                 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1344                         "Channel: %s\r\n"
1345                         "Uniqueid: %s\r\n",
1346                         ast_channel_name(chan),
1347                         ast_channel_uniqueid(chan));
1348                 ast_channel_unlock(chan);
1349         }
1350         return ast_queue_frame(chan, &f);
1351 }
1352
1353 /*! \brief Queue a hangup frame for channel */
1354 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1355 {
1356         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1357
1358         if (cause >= 0)
1359                 f.data.uint32 = cause;
1360
1361         /* Yeah, let's not change a lock-critical value without locking */
1362         if (!ast_channel_trylock(chan)) {
1363                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1364                 if (cause < 0)
1365                         f.data.uint32 = chan->hangupcause;
1366
1367                 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1368                         "Channel: %s\r\n"
1369                         "Uniqueid: %s\r\n"
1370                         "Cause: %d\r\n",
1371                         ast_channel_name(chan),
1372                         ast_channel_uniqueid(chan),
1373                         cause);
1374                 ast_channel_unlock(chan);
1375         }
1376
1377         return ast_queue_frame(chan, &f);
1378 }
1379
1380 /*! \brief Queue a control frame */
1381 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1382 {
1383         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1384         return ast_queue_frame(chan, &f);
1385 }
1386
1387 /*! \brief Queue a control frame with payload */
1388 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1389                            const void *data, size_t datalen)
1390 {
1391         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1392         return ast_queue_frame(chan, &f);
1393 }
1394
1395 /*! \brief Set defer DTMF flag on channel */
1396 int ast_channel_defer_dtmf(struct ast_channel *chan)
1397 {
1398         int pre = 0;
1399
1400         if (chan) {
1401                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1402                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1403         }
1404         return pre;
1405 }
1406
1407 /*! \brief Unset defer DTMF flag on channel */
1408 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1409 {
1410         if (chan)
1411                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1412 }
1413
1414 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1415                 void *data, int ao2_flags)
1416 {
1417         return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1418 }
1419
1420 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
1421 {
1422         struct ast_channel *chan = obj;
1423         const char *name = arg;
1424         size_t name_len = *(size_t *) data;
1425         int ret = CMP_MATCH;
1426
1427         if (ast_strlen_zero(name)) {
1428                 ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
1429                 return CMP_STOP;
1430         }
1431
1432         ast_channel_lock(chan);
1433         if ((!name_len && strcasecmp(ast_channel_name(chan), name))
1434                 || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
1435                 ret = 0; /* name match failed, keep looking */
1436         }
1437         ast_channel_unlock(chan);
1438
1439         return ret;
1440 }
1441
1442 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
1443 {
1444         struct ast_channel *chan = obj;
1445         char *context = arg;
1446         char *exten = data;
1447         int ret = CMP_MATCH;
1448
1449         if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
1450                 ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
1451                 return CMP_STOP;
1452         }
1453
1454         ast_channel_lock(chan);
1455         if (strcasecmp(chan->context, context) && strcasecmp(chan->macrocontext, context)) {
1456                 ret = 0; /* Context match failed, continue */
1457         } else if (strcasecmp(chan->exten, exten) && strcasecmp(chan->macroexten, exten)) {
1458                 ret = 0; /* Extension match failed, continue */
1459         }
1460         ast_channel_unlock(chan);
1461
1462         return ret;
1463 }
1464
1465 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
1466 {
1467         struct ast_channel *chan = obj;
1468         char *uniqueid = arg;
1469         size_t id_len = *(size_t *) data;
1470         int ret = CMP_MATCH;
1471
1472         if (ast_strlen_zero(uniqueid)) {
1473                 ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
1474                 return CMP_STOP;
1475         }
1476
1477         ast_channel_lock(chan);
1478         if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
1479                 || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
1480                 ret = 0; /* uniqueid match failed, keep looking */
1481         }
1482         ast_channel_unlock(chan);
1483
1484         return ret;
1485 }
1486
1487 struct ast_channel_iterator {
1488         /* storage for non-dynamically allocated iterator */
1489         struct ao2_iterator simple_iterator;
1490         /* pointer to the actual iterator (simple_iterator or a dynamically
1491          * allocated iterator)
1492          */
1493         struct ao2_iterator *active_iterator;
1494 };
1495
1496 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1497 {
1498         ao2_iterator_destroy(i->active_iterator);
1499         ast_free(i);
1500
1501         return NULL;
1502 }
1503
1504 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1505 {
1506         struct ast_channel_iterator *i;
1507         char *l_exten = (char *) exten;
1508         char *l_context = (char *) context;
1509
1510         if (!(i = ast_calloc(1, sizeof(*i)))) {
1511                 return NULL;
1512         }
1513
1514         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
1515                 l_context, l_exten, OBJ_MULTIPLE);
1516         if (!i->active_iterator) {
1517                 ast_free(i);
1518                 return NULL;
1519         }
1520
1521         return i;
1522 }
1523
1524 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1525 {
1526         struct ast_channel_iterator *i;
1527         char *l_name = (char *) name;
1528
1529         if (!(i = ast_calloc(1, sizeof(*i)))) {
1530                 return NULL;
1531         }
1532
1533         i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
1534                 l_name, &name_len,
1535                 OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
1536         if (!i->active_iterator) {
1537                 ast_free(i);
1538                 return NULL;
1539         }
1540
1541         return i;
1542 }
1543
1544 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1545 {
1546         struct ast_channel_iterator *i;
1547
1548         if (!(i = ast_calloc(1, sizeof(*i)))) {
1549                 return NULL;
1550         }
1551
1552         i->simple_iterator = ao2_iterator_init(channels, 0);
1553         i->active_iterator = &i->simple_iterator;
1554
1555         return i;
1556 }
1557
1558 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1559 {
1560         return ao2_iterator_next(i->active_iterator);
1561 }
1562
1563 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
1564 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1565 {
1566         ast_log(LOG_ERROR, "BUG! Should never be called!\n");
1567         return CMP_STOP;
1568 }
1569
1570 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1571 {
1572         struct ast_channel *chan;
1573         char *l_name = (char *) name;
1574
1575         chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
1576                 (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
1577         if (chan) {
1578                 return chan;
1579         }
1580
1581         if (ast_strlen_zero(l_name)) {
1582                 /* We didn't have a name to search for so quit. */
1583                 return NULL;
1584         }
1585
1586         /* Now try a search for uniqueid. */
1587         return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
1588 }
1589
1590 struct ast_channel *ast_channel_get_by_name(const char *name)
1591 {
1592         return ast_channel_get_by_name_prefix(name, 0);
1593 }
1594
1595 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1596 {
1597         char *l_exten = (char *) exten;
1598         char *l_context = (char *) context;
1599
1600         return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
1601 }
1602
1603 int ast_is_deferrable_frame(const struct ast_frame *frame)
1604 {
1605         /* Do not add a default entry in this switch statement.  Each new
1606          * frame type should be addressed directly as to whether it should
1607          * be queued up or not.
1608          */
1609         switch (frame->frametype) {
1610         case AST_FRAME_CONTROL:
1611         case AST_FRAME_TEXT:
1612         case AST_FRAME_IMAGE:
1613         case AST_FRAME_HTML:
1614                 return 1;
1615
1616         case AST_FRAME_DTMF_END:
1617         case AST_FRAME_DTMF_BEGIN:
1618         case AST_FRAME_VOICE:
1619         case AST_FRAME_VIDEO:
1620         case AST_FRAME_NULL:
1621         case AST_FRAME_IAX:
1622         case AST_FRAME_CNG:
1623         case AST_FRAME_MODEM:
1624                 return 0;
1625         }
1626         return 0;
1627 }
1628
1629 /*! \brief Wait, look for hangups and condition arg */
1630 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1631 {
1632         struct ast_frame *f;
1633         struct ast_silence_generator *silgen = NULL;
1634         int res = 0;
1635         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1636
1637         AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1638
1639         /* If no other generator is present, start silencegen while waiting */
1640         if (ast_opt_transmit_silence && !chan->generatordata) {
1641                 silgen = ast_channel_start_silence_generator(chan);
1642         }
1643
1644         while (ms > 0) {
1645                 struct ast_frame *dup_f = NULL;
1646                 if (cond && ((*cond)(data) == 0)) {
1647                         break;
1648                 }
1649                 ms = ast_waitfor(chan, ms);
1650                 if (ms < 0) {
1651                         res = -1;
1652                         break;
1653                 }
1654                 if (ms > 0) {
1655                         f = ast_read(chan);
1656                         if (!f) {
1657                                 res = -1;
1658                                 break;
1659                         }
1660
1661                         if (!ast_is_deferrable_frame(f)) {
1662                                 ast_frfree(f);
1663                                 continue;
1664                         }
1665                         
1666                         if ((dup_f = ast_frisolate(f))) {
1667                                 if (dup_f != f) {
1668                                         ast_frfree(f);
1669                                 }
1670                                 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1671                         }
1672                 }
1673         }
1674
1675         /* stop silgen if present */
1676         if (silgen) {
1677                 ast_channel_stop_silence_generator(chan, silgen);
1678         }
1679
1680         /* We need to free all the deferred frames, but we only need to
1681          * queue the deferred frames if there was no error and no
1682          * hangup was received
1683          */
1684         ast_channel_lock(chan);
1685         while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1686                 if (!res) {
1687                         ast_queue_frame_head(chan, f);
1688                 }
1689                 ast_frfree(f);
1690         }
1691         ast_channel_unlock(chan);
1692
1693         return res;
1694 }
1695
1696 /*! \brief Wait, look for hangups */
1697 int ast_safe_sleep(struct ast_channel *chan, int ms)
1698 {
1699         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1700 }
1701
1702 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1703 {
1704         /* Safe, even if already unlinked. */
1705         ao2_unlink(channels, chan);
1706         return ast_channel_unref(chan);
1707 }
1708
1709 void ast_party_name_init(struct ast_party_name *init)
1710 {
1711         init->str = NULL;
1712         init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1713         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1714         init->valid = 0;
1715 }
1716
1717 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1718 {
1719         if (dest == src) {
1720                 /* Don't copy to self */
1721                 return;
1722         }
1723
1724         ast_free(dest->str);
1725         dest->str = ast_strdup(src->str);
1726         dest->char_set = src->char_set;
1727         dest->presentation = src->presentation;
1728         dest->valid = src->valid;
1729 }
1730
1731 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1732 {
1733         init->str = NULL;
1734         init->char_set = guide->char_set;
1735         init->presentation = guide->presentation;
1736         init->valid = guide->valid;
1737 }
1738
1739 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1740 {
1741         if (dest == src) {
1742                 /* Don't set to self */
1743                 return;
1744         }
1745
1746         if (src->str && src->str != dest->str) {
1747                 ast_free(dest->str);
1748                 dest->str = ast_strdup(src->str);
1749         }
1750
1751         dest->char_set = src->char_set;
1752         dest->presentation = src->presentation;
1753         dest->valid = src->valid;
1754 }
1755
1756 void ast_party_name_free(struct ast_party_name *doomed)
1757 {
1758         ast_free(doomed->str);
1759         doomed->str = NULL;
1760 }
1761
1762 void ast_party_number_init(struct ast_party_number *init)
1763 {
1764         init->str = NULL;
1765         init->plan = 0;/* Unknown */
1766         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1767         init->valid = 0;
1768 }
1769
1770 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1771 {
1772         if (dest == src) {
1773                 /* Don't copy to self */
1774                 return;
1775         }
1776
1777         ast_free(dest->str);
1778         dest->str = ast_strdup(src->str);
1779         dest->plan = src->plan;
1780         dest->presentation = src->presentation;
1781         dest->valid = src->valid;
1782 }
1783
1784 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1785 {
1786         init->str = NULL;
1787         init->plan = guide->plan;
1788         init->presentation = guide->presentation;
1789         init->valid = guide->valid;
1790 }
1791
1792 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1793 {
1794         if (dest == src) {
1795                 /* Don't set to self */
1796                 return;
1797         }
1798
1799         if (src->str && src->str != dest->str) {
1800                 ast_free(dest->str);
1801                 dest->str = ast_strdup(src->str);
1802         }
1803
1804         dest->plan = src->plan;
1805         dest->presentation = src->presentation;
1806         dest->valid = src->valid;
1807 }
1808
1809 void ast_party_number_free(struct ast_party_number *doomed)
1810 {
1811         ast_free(doomed->str);
1812         doomed->str = NULL;
1813 }
1814
1815 void ast_party_subaddress_init(struct ast_party_subaddress *init)
1816 {
1817         init->str = NULL;
1818         init->type = 0;
1819         init->odd_even_indicator = 0;
1820         init->valid = 0;
1821 }
1822
1823 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1824 {
1825         if (dest == src) {
1826                 /* Don't copy to self */
1827                 return;
1828         }
1829
1830         ast_free(dest->str);
1831         dest->str = ast_strdup(src->str);
1832         dest->type = src->type;
1833         dest->odd_even_indicator = src->odd_even_indicator;
1834         dest->valid = src->valid;
1835 }
1836
1837 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
1838 {
1839         init->str = NULL;
1840         init->type = guide->type;
1841         init->odd_even_indicator = guide->odd_even_indicator;
1842         init->valid = guide->valid;
1843 }
1844
1845 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
1846 {
1847         if (dest == src) {
1848                 /* Don't set to self */
1849                 return;
1850         }
1851
1852         if (src->str && src->str != dest->str) {
1853                 ast_free(dest->str);
1854                 dest->str = ast_strdup(src->str);
1855         }
1856
1857         dest->type = src->type;
1858         dest->odd_even_indicator = src->odd_even_indicator;
1859         dest->valid = src->valid;
1860 }
1861
1862 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
1863 {
1864         ast_free(doomed->str);
1865         doomed->str = NULL;
1866 }
1867
1868 void ast_party_id_init(struct ast_party_id *init)
1869 {
1870         ast_party_name_init(&init->name);
1871         ast_party_number_init(&init->number);
1872         ast_party_subaddress_init(&init->subaddress);
1873         init->tag = NULL;
1874 }
1875
1876 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
1877 {
1878         if (dest == src) {
1879                 /* Don't copy to self */
1880                 return;
1881         }
1882
1883         ast_party_name_copy(&dest->name, &src->name);
1884         ast_party_number_copy(&dest->number, &src->number);
1885         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
1886
1887         ast_free(dest->tag);
1888         dest->tag = ast_strdup(src->tag);
1889 }
1890
1891 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
1892 {
1893         ast_party_name_set_init(&init->name, &guide->name);
1894         ast_party_number_set_init(&init->number, &guide->number);
1895         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
1896         init->tag = NULL;
1897 }
1898
1899 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
1900 {
1901         if (dest == src) {
1902                 /* Don't set to self */
1903                 return;
1904         }
1905
1906         if (!update || update->name) {
1907                 ast_party_name_set(&dest->name, &src->name);
1908         }
1909         if (!update || update->number) {
1910                 ast_party_number_set(&dest->number, &src->number);
1911         }
1912         if (!update || update->subaddress) {
1913                 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
1914         }
1915
1916         if (src->tag && src->tag != dest->tag) {
1917                 ast_free(dest->tag);
1918                 dest->tag = ast_strdup(src->tag);
1919         }
1920 }
1921
1922 void ast_party_id_free(struct ast_party_id *doomed)
1923 {
1924         ast_party_name_free(&doomed->name);
1925         ast_party_number_free(&doomed->number);
1926         ast_party_subaddress_free(&doomed->subaddress);
1927
1928         ast_free(doomed->tag);
1929         doomed->tag = NULL;
1930 }
1931
1932 int ast_party_id_presentation(const struct ast_party_id *id)
1933 {
1934         int number_priority;
1935         int number_value;
1936         int number_screening;
1937         int name_priority;
1938         int name_value;
1939
1940         /* Determine name presentation priority. */
1941         if (!id->name.valid) {
1942                 name_value = AST_PRES_UNAVAILABLE;
1943                 name_priority = 3;
1944         } else {
1945                 name_value = id->name.presentation & AST_PRES_RESTRICTION;
1946                 switch (name_value) {
1947                 case AST_PRES_RESTRICTED:
1948                         name_priority = 0;
1949                         break;
1950                 case AST_PRES_ALLOWED:
1951                         name_priority = 1;
1952                         break;
1953                 case AST_PRES_UNAVAILABLE:
1954                         name_priority = 2;
1955                         break;
1956                 default:
1957                         name_value = AST_PRES_UNAVAILABLE;
1958                         name_priority = 3;
1959                         break;
1960                 }
1961         }
1962
1963         /* Determine number presentation priority. */
1964         if (!id->number.valid) {
1965                 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1966                 number_value = AST_PRES_UNAVAILABLE;
1967                 number_priority = 3;
1968         } else {
1969                 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
1970                 number_value = id->number.presentation & AST_PRES_RESTRICTION;
1971                 switch (number_value) {
1972                 case AST_PRES_RESTRICTED:
1973                         number_priority = 0;
1974                         break;
1975                 case AST_PRES_ALLOWED:
1976                         number_priority = 1;
1977                         break;
1978                 case AST_PRES_UNAVAILABLE:
1979                         number_priority = 2;
1980                         break;
1981                 default:
1982                         number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
1983                         number_value = AST_PRES_UNAVAILABLE;
1984                         number_priority = 3;
1985                         break;
1986                 }
1987         }
1988
1989         /* Select the wining presentation value. */
1990         if (name_priority < number_priority) {
1991                 number_value = name_value;
1992         }
1993
1994         return number_value | number_screening;
1995 }
1996
1997 void ast_party_dialed_init(struct ast_party_dialed *init)
1998 {
1999         init->number.str = NULL;
2000         init->number.plan = 0;/* Unknown */
2001         ast_party_subaddress_init(&init->subaddress);
2002         init->transit_network_select = 0;
2003 }
2004
2005 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2006 {
2007         if (dest == src) {
2008                 /* Don't copy to self */
2009                 return;
2010         }
2011
2012         ast_free(dest->number.str);
2013         dest->number.str = ast_strdup(src->number.str);
2014         dest->number.plan = src->number.plan;
2015         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2016         dest->transit_network_select = src->transit_network_select;
2017 }
2018
2019 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2020 {
2021         init->number.str = NULL;
2022         init->number.plan = guide->number.plan;
2023         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2024         init->transit_network_select = guide->transit_network_select;
2025 }
2026
2027 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2028 {
2029         if (src->number.str && src->number.str != dest->number.str) {
2030                 ast_free(dest->number.str);
2031                 dest->number.str = ast_strdup(src->number.str);
2032         }
2033         dest->number.plan = src->number.plan;
2034
2035         ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2036
2037         dest->transit_network_select = src->transit_network_select;
2038 }
2039
2040 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2041 {
2042         ast_free(doomed->number.str);
2043         doomed->number.str = NULL;
2044         ast_party_subaddress_free(&doomed->subaddress);
2045 }
2046
2047 void ast_party_caller_init(struct ast_party_caller *init)
2048 {
2049         ast_party_id_init(&init->id);
2050         ast_party_id_init(&init->ani);
2051         init->ani2 = 0;
2052 }
2053
2054 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2055 {
2056         if (dest == src) {
2057                 /* Don't copy to self */
2058                 return;
2059         }
2060
2061         ast_party_id_copy(&dest->id, &src->id);
2062         ast_party_id_copy(&dest->ani, &src->ani);
2063         dest->ani2 = src->ani2;
2064 }
2065
2066 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2067 {
2068         ast_party_id_set_init(&init->id, &guide->id);
2069         ast_party_id_set_init(&init->ani, &guide->ani);
2070         init->ani2 = guide->ani2;
2071 }
2072
2073 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2074 {
2075         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2076         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2077         dest->ani2 = src->ani2;
2078 }
2079
2080 void ast_party_caller_free(struct ast_party_caller *doomed)
2081 {
2082         ast_party_id_free(&doomed->id);
2083         ast_party_id_free(&doomed->ani);
2084 }
2085
2086 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2087 {
2088         ast_party_id_init(&init->id);
2089         ast_party_id_init(&init->ani);
2090         init->ani2 = 0;
2091         init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2092 }
2093
2094 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2095 {
2096         if (dest == src) {
2097                 /* Don't copy to self */
2098                 return;
2099         }
2100
2101         ast_party_id_copy(&dest->id, &src->id);
2102         ast_party_id_copy(&dest->ani, &src->ani);
2103         dest->ani2 = src->ani2;
2104         dest->source = src->source;
2105 }
2106
2107 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2108 {
2109         ast_party_id_set_init(&init->id, &guide->id);
2110         ast_party_id_set_init(&init->ani, &guide->ani);
2111         init->ani2 = guide->ani2;
2112         init->source = guide->source;
2113 }
2114
2115 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)
2116 {
2117         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2118         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2119         dest->ani2 = src->ani2;
2120         dest->source = src->source;
2121 }
2122
2123 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2124 {
2125         connected->id = caller->id;
2126         connected->ani = caller->ani;
2127         connected->ani2 = caller->ani2;
2128         connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2129 }
2130
2131 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2132 {
2133         ast_party_id_free(&doomed->id);
2134         ast_party_id_free(&doomed->ani);
2135 }
2136
2137 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2138 {
2139         ast_party_id_init(&init->from);
2140         ast_party_id_init(&init->to);
2141         init->count = 0;
2142         init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2143 }
2144
2145 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2146 {
2147         if (dest == src) {
2148                 /* Don't copy to self */
2149                 return;
2150         }
2151
2152         ast_party_id_copy(&dest->from, &src->from);
2153         ast_party_id_copy(&dest->to, &src->to);
2154         dest->count = src->count;
2155         dest->reason = src->reason;
2156 }
2157
2158 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2159 {
2160         ast_party_id_set_init(&init->from, &guide->from);
2161         ast_party_id_set_init(&init->to, &guide->to);
2162         init->count = guide->count;
2163         init->reason = guide->reason;
2164 }
2165
2166 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2167 {
2168         ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2169         ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2170         dest->reason = src->reason;
2171         dest->count = src->count;
2172 }
2173
2174 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2175 {
2176         ast_party_id_free(&doomed->from);
2177         ast_party_id_free(&doomed->to);
2178 }
2179
2180 /*! \brief Free a channel structure */
2181 static void ast_channel_destructor(void *obj)
2182 {
2183         struct ast_channel *chan = obj;
2184         int fd;
2185 #ifdef HAVE_EPOLL
2186         int i;
2187 #endif
2188         struct ast_var_t *vardata;
2189         struct ast_frame *f;
2190         struct varshead *headp;
2191         struct ast_datastore *datastore;
2192         char device_name[AST_CHANNEL_NAME];
2193
2194         if (ast_channel_name(chan)) {
2195                 /* The string fields were initialized. */
2196                 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2197                 ast_cel_check_retire_linkedid(chan);
2198         }
2199
2200         /* Get rid of each of the data stores on the channel */
2201         ast_channel_lock(chan);
2202         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
2203                 /* Free the data store */
2204                 ast_datastore_free(datastore);
2205         ast_channel_unlock(chan);
2206
2207         /* Lock and unlock the channel just to be sure nobody has it locked still
2208            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2209         ast_channel_lock(chan);
2210         ast_channel_unlock(chan);
2211
2212         if (chan->tech_pvt) {
2213                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
2214                 ast_free(chan->tech_pvt);
2215         }
2216
2217         if (chan->sched) {
2218                 ast_sched_context_destroy(chan->sched);
2219         }
2220
2221         if (ast_channel_name(chan)) {
2222                 char *dashptr;
2223
2224                 /* The string fields were initialized. */
2225                 ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
2226                 if ((dashptr = strrchr(device_name, '-'))) {
2227                         *dashptr = '\0';
2228                 }
2229         } else {
2230                 device_name[0] = '\0';
2231         }
2232
2233         /* Stop monitoring */
2234         if (chan->monitor)
2235                 chan->monitor->stop( chan, 0 );
2236
2237         /* If there is native format music-on-hold state, free it */
2238         if (chan->music_state)
2239                 ast_moh_cleanup(chan);
2240
2241         /* Free translators */
2242         if (chan->readtrans)
2243                 ast_translator_free_path(chan->readtrans);
2244         if (chan->writetrans)
2245                 ast_translator_free_path(chan->writetrans);
2246         if (chan->pbx)
2247                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
2248
2249         ast_party_dialed_free(&chan->dialed);
2250         ast_party_caller_free(&chan->caller);
2251         ast_party_connected_line_free(&chan->connected);
2252         ast_party_redirecting_free(&chan->redirecting);
2253
2254         /* Close pipes if appropriate */
2255         if ((fd = chan->alertpipe[0]) > -1)
2256                 close(fd);
2257         if ((fd = chan->alertpipe[1]) > -1)
2258                 close(fd);
2259         if (chan->timer) {
2260                 ast_timer_close(chan->timer);
2261         }
2262 #ifdef HAVE_EPOLL
2263         for (i = 0; i < AST_MAX_FDS; i++) {
2264                 if (chan->epfd_data[i])
2265                         free(chan->epfd_data[i]);
2266         }
2267         close(chan->epfd);
2268 #endif
2269         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
2270                 ast_frfree(f);
2271         
2272         /* loop over the variables list, freeing all data and deleting list items */
2273         /* no need to lock the list, as the channel is already locked */
2274         headp = &chan->varshead;
2275         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2276                 ast_var_delete(vardata);
2277
2278         ast_app_group_discard(chan);
2279
2280         /* Destroy the jitterbuffer */
2281         ast_jb_destroy(chan);
2282
2283         if (chan->cdr) {
2284                 ast_cdr_discard(chan->cdr);
2285                 chan->cdr = NULL;
2286         }
2287
2288         if (chan->zone) {
2289                 chan->zone = ast_tone_zone_unref(chan->zone);
2290         }
2291
2292         ast_string_field_free_memory(chan);
2293
2294         if (device_name[0]) {
2295                 /*
2296                  * We have a device name to notify of a new state.
2297                  *
2298                  * Queue an unknown state, because, while we know that this particular
2299                  * instance is dead, we don't know the state of all other possible
2300                  * instances.
2301                  */
2302                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2303         }
2304
2305         chan->nativeformats = ast_format_cap_destroy(chan->nativeformats);
2306 }
2307
2308 /*! \brief Free a dummy channel structure */
2309 static void ast_dummy_channel_destructor(void *obj)
2310 {
2311         struct ast_channel *chan = obj;
2312         struct ast_var_t *vardata;
2313         struct varshead *headp;
2314
2315         headp = &chan->varshead;
2316
2317         ast_party_dialed_free(&chan->dialed);
2318         ast_party_caller_free(&chan->caller);
2319         ast_party_connected_line_free(&chan->connected);
2320         ast_party_redirecting_free(&chan->redirecting);
2321
2322         /* loop over the variables list, freeing all data and deleting list items */
2323         /* no need to lock the list, as the channel is already locked */
2324         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2325                 ast_var_delete(vardata);
2326
2327         if (chan->cdr) {
2328                 ast_cdr_discard(chan->cdr);
2329                 chan->cdr = NULL;
2330         }
2331
2332         ast_string_field_free_memory(chan);
2333 }
2334
2335 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2336 {
2337         return ast_datastore_alloc(info, uid);
2338 }
2339
2340 int ast_channel_datastore_free(struct ast_datastore *datastore)
2341 {
2342         return ast_datastore_free(datastore);
2343 }
2344
2345 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2346 {
2347         struct ast_datastore *datastore = NULL, *datastore2;
2348
2349         AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
2350                 if (datastore->inheritance > 0) {
2351                         datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2352                         if (datastore2) {
2353                                 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2354                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2355                                 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
2356                         }
2357                 }
2358         }
2359         return 0;
2360 }
2361
2362 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2363 {
2364         int res = 0;
2365
2366         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
2367
2368         return res;
2369 }
2370
2371 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2372 {
2373         return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
2374 }
2375
2376 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2377 {
2378         struct ast_datastore *datastore = NULL;
2379         
2380         if (info == NULL)
2381                 return NULL;
2382
2383         AST_LIST_TRAVERSE(&chan->datastores, datastore, entry) {
2384                 if (datastore->info != info) {
2385                         continue;
2386                 }
2387
2388                 if (uid == NULL) {
2389                         /* matched by type only */
2390                         break;
2391                 }
2392
2393                 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2394                         /* Matched by type AND uid */
2395                         break;
2396                 }
2397         }
2398
2399         return datastore;
2400 }
2401
2402 /*! Set the file descriptor on the channel */
2403 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2404 {
2405 #ifdef HAVE_EPOLL
2406         struct epoll_event ev;
2407         struct ast_epoll_data *aed = NULL;
2408
2409         if (chan->fds[which] > -1) {
2410                 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2411                 aed = chan->epfd_data[which];
2412         }
2413
2414         /* If this new fd is valid, add it to the epoll */
2415         if (fd > -1) {
2416                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2417                         return;
2418                 
2419                 chan->epfd_data[which] = aed;
2420                 aed->chan = chan;
2421                 aed->which = which;
2422                 
2423                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2424                 ev.data.ptr = aed;
2425                 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2426         } else if (aed) {
2427                 /* We don't have to keep around this epoll data structure now */
2428                 free(aed);
2429                 chan->epfd_data[which] = NULL;
2430         }
2431 #endif
2432         chan->fds[which] = fd;
2433         return;
2434 }
2435
2436 /*! Add a channel to an optimized waitfor */
2437 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2438 {
2439 #ifdef HAVE_EPOLL
2440         struct epoll_event ev;
2441         int i = 0;
2442
2443         if (chan0->epfd == -1)
2444                 return;
2445
2446         /* Iterate through the file descriptors on chan1, adding them to chan0 */
2447         for (i = 0; i < AST_MAX_FDS; i++) {
2448                 if (chan1->fds[i] == -1)
2449                         continue;
2450                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2451                 ev.data.ptr = chan1->epfd_data[i];
2452                 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2453         }
2454
2455 #endif
2456         return;
2457 }
2458
2459 /*! Delete a channel from an optimized waitfor */
2460 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2461 {
2462 #ifdef HAVE_EPOLL
2463         struct epoll_event ev;
2464         int i = 0;
2465
2466         if (chan0->epfd == -1)
2467                 return;
2468
2469         for (i = 0; i < AST_MAX_FDS; i++) {
2470                 if (chan1->fds[i] == -1)
2471                         continue;
2472                 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2473         }
2474
2475 #endif
2476         return;
2477 }
2478
2479 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2480 {
2481         ast_channel_lock(chan);
2482
2483         chan->_softhangup &= ~flag;
2484
2485         if (!chan->_softhangup) {
2486                 struct ast_frame *fr;
2487
2488                 /* If we have completely cleared the softhangup flag,
2489                  * then we need to fully abort the hangup process.  This requires
2490                  * pulling the END_OF_Q frame out of the channel frame queue if it
2491                  * still happens to be there. */
2492
2493                 fr = AST_LIST_LAST(&chan->readq);
2494                 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2495                                 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2496                         AST_LIST_REMOVE(&chan->readq, fr, frame_list);
2497                         ast_frfree(fr);
2498                 }
2499         }
2500
2501         ast_channel_unlock(chan);
2502 }
2503
2504 /*! \brief Softly hangup a channel, don't lock */
2505 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2506 {
2507         ast_debug(1, "Soft-Hanging up channel '%s'\n", ast_channel_name(chan));
2508         /* Inform channel driver that we need to be hung up, if it cares */
2509         chan->_softhangup |= cause;
2510         ast_queue_frame(chan, &ast_null_frame);
2511         /* Interrupt any poll call or such */
2512         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2513                 pthread_kill(chan->blocker, SIGURG);
2514         return 0;
2515 }
2516
2517 /*! \brief Softly hangup a channel, lock */
2518 int ast_softhangup(struct ast_channel *chan, int cause)
2519 {
2520         int res;
2521
2522         ast_channel_lock(chan);
2523         res = ast_softhangup_nolock(chan, cause);
2524         manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2525                 "Channel: %s\r\n"
2526                 "Uniqueid: %s\r\n"
2527                 "Cause: %d\r\n",
2528                 ast_channel_name(chan),
2529                 ast_channel_uniqueid(chan),
2530                 cause);
2531         ast_channel_unlock(chan);
2532
2533         return res;
2534 }
2535
2536 static void free_translation(struct ast_channel *clonechan)
2537 {
2538         if (clonechan->writetrans)
2539                 ast_translator_free_path(clonechan->writetrans);
2540         if (clonechan->readtrans)
2541                 ast_translator_free_path(clonechan->readtrans);
2542         clonechan->writetrans = NULL;
2543         clonechan->readtrans = NULL;
2544         if (ast_format_cap_is_empty(clonechan->nativeformats)) {
2545                 ast_format_clear(&clonechan->rawwriteformat);
2546                 ast_format_clear(&clonechan->rawreadformat);
2547         } else {
2548                 struct ast_format tmpfmt;
2549                 ast_best_codec(clonechan->nativeformats, &tmpfmt);
2550                 ast_format_copy(&clonechan->rawwriteformat, &tmpfmt);
2551                 ast_format_copy(&clonechan->rawreadformat, &tmpfmt);
2552         }
2553 }
2554
2555 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2556 {
2557         struct ast_channel *bridge;
2558
2559         ast_channel_lock(chan);
2560         if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
2561                 ast_channel_hangupsource_set(chan, source);
2562         }
2563         bridge = ast_bridged_channel(chan);
2564         ast_channel_unlock(chan);
2565
2566         if (bridge && (force || ast_strlen_zero(ast_channel_hangupsource(bridge)))) {
2567                 ast_channel_lock(bridge);
2568                 ast_channel_hangupsource_set(chan, source);
2569                 ast_channel_unlock(bridge);
2570         }
2571 }
2572
2573 static void destroy_hooks(struct ast_channel *chan)
2574 {
2575         if (chan->audiohooks) {
2576                 ast_audiohook_detach_list(chan->audiohooks);
2577                 chan->audiohooks = NULL;
2578         }
2579
2580         ast_framehook_list_destroy(chan);
2581 }
2582
2583 /*! \brief Hangup a channel */
2584 int ast_hangup(struct ast_channel *chan)
2585 {
2586         char extra_str[64]; /* used for cel logging below */
2587         int was_zombie;
2588
2589         ast_autoservice_stop(chan);
2590
2591         ast_channel_lock(chan);
2592
2593         /*
2594          * Do the masquerade if someone is setup to masquerade into us.
2595          *
2596          * NOTE: We must hold the channel lock after testing for a
2597          * pending masquerade and setting the channel as a zombie to
2598          * prevent __ast_channel_masquerade() from setting up a
2599          * masquerade with a dead channel.
2600          */
2601         while (chan->masq) {
2602                 ast_channel_unlock(chan);
2603                 if (ast_do_masquerade(chan)) {
2604                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2605
2606                         /* Abort the loop or we might never leave. */
2607                         ast_channel_lock(chan);
2608                         break;
2609                 }
2610                 ast_channel_lock(chan);
2611         }
2612
2613         if (chan->masqr) {
2614                 /*
2615                  * This channel is one which will be masqueraded into something.
2616                  * Mark it as a zombie already so ast_do_masquerade() will know
2617                  * to free it later.
2618                  */
2619                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2620                 destroy_hooks(chan);
2621                 ast_channel_unlock(chan);
2622                 return 0;
2623         }
2624
2625         if (!(was_zombie = ast_test_flag(chan, AST_FLAG_ZOMBIE))) {
2626                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2627         }
2628
2629         ast_channel_unlock(chan);
2630         ao2_unlink(channels, chan);
2631         ast_channel_lock(chan);
2632
2633         destroy_hooks(chan);
2634
2635         free_translation(chan);
2636         /* Close audio stream */
2637         if (chan->stream) {
2638                 ast_closestream(chan->stream);
2639                 chan->stream = NULL;
2640         }
2641         /* Close video stream */
2642         if (chan->vstream) {
2643                 ast_closestream(chan->vstream);
2644                 chan->vstream = NULL;
2645         }
2646         if (chan->sched) {
2647                 ast_sched_context_destroy(chan->sched);
2648                 chan->sched = NULL;
2649         }
2650
2651         if (chan->generatordata) {      /* Clear any tone stuff remaining */
2652                 if (chan->generator && chan->generator->release) {
2653                         chan->generator->release(chan, chan->generatordata);
2654                 }
2655         }
2656         chan->generatordata = NULL;
2657         chan->generator = NULL;
2658
2659         snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, ast_channel_hangupsource(chan), S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2660         ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2661
2662         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2663                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2664                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
2665                         (long) pthread_self(), ast_channel_name(chan), (long)chan->blocker, chan->blockproc);
2666                 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2667         }
2668         if (!was_zombie) {
2669                 ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
2670
2671                 if (chan->tech->hangup) {
2672                         chan->tech->hangup(chan);
2673                 }
2674         } else {
2675                 ast_debug(1, "Hanging up zombie '%s'\n", ast_channel_name(chan));
2676         }
2677
2678         ast_channel_unlock(chan);
2679
2680         ast_cc_offer(chan);
2681         ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2682                 "Channel: %s\r\n"
2683                 "Uniqueid: %s\r\n"
2684                 "CallerIDNum: %s\r\n"
2685                 "CallerIDName: %s\r\n"
2686                 "ConnectedLineNum: %s\r\n"
2687                 "ConnectedLineName: %s\r\n"
2688                 "Cause: %d\r\n"
2689                 "Cause-txt: %s\r\n",
2690                 ast_channel_name(chan),
2691                 ast_channel_uniqueid(chan),
2692                 S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<unknown>"),
2693                 S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, "<unknown>"),
2694                 S_COR(chan->connected.id.number.valid, chan->connected.id.number.str, "<unknown>"),
2695                 S_COR(chan->connected.id.name.valid, chan->connected.id.name.str, "<unknown>"),
2696                 chan->hangupcause,
2697                 ast_cause2str(chan->hangupcause)
2698                 );
2699
2700         if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
2701                 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
2702                 (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2703                 ast_channel_lock(chan);
2704                 ast_cdr_end(chan->cdr);
2705                 ast_cdr_detach(chan->cdr);
2706                 chan->cdr = NULL;
2707                 ast_channel_unlock(chan);
2708         }
2709
2710         ast_channel_unref(chan);
2711
2712         return 0;
2713 }
2714
2715 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2716 {
2717         int res = 0;
2718
2719         ast_channel_lock(chan);
2720
2721         /* You can't answer an outbound call */
2722         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2723                 ast_channel_unlock(chan);
2724                 return 0;
2725         }
2726
2727         /* Stop if we're a zombie or need a soft hangup */
2728         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2729                 ast_channel_unlock(chan);
2730                 return -1;
2731         }
2732
2733         ast_channel_unlock(chan);
2734
2735         switch (chan->_state) {
2736         case AST_STATE_RINGING:
2737         case AST_STATE_RING:
2738                 ast_channel_lock(chan);
2739                 if (chan->tech->answer) {
2740                         res = chan->tech->answer(chan);
2741                 }
2742                 ast_setstate(chan, AST_STATE_UP);
2743                 if (cdr_answer) {
2744                         ast_cdr_answer(chan->cdr);
2745                 }
2746                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2747                 ast_channel_unlock(chan);
2748                 break;
2749         case AST_STATE_UP:
2750                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2751                 /* Calling ast_cdr_answer when it it has previously been called
2752                  * is essentially a no-op, so it is safe.
2753                  */
2754                 if (cdr_answer) {
2755                         ast_cdr_answer(chan->cdr);
2756                 }
2757                 break;
2758         default:
2759                 break;
2760         }
2761
2762         ast_indicate(chan, -1);
2763
2764         return res;
2765 }
2766
2767 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2768 {
2769         int res = 0;
2770         enum ast_channel_state old_state;
2771
2772         old_state = chan->_state;
2773         if ((res = ast_raw_answer(chan, cdr_answer))) {
2774                 return res;
2775         }
2776
2777         switch (old_state) {
2778         case AST_STATE_RINGING:
2779         case AST_STATE_RING:
2780                 /* wait for media to start flowing, but don't wait any longer
2781                  * than 'delay' or 500 milliseconds, whichever is longer
2782                  */
2783                 do {
2784                         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2785                         struct ast_frame *cur, *new;
2786                         int ms = MAX(delay, 500);
2787                         unsigned int done = 0;
2788
2789                         AST_LIST_HEAD_INIT_NOLOCK(&frames);
2790
2791                         for (;;) {
2792                                 ms = ast_waitfor(chan, ms);
2793                                 if (ms < 0) {
2794                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
2795                                         res = -1;
2796                                         break;
2797                                 }
2798                                 if (ms == 0) {
2799                                         ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", ast_channel_name(chan), MAX(delay, 500));
2800                                         break;
2801                                 }
2802                                 cur = ast_read(chan);
2803                                 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2804                                              (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2805                                         if (cur) {
2806                                                 ast_frfree(cur);
2807                                         }
2808                                         res = -1;
2809                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
2810                                         break;
2811                                 }
2812
2813                                 if ((new = ast_frisolate(cur)) != cur) {
2814                                         ast_frfree(cur);
2815                                 }
2816
2817                                 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2818
2819                                 /* if a specific delay period was requested, continue
2820                                  * until that delay has passed. don't stop just because
2821                                  * incoming media has arrived.
2822                                  */
2823                                 if (delay) {
2824                                         continue;
2825                                 }
2826
2827                                 switch (new->frametype) {
2828                                         /* all of these frametypes qualify as 'media' */
2829                                 case AST_FRAME_VOICE:
2830                                 case AST_FRAME_VIDEO:
2831                                 case AST_FRAME_TEXT:
2832                                 case AST_FRAME_DTMF_BEGIN:
2833                                 case AST_FRAME_DTMF_END:
2834                                 case AST_FRAME_IMAGE:
2835                                 case AST_FRAME_HTML:
2836                                 case AST_FRAME_MODEM:
2837                                         done = 1;
2838                                         break;
2839                                 case AST_FRAME_CONTROL:
2840                                 case AST_FRAME_IAX:
2841                                 case AST_FRAME_NULL:
2842                                 case AST_FRAME_CNG:
2843                                         break;
2844                                 }
2845
2846                                 if (done) {
2847                                         break;
2848                                 }
2849                         }
2850
2851                         if (res == 0) {
2852                                 ast_channel_lock(chan);
2853                                 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
2854                                         ast_queue_frame_head(chan, cur);
2855                                         ast_frfree(cur);
2856                                 }
2857                                 ast_channel_unlock(chan);
2858                         }
2859                 } while (0);
2860                 break;
2861         default:
2862                 break;
2863         }
2864
2865         return res;
2866 }
2867
2868 int ast_answer(struct ast_channel *chan)
2869 {
2870         return __ast_answer(chan, 0, 1);
2871 }
2872
2873 void ast_deactivate_generator(struct ast_channel *chan)
2874 {
2875         ast_channel_lock(chan);
2876         if (chan->generatordata) {
2877                 if (chan->generator && chan->generator->release)
2878                         chan->generator->release(chan, chan->generatordata);
2879                 chan->generatordata = NULL;
2880                 chan->generator = NULL;
2881                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
2882                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
2883                 ast_settimeout(chan, 0, NULL, NULL);
2884         }
2885         ast_channel_unlock(chan);
2886 }
2887
2888 static void generator_write_format_change(struct ast_channel *chan)
2889 {
2890         ast_channel_lock(chan);
2891         if (chan->generator && chan->generator->write_format_change) {
2892                 chan->generator->write_format_change(chan, chan->generatordata);
2893         }
2894         ast_channel_unlock(chan);
2895 }
2896
2897 static int generator_force(const void *data)
2898 {
2899         /* Called if generator doesn't have data */
2900         void *tmp;
2901         int res;
2902         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2903         struct ast_channel *chan = (struct ast_channel *)data;
2904
2905         ast_channel_lock(chan);
2906         tmp = chan->generatordata;
2907         chan->generatordata = NULL;
2908         if (chan->generator)
2909                 generate = chan->generator->generate;
2910         ast_channel_unlock(chan);
2911
2912         if (!tmp || !generate)
2913                 return 0;
2914
2915         res = generate(chan, tmp, 0, ast_format_rate(&chan->writeformat) / 50);
2916
2917         chan->generatordata = tmp;
2918
2919         if (res) {
2920                 ast_debug(1, "Auto-deactivating generator\n");
2921                 ast_deactivate_generator(chan);
2922         }
2923
2924         return 0;
2925 }
2926
2927 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
2928 {
2929         int res = 0;
2930
2931         ast_channel_lock(chan);
2932         if (chan->generatordata) {
2933                 if (chan->generator && chan->generator->release)
2934                         chan->generator->release(chan, chan->generatordata);
2935                 chan->generatordata = NULL;
2936         }
2937         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
2938                 res = -1;
2939         }
2940         if (!res) {
2941                 ast_settimeout(chan, 50, generator_force, chan);
2942                 chan->generator = gen;
2943         }
2944         ast_channel_unlock(chan);
2945
2946         ast_prod(chan);
2947
2948         return res;
2949 }
2950
2951 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
2952 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
2953 {
2954         int winner = -1;
2955         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
2956         return winner;
2957 }
2958
2959 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
2960 #ifdef HAVE_EPOLL
2961 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
2962                                         int *exception, int *outfd, int *ms)
2963 #else
2964 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2965                                         int *exception, int *outfd, int *ms)
2966 #endif
2967 {
2968         struct timeval start = { 0 , 0 };
2969         struct pollfd *pfds = NULL;
2970         int res;
2971         long rms;
2972         int x, y, max;
2973         int sz;
2974         struct timeval now = { 0, 0 };
2975         struct timeval whentohangup = { 0, 0 }, diff;
2976         struct ast_channel *winner = NULL;
2977         struct fdmap {
2978                 int chan;
2979                 int fdno;
2980         } *fdmap = NULL;
2981
2982         if ((sz = n * AST_MAX_FDS + nfds)) {
2983                 pfds = alloca(sizeof(*pfds) * sz);
2984                 fdmap = alloca(sizeof(*fdmap) * sz);
2985         }
2986
2987         if (outfd)
2988                 *outfd = -99999;
2989         if (exception)
2990                 *exception = 0;
2991         
2992         /* Perform any pending masquerades */
2993         for (x = 0; x < n; x++) {
2994                 if (c[x]->masq && ast_do_masquerade(c[x])) {
2995                         ast_log(LOG_WARNING, "Masquerade failed\n");
2996                         *ms = -1;
2997                         return NULL;
2998                 }
2999
3000                 ast_channel_lock(c[x]);
3001                 if (!ast_tvzero(c[x]->whentohangup)) {
3002                         if (ast_tvzero(whentohangup))
3003                                 now = ast_tvnow();
3004                         diff = ast_tvsub(c[x]->whentohangup, now);
3005                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3006                                 /* Should already be hungup */
3007                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3008                                 ast_channel_unlock(c[x]);
3009                                 return c[x];
3010                         }
3011                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3012                                 whentohangup = diff;
3013                 }
3014                 ast_channel_unlock(c[x]);
3015         }
3016         /* Wait full interval */
3017         rms = *ms;
3018         /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3019         if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3020                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
3021                 if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
3022                         rms =  *ms;
3023                 }
3024         } else if (!ast_tvzero(whentohangup) && rms < 0) {
3025                 /* Tiny corner case... call would need to last >24 days */
3026                 rms = INT_MAX;
3027         }
3028         /*
3029          * Build the pollfd array, putting the channels' fds first,
3030          * followed by individual fds. Order is important because
3031          * individual fd's must have priority over channel fds.
3032          */
3033         max = 0;
3034         for (x = 0; x < n; x++) {
3035                 for (y = 0; y < AST_MAX_FDS; y++) {
3036                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
3037                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
3038                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
3039                 }
3040                 CHECK_BLOCKING(c[x]);
3041         }
3042         /* Add the individual fds */
3043         for (x = 0; x < nfds; x++) {
3044                 fdmap[max].chan = -1;
3045                 max += ast_add_fd(&pfds[max], fds[x]);
3046         }
3047
3048         if (*ms > 0)
3049                 start = ast_tvnow();
3050         
3051         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3052                 do {
3053                         int kbrms = rms;
3054                         if (kbrms > 600000)
3055                                 kbrms = 600000;
3056                         res = ast_poll(pfds, max, kbrms);
3057                         if (!res)
3058                                 rms -= kbrms;
3059                 } while (!res && (rms > 0));
3060         } else {
3061                 res = ast_poll(pfds, max, rms);
3062         }
3063         for (x = 0; x < n; x++)
3064                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
3065         if (res < 0) { /* Simulate a timeout if we were interrupted */
3066                 if (errno != EINTR)
3067                         *ms = -1;
3068                 return NULL;
3069         }
3070         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
3071                 now = ast_tvnow();
3072                 for (x = 0; x < n; x++) {
3073                         if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
3074                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3075                                 if (winner == NULL)
3076                                         winner = c[x];
3077                         }
3078                 }
3079         }
3080         if (res == 0) { /* no fd ready, reset timeout and done */
3081                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
3082                 return winner;
3083         }
3084         /*
3085          * Then check if any channel or fd has a pending event.
3086          * Remember to check channels first and fds last, as they
3087          * must have priority on setting 'winner'
3088          */
3089         for (x = 0; x < max; x++) {
3090                 res = pfds[x].revents;
3091                 if (res == 0)
3092                         continue;
3093                 if (fdmap[x].chan >= 0) {       /* this is a channel */
3094                         winner = c[fdmap[x].chan];      /* override previous winners */
3095                         if (res & POLLPRI)
3096                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
3097                         else
3098                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3099                         winner->fdno = fdmap[x].fdno;
3100                 } else {                        /* this is an fd */
3101                         if (outfd)
3102                                 *outfd = pfds[x].fd;
3103                         if (exception)
3104                                 *exception = (res & POLLPRI) ? -1 : 0;
3105                         winner = NULL;
3106                 }
3107         }
3108         if (*ms > 0) {
3109                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3110                 if (*ms < 0)
3111                         *ms = 0;
3112         }
3113         return winner;
3114 }
3115
3116 #ifdef HAVE_EPOLL
3117 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3118 {
3119         struct timeval start = { 0 , 0 };
3120         int res = 0;
3121         struct epoll_event ev[1];
3122         long diff, rms = *ms;
3123         struct ast_channel *winner = NULL;
3124         struct ast_epoll_data *aed = NULL;
3125
3126
3127         /* See if this channel needs to be masqueraded */
3128         if (chan->masq && ast_do_masquerade(chan)) {
3129                 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", ast_channel_name(chan));
3130                 *ms = -1;
3131                 return NULL;
3132         }
3133
3134         ast_channel_lock(chan);
3135         /* Figure out their timeout */
3136         if (!ast_tvzero(chan->whentohangup)) {
3137                 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
3138                         /* They should already be hungup! */
3139                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3140                         ast_channel_unlock(chan);
3141                         return NULL;
3142                 }
3143                 /* If this value is smaller then the current one... make it priority */
3144                 if (rms > diff)
3145                         rms = diff;
3146         }
3147
3148         ast_channel_unlock(chan);
3149
3150         /* Time to make this channel block... */
3151         CHECK_BLOCKING(chan);
3152
3153         if (*ms > 0)
3154                 start = ast_tvnow();
3155
3156         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
3157         res = epoll_wait(chan->epfd, ev, 1, rms);
3158
3159         /* Stop blocking */
3160         ast_clear_flag(chan, AST_FLAG_BLOCKING);
3161
3162         /* Simulate a timeout if we were interrupted */
3163         if (res < 0) {
3164                 if (errno != EINTR)
3165                         *ms = -1;
3166                 return NULL;
3167         }
3168
3169         /* If this channel has a timeout see if it expired */
3170         if (!ast_tvzero(chan->whentohangup)) {
3171                 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
3172                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3173                         winner = chan;
3174                 }
3175         }
3176
3177         /* No fd ready, reset timeout and be done for now */
3178         if (!res) {
3179                 *ms = 0;
3180                 return winner;
3181         }
3182
3183         /* See what events are pending */
3184         aed = ev[0].data.ptr;
3185         chan->fdno = aed->which;
3186         if (ev[0].events & EPOLLPRI)
3187                 ast_set_flag(chan, AST_FLAG_EXCEPTION);
3188         else
3189                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3190
3191         if (*ms > 0) {
3192                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3193                 if (*ms < 0)
3194                         *ms = 0;
3195         }
3196
3197         return chan;
3198 }
3199
3200 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
3201 {
3202         struct timeval start = { 0 , 0 };
3203         int res = 0, i;
3204         struct epoll_event ev[25] = { { 0, } };
3205         struct timeval now = { 0, 0 };
3206         long whentohangup = 0, diff = 0, rms = *ms;
3207         struct ast_channel *winner = NULL;
3208
3209         for (i = 0; i < n; i++) {
3210                 if (c[i]->masq && ast_do_masquerade(c[i])) {
3211                         ast_log(LOG_WARNING, "Masquerade failed\n");
3212                         *ms = -1;
3213                         return NULL;
3214                 }
3215
3216                 ast_channel_lock(c[i]);
3217                 if (!ast_tvzero(c[i]->whentohangup)) {
3218                         if (whentohangup == 0)
3219                                 now = ast_tvnow();
3220                         if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
3221                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3222                                 ast_channel_unlock(c[i]);
3223                                 return c[i];
3224                         }
3225                         if (!whentohangup || whentohangup > diff)
3226                                 whentohangup = diff;
3227                 }
3228                 ast_channel_unlock(c[i]);
3229                 CHECK_BLOCKING(c[i]);
3230         }
3231
3232         rms = *ms;
3233         if (whentohangup) {
3234                 rms = whentohangup;
3235                 if (*ms >= 0 && *ms < rms)
3236                         rms = *ms;
3237         }
3238
3239         if (*ms > 0)
3240                 start = ast_tvnow();
3241
3242         res = epoll_wait(c[0]->epfd, ev, 25, rms);
3243
3244         for (i = 0; i < n; i++)
3245                 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
3246
3247         if (res < 0) {
3248                 if (errno != EINTR)
3249                         *ms = -1;
3250                 return NULL;
3251         }
3252
3253         if (whentohangup) {
3254                 now = ast_tvnow();
3255                 for (i = 0; i < n; i++) {
3256                         if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
3257                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3258                                 if (!winner)
3259                                         winner = c[i];
3260                         }
3261                 }
3262         }
3263
3264         if (!res) {
3265                 *ms = 0;
3266                 return winner;
3267         }
3268
3269         for (i = 0; i < res; i++) {
3270                 struct ast_epoll_data *aed = ev[i].data.ptr;
3271
3272                 if (!ev[i].events || !aed)
3273                         continue;
3274
3275                 winner = aed->chan;
3276                 if (ev[i].events & EPOLLPRI)
3277                         ast_set_flag(winner, AST_FLAG_EXCEPTION);
3278                 else
3279                         ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3280                 winner->fdno = aed->which;
3281         }
3282
3283         if (*ms > 0) {
3284                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3285                 if (*ms < 0)
3286                         *ms = 0;
3287         }
3288
3289         return winner;
3290 }
3291
3292 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3293                                         int *exception, int *outfd, int *ms)
3294 {
3295         /* Clear all provided values in one place. */
3296         if (outfd)
3297                 *outfd = -99999;
3298         if (exception)
3299                 *exception = 0;
3300
3301         /* If no epoll file descriptor is available resort to classic nandfds */
3302         if (!n || nfds || c[0]->epfd == -1)
3303                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
3304         else if (!nfds && n == 1)
3305                 return ast_waitfor_nandfds_simple(c[0], ms);
3306         else
3307                 return ast_waitfor_nandfds_complex(c, n, ms);
3308 }
3309 #endif
3310
3311 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
3312 {
3313         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
3314 }
3315
3316 int ast_waitfor(struct ast_channel *c, int ms)
3317 {
3318         int oldms = ms; /* -1 if no timeout */
3319
3320         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
3321         if ((ms < 0) && (oldms < 0))
3322                 ms = 0;
3323         return ms;
3324 }
3325
3326 /* XXX never to be called with ms = -1 */
3327 int ast_waitfordigit(struct ast_channel *c, int ms)
3328 {
3329         return ast_waitfordigit_full(c, ms, -1, -1);
3330 }
3331
3332 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
3333 {
3334         int res;
3335         unsigned int real_rate = rate, max_rate;
3336
3337         ast_channel_lock(c);
3338
3339         if (c->timingfd == -1) {
3340                 ast_channel_unlock(c);
3341                 return -1;
3342         }
3343
3344         if (!func) {
3345                 rate = 0;
3346                 data = NULL;
3347         }
3348
3349         if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
3350                 real_rate = max_rate;
3351         }
3352
3353         ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
3354
3355         res = ast_timer_set_rate(c->timer, real_rate);
3356
3357         c->timingfunc = func;
3358         c->timingdata = data;
3359
3360         ast_channel_unlock(c);
3361
3362         return res;
3363 }
3364
3365 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
3366 {
3367         /* Stop if we're a zombie or need a soft hangup */
3368         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3369                 return -1;
3370
3371         /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
3372         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
3373
3374         /* Wait for a digit, no more than ms milliseconds total. */
3375         
3376         while (ms) {
3377                 struct ast_channel *rchan;
3378                 int outfd=-1;
3379
3380                 errno = 0;
3381                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
3382                 
3383                 if (!rchan && outfd < 0 && ms) {
3384                         if (errno == 0 || errno == EINTR)
3385                                 continue;
3386                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
3387                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3388                         return -1;
3389                 } else if (outfd > -1) {
3390                         /* The FD we were watching has something waiting */
3391                         ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
3392                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3393                         return 1;
3394                 } else if (rchan) {
3395                         int res;
3396                         struct ast_frame *f = ast_read(c);
3397                         if (!f)
3398                                 return -1;
3399
3400                         switch (f->frametype) {
3401                         case AST_FRAME_DTMF_BEGIN:
3402                                 break;
3403                         case AST_FRAME_DTMF_END:
3404                                 res = f->subclass.integer;
3405                                 ast_frfree(f);
3406                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3407                                 return res;
3408                         case AST_FRAME_CONTROL:
3409                                 switch (f->subclass.integer) {
3410                                 case AST_CONTROL_HANGUP:
3411                                         ast_frfree(f);
3412                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3413                                         return -1;
3414                                 case AST_CONTROL_RINGING:
3415                                 case AST_CONTROL_ANSWER:
3416                                 case AST_CONTROL_SRCUPDATE:
3417                                 case AST_CONTROL_SRCCHANGE:
3418                                 case AST_CONTROL_CONNECTED_LINE:
3419                                 case AST_CONTROL_REDIRECTING:
3420                                 case AST_CONTROL_UPDATE_RTP_PEER:
3421                                 case -1:
3422                                         /* Unimportant */
3423                                         break;
3424                                 default:
3425                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
3426                                         break;
3427                                 }
3428                                 break;
3429                         case AST_FRAME_VOICE:
3430                                 /* Write audio if appropriate */
3431                                 if (audiofd > -1) {
3432                                         if (write(audiofd, f->data.ptr, f->datalen) < 0) {
3433                                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3434                                         }
3435                                 }
3436                         default:
3437                                 /* Ignore */
3438                                 break;
3439                         }
3440                         ast_frfree(f);
3441                 }
3442         }
3443
3444         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
3445
3446         return 0; /* Time is up */
3447 }
3448
3449 static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
3450 {
3451         ast_manager_event(chan, EVENT_FLAG_DTMF,
3452                         "DTMF",
3453                         "Channel: %s\r\n"
3454                         "Uniqueid: %s\r\n"
3455                         "Digit: %c\r\n"
3456                         "Direction: %s\r\n"
3457                         "Begin: %s\r\n"
3458                         "End: %s\r\n",
3459                         ast_channel_name(chan), ast_channel_uniqueid(chan), digit, direction, begin, end);
3460 }
3461
3462 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
3463 {
3464         if (chan->generator && chan->generator->generate && chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
3465                 void *tmp = chan->generatordata;
3466                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = chan->generator->generate;
3467                 int res;
3468                 int samples;
3469
3470                 if (chan->timingfunc) {
3471                         ast_debug(1, "Generator got voice, switching to phase locked mode\n");
3472                         ast_settimeout(chan, 0, NULL, NULL);
3473                 }
3474
3475                 chan->generatordata = NULL;     /* reset, to let writes go through */
3476
3477                 if (ast_format_cmp(&f->subclass.format, &chan->writeformat) == AST_FORMAT_CMP_NOT_EQUAL) {
3478                         float factor;
3479                         factor = ((float) ast_format_rate(&chan->writeformat)) / ((float) ast_format_rate(&f->subclass.format));
3480                         samples = (int) ( ((float) f->samples) * factor );
3481                 } else {
3482                         samples = f->samples;
3483                 }
3484
3485                 /* This unlock is here based on two assumptions that hold true at this point in the
3486                  * code. 1) this function is only called from within __ast_read() and 2) all generators
3487                  * call ast_write() in their generate callback.
3488                  *
3489                  * The reason this is added is so that when ast_write is called, the lock that occurs 
3490                  * there will not recursively lock the channel. Doing this will cause intended deadlock 
3491                  * avoidance not to work in deeper functions
3492                  */
3493                 ast_channel_unlock(chan);
3494                 res = generate(chan, tmp, f->datalen, samples);
3495                 ast_channel_lock(chan);
3496                 chan->generatordata = tmp;
3497                 if (res) {
3498                         ast_debug(1, "Auto-deactivating generator\n");
3499                         ast_deactivate_generator(chan);
3500                 }
3501
3502         } else if (f->frametype == AST_FRAME_CNG) {
3503                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
3504                         ast_debug(1, "Generator got CNG, switching to timed mode\n");
3505                         ast_settimeout(chan, 50, generator_force, chan);
3506                 }
3507         }
3508 }
3509
3510 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
3511 {
3512         struct ast_frame *fr = &chan->dtmff;
3513
3514         fr->frametype = AST_FRAME_DTMF_END;
3515         fr->subclass.integer = f->subclass.integer;
3516         fr->len = f->len;
3517
3518         /* The only time this function will be called is for a frame that just came
3519          * out of the channel driver.  So, we want to stick it on the tail of the
3520          * readq. */
3521
3522         ast_queue_frame(chan, fr);
3523 }
3524
3525 /*!
3526  * \brief Determine whether or not we should ignore DTMF in the readq
3527  */
3528 static inline int should_skip_dtmf(struct ast_channel *chan)
3529 {
3530         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
3531                 /* We're in the middle of emulating a digit, or DTMF has been
3532                  * explicitly deferred.  Skip this digit, then. */
3533                 return 1;
3534         }
3535                         
3536         if (!ast_tvzero(chan->dtmf_tv) && 
3537                         ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
3538                 /* We're not in the middle of a digit, but it hasn't been long enough
3539                  * since the last digit, so we'll have to skip DTMF for now. */
3540                 return 1;
3541         }
3542
3543         return 0;
3544 }
3545
3546 /*!
3547  * \brief calculates the number of samples to jump forward with in a monitor stream.
3548  
3549  * \note When using ast_seekstream() with the read and write streams of a monitor,
3550  * the number of samples to seek forward must be of the same sample rate as the stream
3551  * or else the jump will not be calculated correctly.
3552  *
3553  * \retval number of samples to seek forward after rate conversion.
3554  */
3555 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
3556 {
3557         int diff = sample_rate - seek_rate;
3558
3559         if (diff > 0) {
3560                 samples = samples / (float) (sample_rate / seek_rate);
3561         } else if (diff < 0) {
3562                 samples = samples * (float) (seek_rate / sample_rate);
3563         }
3564
3565         return samples;
3566 }
3567
3568 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
3569 {
3570         struct ast_frame *f = NULL;     /* the return value */
3571         int blah;
3572         int prestate;
3573         int cause = 0;
3574
3575         /* this function is very long so make sure there is only one return
3576          * point at the end (there are only two exceptions to this).
3577          */
3578
3579         if (chan->masq) {
3580                 if (ast_do_masquerade(chan))
3581                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
3582                 else
3583                         f =  &ast_null_frame;
3584                 return f;
3585         }
3586
3587         /* if here, no masq has happened, lock the channel and proceed */
3588         ast_channel_lock(chan);
3589
3590         /* Stop if we're a zombie or need a soft hangup */
3591         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
3592                 if (chan->generator)
3593                         ast_deactivate_generator(chan);
3594
3595                 /*
3596                  * It is possible for chan->_softhangup to be set and there
3597                  * still be control frames that need to be read.  Instead of
3598                  * just going to 'done' in the case of ast_check_hangup(), we
3599                  * need to queue the end-of-Q frame so that it can mark the end
3600                  * of the read queue.  If there are frames to be read,
3601                  * ast_queue_control() will be called repeatedly, but will only
3602                  * queue the first end-of-Q frame.
3603                  */
3604                 if (chan->_softhangup) {
3605                         ast_queue_control(chan, AST_CONTROL_END_OF_Q);
3606                 } else {
3607                         goto done;
3608                 }
3609         } else {
3610 #ifdef AST_DEVMODE
3611                 /*
3612                  * The ast_waitfor() code records which of the channel's file
3613                  * descriptors reported that data is available.  In theory,
3614                  * ast_read() should only be called after ast_waitfor() reports
3615                  * that a channel has data available for reading.  However,
3616                  * there still may be some edge cases throughout the code where
3617                  * ast_read() is called improperly.  This can potentially cause
3618                  * problems, so if this is a developer build, make a lot of
3619                  * noise if this happens so that it can be addressed.
3620                  *
3621                  * One of the potential problems is blocking on a dead channel.
3622                  */
3623                 if (chan->fdno == -1) {
3624                         ast_log(LOG_ERROR,
3625                                 "ast_read() on chan '%s' called with no recorded file descriptor.\n",
3626                                 ast_channel_name(chan));
3627                 }
3628 #endif
3629         }
3630
3631         prestate = chan->_state;
3632
3633         /* Read and ignore anything on the alertpipe, but read only
3634            one sizeof(blah) per frame that we send from it */
3635         if (chan->alertpipe[0] > -1) {
3636                 int flags = fcntl(chan->alertpipe[0], F_GETFL);
3637                 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
3638                  * which immediately causes a deadlock scenario.  Detect and prevent this. */
3639                 if ((flags & O_NONBLOCK) == 0) {
3640                         ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", ast_channel_name(chan));
3641                         if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
3642                                 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
3643                                 f = &ast_null_frame;
3644                                 goto done;
3645                         }
3646                 }
3647                 if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
3648                         if (errno != EINTR && errno != EAGAIN)
3649                                 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
3650                 }
3651         }
3652
3653         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
3654                 enum ast_timer_event res;
3655
3656                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3657
3658                 res = ast_timer_get_event(chan->timer);
3659
3660                 switch (res) {
3661                 case AST_TIMING_EVENT_EXPIRED:
3662                         ast_timer_ack(chan->timer, 1);
3663
3664                         if (chan->timingfunc) {
3665                                 /* save a copy of func/data before unlocking the channel */
3666                                 int (*func)(const void *) = chan->timingfunc;
3667                                 void *data = chan->timingdata;
3668                                 chan->fdno = -1;
3669                                 ast_channel_unlock(chan);
3670                                 func(data);
3671                         } else {
3672                                 ast_timer_set_rate(chan->timer, 0);
3673                                 chan->fdno = -1;
3674                                 ast_channel_unlock(chan);
3675                         }
3676
3677                         /* cannot 'goto done' because the channel is already unlocked */
3678                         return &ast_null_frame;
3679
3680                 case AST_TIMING_EVENT_CONTINUOUS:
3681                         if (AST_LIST_EMPTY(&chan->readq) || 
3682                                 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
3683                                 ast_timer_disable_continuous(chan->timer);
3684                         }
3685                         break;
3686                 }
3687
3688         } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
3689                 /* if the AST_GENERATOR_FD is set, call the generator with args
3690                  * set to -1 so it can do whatever it needs to.
3691                  */
3692                 void *tmp = chan->generatordata;
3693                 chan->generatordata = NULL;     /* reset to let ast_write get through */
3694                 chan->generator->generate(chan, tmp, -1, -1);
3695                 chan->generatordata = tmp;
3696                 f = &ast_null_frame;
3697                 chan->fdno = -1;
3698                 goto done;
3699         } else if (chan->fds[AST_JITTERBUFFER_FD] > -1 && chan->fdno == AST_JITTERBUFFER_FD) {
3700                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3701         }
3702
3703         /* Check for pending read queue */
3704         if (!AST_LIST_EMPTY(&chan->readq)) {
3705                 int skip_dtmf = should_skip_dtmf(chan);
3706
3707                 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
3708                         /* We have to be picky about which frame we pull off of the readq because
3709                          * there are cases where we want to leave DTMF frames on the queue until
3710                          * some later time. */
3711
3712                         if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
3713                                 continue;
3714                         }
3715
3716                         AST_LIST_REMOVE_CURRENT(frame_list);
3717                         break;
3718                 }
3719                 AST_LIST_TRAVERSE_SAFE_END;
3720                 
3721                 if (!f) {
3722                         /* There were no acceptable frames on the readq. */
3723                         f = &ast_null_frame;
3724                         if (chan->alertpipe[0] > -1) {
3725                                 int poke = 0;
3726                                 /* Restore the state of the alertpipe since we aren't ready for any
3727                                  * of the frames in the readq. */
3728                                 if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
3729                                         ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
3730                                 }
3731                         }
3732                 }
3733
3734                 /* Interpret hangup and end-of-Q frames to return NULL */
3735                 /* XXX why not the same for frames from the channel ? */
3736                 if (f->frametype == AST_FRAME_CONTROL) {
3737                         switch (f->subclass.integer) {
3738                         case AST_CONTROL_HANGUP:
3739                                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
3740                                 cause = f->data.uint32;
3741                                 /* Fall through */
3742                         case AST_CONTROL_END_OF_Q:
3743                                 ast_frfree(f);
3744                                 f = NULL;
3745                                 break;
3746                         default:
3747                                 break;
3748                         }
3749                 }
3750         } else {
3751                 chan->blocker = pthread_self();
3752                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
3753                         if (chan->tech->exception)
3754                                 f = chan->tech->exception(chan);
3755                         else {
3756                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", ast_channel_name(chan));
3757                                 f = &ast_null_frame;
3758                         }
3759                         /* Clear the exception flag */
3760                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
3761                 } else if (chan->tech && chan->tech->read)
3762                         f = chan->tech->read(chan);
3763                 else
3764                         ast_log(LOG_WARNING, "No read routine on channel %s\n", ast_channel_name(chan));
3765         }
3766
3767         /* Perform the framehook read event here. After the frame enters the framehook list
3768          * there is no telling what will happen, <insert mad scientist laugh here>!!! */
3769         f = ast_framehook_list_read_event(chan->framehooks, f);
3770
3771         /*
3772          * Reset the recorded file descriptor that triggered this read so that we can
3773          * easily detect when ast_read() is called without properly using ast_waitfor().
3774          */
3775         chan->fdno = -1;
3776
3777         if (f) {
3778                 struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
3779                 struct ast_control_read_action_payload *read_action_payload;
3780                 struct ast_party_connected_line connected;
3781
3782                 /* if the channel driver returned more than one frame, stuff the excess
3783                    into the readq for the next ast_read call
3784                 */
3785                 if (AST_LIST_NEXT(f, frame_list)) {
3786                         ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
3787                         ast_frfree(AST_LIST_NEXT(f, frame_list));
3788                         AST_LIST_NEXT(f, frame_list) = NULL;
3789                 }
3790
3791                 switch (f->frametype) {
3792                 case AST_FRAME_CONTROL:
3793                         if (f->subclass.integer == AST_CONTROL_ANSWER) {
3794                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
3795                                         ast_debug(1, "Ignoring answer on an inbound call!\n");
3796                                         ast_frfree(f);
3797                                         f = &ast_null_frame;
3798                                 } else if (prestate == AST_STATE_UP && ast_bridged_channel(chan)) {
3799                                         ast_debug(1, "Dropping duplicate answer!\n");
3800                                         ast_frfree(f);
3801                                         f = &ast_null_frame;
3802                                 } else {
3803                                         /* Answer the CDR */
3804                                         ast_setstate(chan, AST_STATE_UP);
3805                                         /* removed a call to ast_cdr_answer(chan->cdr) from here. */
3806                                         ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
3807                                 }
3808                         } else if (f->subclass.integer == AST_CONTROL_READ_ACTION) {
3809                                 read_action_payload = f->data.ptr;
3810                                 switch (read_action_payload->action) {
3811                                 case AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO:
3812                                         ast_party_connected_line_init(&connected);
3813                                         ast_party_connected_line_copy(&connected, &chan->connected);
3814                                         if (ast_connected_line_parse_data(read_action_payload->payload,
3