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