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