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