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