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