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