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