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