Merged revisions 59486 via svnmerge from
[asterisk/asterisk.git] / main / channel.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Channel Management
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <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         /* Experiment: under what conditions do we NOT want to track cdrs on channels? */
736         tmp->cdr = ast_cdr_alloc();
737         ast_cdr_init(tmp->cdr, tmp);
738         ast_cdr_start(tmp->cdr);
739         
740         headp = &tmp->varshead;
741         AST_LIST_HEAD_INIT_NOLOCK(headp);
742         
743         ast_mutex_init(&tmp->lock);
744         
745         AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
746         
747         strcpy(tmp->context, "default");
748         strcpy(tmp->exten, "s");
749         tmp->priority = 1;
750         
751         ast_string_field_set(tmp, language, defaultlanguage);
752         tmp->amaflags = ast_default_amaflags;
753         ast_string_field_set(tmp, accountcode, ast_default_accountcode);
754
755         tmp->tech = &null_tech;
756
757         AST_LIST_LOCK(&channels);
758         AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
759         AST_LIST_UNLOCK(&channels);
760
761         return tmp;
762 }
763
764 /*! \brief Queue an outgoing media frame */
765 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
766 {
767         struct ast_frame *f;
768         struct ast_frame *cur;
769         int blah = 1;
770         int qlen = 0;
771
772         /* Build us a copy and free the original one */
773         if (!(f = ast_frdup(fin))) {
774                 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
775                 return -1;
776         }
777         ast_channel_lock(chan);
778
779         /* See if the last frame on the queue is a hangup, if so don't queue anything */
780         if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
781                 ast_frfree(f);
782                 ast_channel_unlock(chan);
783                 return 0;
784         }
785
786         /* Count how many frames exist on the queue */
787         AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
788                 qlen++;
789         }
790
791         /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
792         if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen  > 128)) {
793                 if (fin->frametype != AST_FRAME_VOICE) {
794                         ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
795                         CRASH;
796                 } else {
797                         if (option_debug)
798                                 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
799                         ast_frfree(f);
800                         ast_channel_unlock(chan);
801                         return 0;
802                 }
803         }
804         AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
805         if (chan->alertpipe[1] > -1) {
806                 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
807                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
808                                 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
809 #ifdef HAVE_ZAPTEL
810         } else if (chan->timingfd > -1) {
811                 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
812 #endif                          
813         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
814                 pthread_kill(chan->blocker, SIGURG);
815         }
816         ast_channel_unlock(chan);
817         return 0;
818 }
819
820 /*! \brief Queue a hangup frame for channel */
821 int ast_queue_hangup(struct ast_channel *chan)
822 {
823         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
824         /* Yeah, let's not change a lock-critical value without locking */
825         if (!ast_channel_trylock(chan)) {
826                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
827                 ast_channel_unlock(chan);
828         }
829         return ast_queue_frame(chan, &f);
830 }
831
832 /*! \brief Queue a control frame */
833 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
834 {
835         struct ast_frame f = { AST_FRAME_CONTROL, };
836
837         f.subclass = control;
838
839         return ast_queue_frame(chan, &f);
840 }
841
842 /*! \brief Queue a control frame with payload */
843 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
844                            const void *data, size_t datalen)
845 {
846         struct ast_frame f = { AST_FRAME_CONTROL, };
847
848         f.subclass = control;
849         f.data = (void *) data;
850         f.datalen = datalen;
851
852         return ast_queue_frame(chan, &f);
853 }
854
855 /*! \brief Set defer DTMF flag on channel */
856 int ast_channel_defer_dtmf(struct ast_channel *chan)
857 {
858         int pre = 0;
859
860         if (chan) {
861                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
862                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
863         }
864         return pre;
865 }
866
867 /*! \brief Unset defer DTMF flag on channel */
868 void ast_channel_undefer_dtmf(struct ast_channel *chan)
869 {
870         if (chan)
871                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
872 }
873
874 /*!
875  * \brief Helper function to find channels.
876  *
877  * It supports these modes:
878  *
879  * prev != NULL : get channel next in list after prev
880  * name != NULL : get channel with matching name
881  * name != NULL && namelen != 0 : get channel whose name starts with prefix
882  * exten != NULL : get channel whose exten or macroexten matches
883  * context != NULL && exten != NULL : get channel whose context or macrocontext
884  *
885  * It returns with the channel's lock held. If getting the individual lock fails,
886  * unlock and retry quickly up to 10 times, then give up.
887  *
888  * \note XXX Note that this code has cost O(N) because of the need to verify
889  * that the object is still on the global list.
890  *
891  * \note XXX also note that accessing fields (e.g. c->name in ast_log())
892  * can only be done with the lock held or someone could delete the
893  * object while we work on it. This causes some ugliness in the code.
894  * Note that removing the first ast_log() may be harmful, as it would
895  * shorten the retry period and possibly cause failures.
896  * We should definitely go for a better scheme that is deadlock-free.
897  */
898 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
899                                                const char *name, const int namelen,
900                                                const char *context, const char *exten)
901 {
902         const char *msg = prev ? "deadlock" : "initial deadlock";
903         int retries;
904         struct ast_channel *c;
905
906         for (retries = 0; retries < 10; retries++) {
907                 int done;
908                 AST_LIST_LOCK(&channels);
909                 AST_LIST_TRAVERSE(&channels, c, chan_list) {
910                         if (prev) {     /* look for next item */
911                                 if (c != prev)  /* not this one */
912                                         continue;
913                                 /* found, prepare to return c->next */
914                                 if ((c = AST_LIST_NEXT(c, chan_list)) == NULL) break;
915                                 /* If prev was the last item on the channel list, then we just
916                                  * want to return NULL, instead of trying to deref NULL in the
917                                  * next section.
918                                  */
919                         }
920                         if (name) { /* want match by name */
921                                 if ((!namelen && strcasecmp(c->name, name)) ||
922                                     (namelen && strncasecmp(c->name, name, namelen)))
923                                         continue;       /* name match failed */
924                         } else if (exten) {
925                                 if (context && strcasecmp(c->context, context) &&
926                                     strcasecmp(c->macrocontext, context))
927                                         continue;       /* context match failed */
928                                 if (strcasecmp(c->exten, exten) &&
929                                     strcasecmp(c->macroexten, exten))
930                                         continue;       /* exten match failed */
931                         }
932                         /* if we get here, c points to the desired record */
933                         break;
934                 }
935                 /* exit if chan not found or mutex acquired successfully */
936                 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
937                 done = c == NULL || ast_channel_trylock(c) == 0;
938                 if (!done) {
939                         if (option_debug)
940                                 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
941                 }
942                 AST_LIST_UNLOCK(&channels);
943                 if (done)
944                         return c;
945                 usleep(1);      /* give other threads a chance before retrying */
946         }
947         /*
948          * c is surely not null, but we don't have the lock so cannot
949          * access c->name
950          */
951         if (option_debug)
952                 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n",
953                         c, retries);
954
955         return NULL;
956 }
957
958 /*! \brief Browse channels in use */
959 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
960 {
961         return channel_find_locked(prev, NULL, 0, NULL, NULL);
962 }
963
964 /*! \brief Get channel by name and lock it */
965 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
966 {
967         return channel_find_locked(NULL, name, 0, NULL, NULL);
968 }
969
970 /*! \brief Get channel by name prefix and lock it */
971 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
972 {
973         return channel_find_locked(NULL, name, namelen, NULL, NULL);
974 }
975
976 /*! \brief Get next channel by name prefix and lock it */
977 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
978                                                            const int namelen)
979 {
980         return channel_find_locked(chan, name, namelen, NULL, NULL);
981 }
982
983 /*! \brief Get channel by exten (and optionally context) and lock it */
984 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
985 {
986         return channel_find_locked(NULL, NULL, 0, context, exten);
987 }
988
989 /*! \brief Get next channel by exten (and optionally context) and lock it */
990 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
991                                                      const char *context)
992 {
993         return channel_find_locked(chan, NULL, 0, context, exten);
994 }
995
996 /*! \brief Wait, look for hangups and condition arg */
997 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
998 {
999         struct ast_frame *f;
1000
1001         while (ms > 0) {
1002                 if (cond && ((*cond)(data) == 0))
1003                         return 0;
1004                 ms = ast_waitfor(chan, ms);
1005                 if (ms < 0)
1006                         return -1;
1007                 if (ms > 0) {
1008                         f = ast_read(chan);
1009                         if (!f)
1010                                 return -1;
1011                         ast_frfree(f);
1012                 }
1013         }
1014         return 0;
1015 }
1016
1017 /*! \brief Wait, look for hangups */
1018 int ast_safe_sleep(struct ast_channel *chan, int ms)
1019 {
1020         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1021 }
1022
1023 static void free_cid(struct ast_callerid *cid)
1024 {
1025         if (cid->cid_dnid)
1026                 free(cid->cid_dnid);
1027         if (cid->cid_num)
1028                 free(cid->cid_num);     
1029         if (cid->cid_name)
1030                 free(cid->cid_name);    
1031         if (cid->cid_ani)
1032                 free(cid->cid_ani);
1033         if (cid->cid_rdnis)
1034                 free(cid->cid_rdnis);
1035         cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1036 }
1037
1038 /*! \brief Free a channel structure */
1039 void ast_channel_free(struct ast_channel *chan)
1040 {
1041         int fd;
1042         struct ast_var_t *vardata;
1043         struct ast_frame *f;
1044         struct varshead *headp;
1045         struct ast_datastore *datastore = NULL;
1046         char name[AST_CHANNEL_NAME];
1047         
1048         headp=&chan->varshead;
1049         
1050         AST_LIST_LOCK(&channels);
1051         AST_LIST_REMOVE(&channels, chan, chan_list);
1052         /* Lock and unlock the channel just to be sure nobody
1053            has it locked still */
1054         ast_channel_lock(chan);
1055         ast_channel_unlock(chan);
1056         if (chan->tech_pvt) {
1057                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1058                 free(chan->tech_pvt);
1059         }
1060
1061         if (chan->sched)
1062                 sched_context_destroy(chan->sched);
1063
1064         ast_copy_string(name, chan->name, sizeof(name));
1065
1066         /* Stop monitoring */
1067         if (chan->monitor)
1068                 chan->monitor->stop( chan, 0 );
1069
1070         /* If there is native format music-on-hold state, free it */
1071         if (chan->music_state)
1072                 ast_moh_cleanup(chan);
1073
1074         /* if someone is whispering on the channel, stop them */
1075         if (chan->whisper)
1076                 ast_channel_whisper_stop(chan);
1077
1078         /* Free translators */
1079         if (chan->readtrans)
1080                 ast_translator_free_path(chan->readtrans);
1081         if (chan->writetrans)
1082                 ast_translator_free_path(chan->writetrans);
1083         if (chan->pbx)
1084                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1085         free_cid(&chan->cid);
1086         ast_mutex_destroy(&chan->lock);
1087         /* Close pipes if appropriate */
1088         if ((fd = chan->alertpipe[0]) > -1)
1089                 close(fd);
1090         if ((fd = chan->alertpipe[1]) > -1)
1091                 close(fd);
1092         if ((fd = chan->timingfd) > -1)
1093                 close(fd);
1094         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1095                 ast_frfree(f);
1096         
1097         /* Get rid of each of the data stores on the channel */
1098         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1099                 /* Free the data store */
1100                 ast_channel_datastore_free(datastore);
1101         AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1102
1103         /* loop over the variables list, freeing all data and deleting list items */
1104         /* no need to lock the list, as the channel is already locked */
1105         
1106         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1107                 ast_var_delete(vardata);
1108
1109         /* Destroy the jitterbuffer */
1110         ast_jb_destroy(chan);
1111
1112         ast_string_field_free_pools(chan);
1113         free(chan);
1114         AST_LIST_UNLOCK(&channels);
1115
1116         ast_device_state_changed_literal(name);
1117 }
1118
1119 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1120 {
1121         struct ast_datastore *datastore = NULL;
1122
1123         /* Make sure we at least have type so we can identify this */
1124         if (info == NULL) {
1125                 return NULL;
1126         }
1127
1128         /* Allocate memory for datastore and clear it */
1129         datastore = ast_calloc(1, sizeof(*datastore));
1130         if (datastore == NULL) {
1131                 return NULL;
1132         }
1133
1134         datastore->info = info;
1135
1136         datastore->uid = ast_strdup(uid);
1137
1138         return datastore;
1139 }
1140
1141 int ast_channel_datastore_free(struct ast_datastore *datastore)
1142 {
1143         int res = 0;
1144
1145         /* Using the destroy function (if present) destroy the data */
1146         if (datastore->info->destroy != NULL && datastore->data != NULL) {
1147                 datastore->info->destroy(datastore->data);
1148                 datastore->data = NULL;
1149         }
1150
1151         /* Free allocated UID memory */
1152         if (datastore->uid != NULL) {
1153                 ast_free(datastore->uid);
1154                 datastore->uid = NULL;
1155         }
1156
1157         /* Finally free memory used by ourselves */
1158         free(datastore);
1159
1160         return res;
1161 }
1162
1163 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1164 {
1165         struct ast_datastore *datastore = NULL, *datastore2;
1166
1167         AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1168                 if (datastore->inheritance > 0) {
1169                         datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1170                         if (datastore2) {
1171                                 datastore2->data = datastore->info->duplicate(datastore->data);
1172                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1173                                 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1174                         }
1175                 }
1176         }
1177         return 0;
1178 }
1179
1180 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1181 {
1182         int res = 0;
1183
1184         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1185
1186         return res;
1187 }
1188
1189 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1190 {
1191         struct ast_datastore *datastore2 = NULL;
1192         int res = -1;
1193
1194         /* Find our position and remove ourselves */
1195         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1196                 if (datastore2 == datastore) {
1197                         AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1198                         res = 0;
1199                         break;
1200                 }
1201         }
1202         AST_LIST_TRAVERSE_SAFE_END
1203
1204         return res;
1205 }
1206
1207 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1208 {
1209         struct ast_datastore *datastore = NULL;
1210         
1211         if (info == NULL)
1212                 return NULL;
1213
1214         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1215                 if (datastore->info == info) {
1216                         if (uid != NULL && datastore->uid != NULL) {
1217                                 if (!strcasecmp(uid, datastore->uid)) {
1218                                         /* Matched by type AND uid */
1219                                         break;
1220                                 }
1221                         } else {
1222                                 /* Matched by type at least */
1223                                 break;
1224                         }
1225                 }
1226         }
1227         AST_LIST_TRAVERSE_SAFE_END
1228
1229         return datastore;
1230 }
1231
1232 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1233 {
1234         /* Link the owner channel to the spy */
1235         spy->chan = chan;
1236
1237         if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1238                 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1239                         spy->type, chan->name);
1240                 return -1;
1241         }
1242
1243         if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1244                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1245                         ast_getformatname(spy->read_queue.format));
1246                 return -1;
1247         }
1248
1249         if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1250                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1251                         ast_getformatname(spy->write_queue.format));
1252                 return -1;
1253         }
1254
1255         if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1256             ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1257              (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1258                 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1259                         ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1260                 return -1;
1261         }
1262
1263         if (!chan->spies) {
1264                 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1265                         return -1;
1266                 }
1267
1268                 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1269                 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1270         } else {
1271                 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1272         }
1273
1274         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1275                 ast_cond_init(&spy->trigger, NULL);
1276                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1277                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1278         }
1279
1280         if (option_debug)
1281                 ast_log(LOG_DEBUG, "Spy %s added to channel %s\n",
1282                         spy->type, chan->name);
1283
1284         return 0;
1285 }
1286
1287 /* Clean up a channel's spy information */
1288 static void spy_cleanup(struct ast_channel *chan)
1289 {
1290         if (!AST_LIST_EMPTY(&chan->spies->list))
1291                 return;
1292         if (chan->spies->read_translator.path)
1293                 ast_translator_free_path(chan->spies->read_translator.path);
1294         if (chan->spies->write_translator.path)
1295                 ast_translator_free_path(chan->spies->write_translator.path);
1296         free(chan->spies);
1297         chan->spies = NULL;
1298         return;
1299 }
1300
1301 /* Detach a spy from it's channel */
1302 static void spy_detach(struct ast_channel_spy *spy, struct ast_channel *chan)
1303 {
1304         ast_mutex_lock(&spy->lock);
1305
1306         /* We only need to poke them if they aren't already done */
1307         if (spy->status != CHANSPY_DONE) {
1308                 /* Indicate to the spy to stop */
1309                 spy->status = CHANSPY_STOP;
1310                 spy->chan = NULL;
1311                 /* Poke the spy if needed */
1312                 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1313                         ast_cond_signal(&spy->trigger);
1314         }
1315
1316         /* Print it out while we still have a lock so the structure can't go away (if signalled above) */
1317         if (option_debug)
1318                 ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n", spy->type, chan->name);
1319
1320         ast_mutex_unlock(&spy->lock);
1321
1322         return;
1323 }
1324
1325 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1326 {
1327         struct ast_channel_spy *spy = NULL;
1328         
1329         if (!chan->spies)
1330                 return;
1331
1332         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1333                 ast_mutex_lock(&spy->lock);
1334                 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1335                         ast_mutex_unlock(&spy->lock);
1336                         AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1337                         spy_detach(spy, chan);
1338                 } else
1339                         ast_mutex_unlock(&spy->lock);
1340         }
1341         AST_LIST_TRAVERSE_SAFE_END
1342         spy_cleanup(chan);
1343 }
1344
1345 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1346 {
1347         struct timeval tv;
1348         struct timespec ts;
1349
1350         tv = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1351         ts.tv_sec = tv.tv_sec;
1352         ts.tv_nsec = tv.tv_usec * 1000;
1353
1354         ast_cond_timedwait(&spy->trigger, &spy->lock, &ts);
1355 }
1356
1357 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1358 {
1359         if (!chan->spies)
1360                 return;
1361
1362         AST_LIST_REMOVE(&chan->spies->list, spy, list);
1363         spy_detach(spy, chan);
1364         spy_cleanup(chan);
1365 }
1366
1367 void ast_channel_spy_free(struct ast_channel_spy *spy)
1368 {
1369         struct ast_frame *f = NULL;
1370
1371         if (spy->status == CHANSPY_DONE)
1372                 return;
1373
1374         /* Switch status to done in case we get called twice */
1375         spy->status = CHANSPY_DONE;
1376
1377         /* Drop any frames in the queue */
1378         while ((f = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list)))
1379                 ast_frfree(f);
1380         while ((f = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list)))
1381                 ast_frfree(f);
1382
1383         /* Destroy the condition if in use */
1384         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1385                 ast_cond_destroy(&spy->trigger);
1386
1387         /* Destroy our mutex since it is no longer in use */
1388         ast_mutex_destroy(&spy->lock);
1389
1390         return;
1391 }
1392
1393 static void detach_spies(struct ast_channel *chan)
1394 {
1395         struct ast_channel_spy *spy = NULL;
1396
1397         if (!chan->spies)
1398                 return;
1399
1400         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1401                 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1402                 spy_detach(spy, chan);
1403         }
1404         AST_LIST_TRAVERSE_SAFE_END
1405
1406         spy_cleanup(chan);
1407 }
1408
1409 /*! \brief Softly hangup a channel, don't lock */
1410 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1411 {
1412         if (option_debug)
1413                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1414         /* Inform channel driver that we need to be hung up, if it cares */
1415         chan->_softhangup |= cause;
1416         ast_queue_frame(chan, &ast_null_frame);
1417         /* Interrupt any poll call or such */
1418         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1419                 pthread_kill(chan->blocker, SIGURG);
1420         return 0;
1421 }
1422
1423 /*! \brief Softly hangup a channel, lock */
1424 int ast_softhangup(struct ast_channel *chan, int cause)
1425 {
1426         int res;
1427         ast_channel_lock(chan);
1428         res = ast_softhangup_nolock(chan, cause);
1429         ast_channel_unlock(chan);
1430         return res;
1431 }
1432
1433 enum spy_direction {
1434         SPY_READ,
1435         SPY_WRITE,
1436 };
1437
1438 #define SPY_QUEUE_SAMPLE_LIMIT 4000                     /* half of one second */
1439
1440 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1441 {
1442         struct ast_frame *translated_frame = NULL;
1443         struct ast_channel_spy *spy;
1444         struct channel_spy_trans *trans;
1445
1446         trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1447
1448         AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1449                 struct ast_channel_spy_queue *queue;
1450                 struct ast_frame *duped_fr;
1451
1452                 ast_mutex_lock(&spy->lock);
1453
1454                 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1455
1456                 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1457                         if (!translated_frame) {
1458                                 if (trans->path && (trans->last_format != f->subclass)) {
1459                                         ast_translator_free_path(trans->path);
1460                                         trans->path = NULL;
1461                                 }
1462                                 if (!trans->path) {
1463                                         if (option_debug)
1464                                                 ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1465                                                         ast_getformatname(f->subclass), chan->name);
1466                                         if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1467                                                 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1468                                                         ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1469                                                 ast_mutex_unlock(&spy->lock);
1470                                                 continue;
1471                                         } else {
1472                                                 trans->last_format = f->subclass;
1473                                         }
1474                                 }
1475                                 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1476                                         ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1477                                                 ast_getformatname(AST_FORMAT_SLINEAR));
1478                                         ast_mutex_unlock(&spy->lock);
1479                                         break;
1480                                 }
1481                         }
1482                         duped_fr = ast_frdup(translated_frame);
1483                 } else if (f->subclass != queue->format) {
1484                         ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1485                                 spy->type, chan->name,
1486                                 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1487                         ast_mutex_unlock(&spy->lock);
1488                         continue;
1489                 } else
1490                         duped_fr = ast_frdup(f);
1491
1492                 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1493
1494                 queue->samples += f->samples;
1495
1496                 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1497                         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1498                                 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1499                                 case CHANSPY_TRIGGER_READ:
1500                                         if (dir == SPY_WRITE) {
1501                                                 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1502                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1503                                                 if (option_debug)
1504                                                         ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1505                                                                 spy->type, chan->name);
1506                                         }
1507                                         break;
1508                                 case CHANSPY_TRIGGER_WRITE:
1509                                         if (dir == SPY_READ) {
1510                                                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1511                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1512                                                 if (option_debug)
1513                                                         ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1514                                                                 spy->type, chan->name);
1515                                         }
1516                                         break;
1517                                 }
1518                                 if (option_debug)
1519                                         ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1520                                                 spy->type, chan->name);
1521                                 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1522                                 ast_cond_signal(&spy->trigger);
1523                         } else {
1524                                 if (option_debug)
1525                                         ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1526                                                 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1527                                 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1528                                         struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1529                                         queue->samples -= drop->samples;
1530                                         ast_frfree(drop);
1531                                 }
1532                         }
1533                 } else {
1534                         switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1535                         case CHANSPY_TRIGGER_READ:
1536                                 if (dir == SPY_READ)
1537                                         ast_cond_signal(&spy->trigger);
1538                                 break;
1539                         case CHANSPY_TRIGGER_WRITE:
1540                                 if (dir == SPY_WRITE)
1541                                         ast_cond_signal(&spy->trigger);
1542                                 break;
1543                         }
1544                 }
1545
1546                 ast_mutex_unlock(&spy->lock);
1547         }
1548
1549         if (translated_frame)
1550                 ast_frfree(translated_frame);
1551 }
1552
1553 static void free_translation(struct ast_channel *clone)
1554 {
1555         if (clone->writetrans)
1556                 ast_translator_free_path(clone->writetrans);
1557         if (clone->readtrans)
1558                 ast_translator_free_path(clone->readtrans);
1559         clone->writetrans = NULL;
1560         clone->readtrans = NULL;
1561         clone->rawwriteformat = clone->nativeformats;
1562         clone->rawreadformat = clone->nativeformats;
1563 }
1564
1565 /*! \brief Hangup a channel */
1566 int ast_hangup(struct ast_channel *chan)
1567 {
1568         int res = 0;
1569
1570         /* Don't actually hang up a channel that will masquerade as someone else, or
1571            if someone is going to masquerade as us */
1572         ast_channel_lock(chan);
1573
1574         detach_spies(chan);             /* get rid of spies */
1575
1576         if (chan->masq) {
1577                 if (ast_do_masquerade(chan))
1578                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1579         }
1580
1581         if (chan->masq) {
1582                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1583                 ast_channel_unlock(chan);
1584                 return 0;
1585         }
1586         /* If this channel is one which will be masqueraded into something,
1587            mark it as a zombie already, so we know to free it later */
1588         if (chan->masqr) {
1589                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1590                 ast_channel_unlock(chan);
1591                 return 0;
1592         }
1593         free_translation(chan);
1594         /* Close audio stream */
1595         if (chan->stream) {
1596                 ast_closestream(chan->stream);
1597                 chan->stream = NULL;
1598         }
1599         /* Close video stream */
1600         if (chan->vstream) {
1601                 ast_closestream(chan->vstream);
1602                 chan->vstream = NULL;
1603         }
1604         if (chan->sched) {
1605                 sched_context_destroy(chan->sched);
1606                 chan->sched = NULL;
1607         }
1608         
1609         if (chan->generatordata)        /* Clear any tone stuff remaining */
1610                 if (chan->generator && chan->generator->release)
1611                         chan->generator->release(chan, chan->generatordata);
1612         chan->generatordata = NULL;
1613         chan->generator = NULL;
1614         if (chan->cdr) {                /* End the CDR if it hasn't already */
1615                 ast_cdr_end(chan->cdr);
1616                 ast_cdr_detach(chan->cdr);      /* Post and Free the CDR */
1617                 chan->cdr = NULL;
1618         }
1619         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1620                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1621                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1622                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1623                 CRASH;
1624         }
1625         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1626                 if (option_debug)
1627                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1628                 if (chan->tech->hangup)
1629                         res = chan->tech->hangup(chan);
1630         } else {
1631                 if (option_debug)
1632                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1633         }
1634                         
1635         ast_channel_unlock(chan);
1636         manager_event(EVENT_FLAG_CALL, "Hangup",
1637                         "Channel: %s\r\n"
1638                         "Uniqueid: %s\r\n"
1639                         "Cause: %d\r\n"
1640                         "Cause-txt: %s\r\n",
1641                         chan->name,
1642                         chan->uniqueid,
1643                         chan->hangupcause,
1644                         ast_cause2str(chan->hangupcause)
1645                         );
1646         ast_channel_free(chan);
1647         return res;
1648 }
1649
1650 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1651 {
1652         int res = 0;
1653
1654         ast_channel_lock(chan);
1655
1656         /* You can't answer an outbound call */
1657         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1658                 ast_channel_unlock(chan);
1659                 return 0;
1660         }
1661
1662         /* Stop if we're a zombie or need a soft hangup */
1663         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1664                 ast_channel_unlock(chan);
1665                 return -1;
1666         }
1667
1668         switch (chan->_state) {
1669         case AST_STATE_RINGING:
1670         case AST_STATE_RING:
1671                 if (chan->tech->answer)
1672                         res = chan->tech->answer(chan);
1673                 ast_setstate(chan, AST_STATE_UP);
1674                 ast_cdr_answer(chan->cdr);
1675                 ast_channel_unlock(chan);
1676                 if (delay)
1677                         ast_safe_sleep(chan, delay);
1678                 return res;
1679                 break;
1680         case AST_STATE_UP:
1681                 ast_cdr_answer(chan->cdr);
1682                 break;
1683         default:
1684                 break;
1685         }
1686
1687         ast_channel_unlock(chan);
1688
1689         return res;
1690 }
1691
1692 int ast_answer(struct ast_channel *chan)
1693 {
1694         return __ast_answer(chan, 500);
1695 }
1696
1697 void ast_deactivate_generator(struct ast_channel *chan)
1698 {
1699         ast_channel_lock(chan);
1700         if (chan->generatordata) {
1701                 if (chan->generator && chan->generator->release)
1702                         chan->generator->release(chan, chan->generatordata);
1703                 chan->generatordata = NULL;
1704                 chan->generator = NULL;
1705                 chan->fds[AST_GENERATOR_FD] = -1;
1706                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1707                 ast_settimeout(chan, 0, NULL, NULL);
1708         }
1709         ast_channel_unlock(chan);
1710 }
1711
1712 static int generator_force(void *data)
1713 {
1714         /* Called if generator doesn't have data */
1715         void *tmp;
1716         int res;
1717         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1718         struct ast_channel *chan = data;
1719         tmp = chan->generatordata;
1720         chan->generatordata = NULL;
1721         generate = chan->generator->generate;
1722         res = generate(chan, tmp, 0, 160);
1723         chan->generatordata = tmp;
1724         if (res) {
1725                 if (option_debug)
1726                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1727                 ast_deactivate_generator(chan);
1728         }
1729         return 0;
1730 }
1731
1732 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1733 {
1734         int res = 0;
1735
1736         ast_channel_lock(chan);
1737
1738         if (chan->generatordata) {
1739                 if (chan->generator && chan->generator->release)
1740                         chan->generator->release(chan, chan->generatordata);
1741                 chan->generatordata = NULL;
1742         }
1743
1744         ast_prod(chan);
1745         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1746                 res = -1;
1747         }
1748         
1749         if (!res) {
1750                 ast_settimeout(chan, 160, generator_force, chan);
1751                 chan->generator = gen;
1752         }
1753
1754         ast_channel_unlock(chan);
1755
1756         return res;
1757 }
1758
1759 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1760 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1761 {
1762         int winner = -1;
1763         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1764         return winner;
1765 }
1766
1767 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1768 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1769         int *exception, int *outfd, int *ms)
1770 {
1771         struct timeval start = { 0 , 0 };
1772         struct pollfd *pfds;
1773         int res;
1774         long rms;
1775         int x, y, max;
1776         int sz;
1777         time_t now = 0;
1778         long whentohangup = 0, diff;
1779         struct ast_channel *winner = NULL;
1780         struct fdmap {
1781                 int chan;
1782                 int fdno;
1783         } *fdmap;
1784
1785         sz = n * AST_MAX_FDS + nfds;
1786         pfds = alloca(sizeof(*pfds) * sz);
1787         fdmap = alloca(sizeof(*fdmap) * sz);
1788
1789         if (outfd)
1790                 *outfd = -99999;
1791         if (exception)
1792                 *exception = 0;
1793         
1794         /* Perform any pending masquerades */
1795         for (x=0; x < n; x++) {
1796                 ast_channel_lock(c[x]);
1797                 if (c[x]->masq) {
1798                         if (ast_do_masquerade(c[x])) {
1799                                 ast_log(LOG_WARNING, "Masquerade failed\n");
1800                                 *ms = -1;
1801                                 ast_channel_unlock(c[x]);
1802                                 return NULL;
1803                         }
1804                 }
1805                 if (c[x]->whentohangup) {
1806                         if (!whentohangup)
1807                                 time(&now);
1808                         diff = c[x]->whentohangup - now;
1809                         if (diff < 1) {
1810                                 /* Should already be hungup */
1811                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1812                                 ast_channel_unlock(c[x]);
1813                                 return c[x];
1814                         }
1815                         if (!whentohangup || (diff < whentohangup))
1816                                 whentohangup = diff;
1817                 }
1818                 ast_channel_unlock(c[x]);
1819         }
1820         /* Wait full interval */
1821         rms = *ms;
1822         if (whentohangup) {
1823                 rms = whentohangup * 1000;              /* timeout in milliseconds */
1824                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1825                         rms =  *ms;
1826         }
1827         /*
1828          * Build the pollfd array, putting the channels' fds first,
1829          * followed by individual fds. Order is important because
1830          * individual fd's must have priority over channel fds.
1831          */
1832         max = 0;
1833         for (x=0; x<n; x++) {
1834                 for (y=0; y<AST_MAX_FDS; y++) {
1835                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1836                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1837                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1838                 }
1839                 CHECK_BLOCKING(c[x]);
1840         }
1841         /* Add the individual fds */
1842         for (x=0; x<nfds; x++) {
1843                 fdmap[max].chan = -1;
1844                 max += ast_add_fd(&pfds[max], fds[x]);
1845         }
1846
1847         if (*ms > 0)
1848                 start = ast_tvnow();
1849         
1850         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1851                 do {
1852                         int kbrms = rms;
1853                         if (kbrms > 600000)
1854                                 kbrms = 600000;
1855                         res = poll(pfds, max, kbrms);
1856                         if (!res)
1857                                 rms -= kbrms;
1858                 } while (!res && (rms > 0));
1859         } else {
1860                 res = poll(pfds, max, rms);
1861         }
1862         for (x=0; x<n; x++)
1863                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1864         if (res < 0) { /* Simulate a timeout if we were interrupted */
1865                 if (errno != EINTR)
1866                         *ms = -1;
1867                 return NULL;
1868         }
1869         if (whentohangup) {   /* if we have a timeout, check who expired */
1870                 time(&now);
1871                 for (x=0; x<n; x++) {
1872                         if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1873                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1874                                 if (winner == NULL)
1875                                         winner = c[x];
1876                         }
1877                 }
1878         }
1879         if (res == 0) { /* no fd ready, reset timeout and done */
1880                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1881                 return winner;
1882         }
1883         /*
1884          * Then check if any channel or fd has a pending event.
1885          * Remember to check channels first and fds last, as they
1886          * must have priority on setting 'winner'
1887          */
1888         for (x = 0; x < max; x++) {
1889                 res = pfds[x].revents;
1890                 if (res == 0)
1891                         continue;
1892                 if (fdmap[x].chan >= 0) {       /* this is a channel */
1893                         winner = c[fdmap[x].chan];      /* override previous winners */
1894                         if (res & POLLPRI)
1895                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1896                         else
1897                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1898                         winner->fdno = fdmap[x].fdno;
1899                 } else {                        /* this is an fd */
1900                         if (outfd)
1901                                 *outfd = pfds[x].fd;
1902                         if (exception)
1903                                 *exception = (res & POLLPRI) ? -1 : 0;
1904                         winner = NULL;
1905                 }
1906         }
1907         if (*ms > 0) {
1908                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1909                 if (*ms < 0)
1910                         *ms = 0;
1911         }
1912         return winner;
1913 }
1914
1915 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1916 {
1917         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1918 }
1919
1920 int ast_waitfor(struct ast_channel *c, int ms)
1921 {
1922         int oldms = ms; /* -1 if no timeout */
1923
1924         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1925         if ((ms < 0) && (oldms < 0))
1926                 ms = 0;
1927         return ms;
1928 }
1929
1930 /* XXX never to be called with ms = -1 */
1931 int ast_waitfordigit(struct ast_channel *c, int ms)
1932 {
1933         return ast_waitfordigit_full(c, ms, -1, -1);
1934 }
1935
1936 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1937 {
1938         int res = -1;
1939 #ifdef HAVE_ZAPTEL
1940         if (c->timingfd > -1) {
1941                 if (!func) {
1942                         samples = 0;
1943                         data = 0;
1944                 }
1945                 if (option_debug)
1946                         ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1947                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1948                 c->timingfunc = func;
1949                 c->timingdata = data;
1950         }
1951 #endif  
1952         return res;
1953 }
1954
1955 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1956 {
1957
1958         /* Stop if we're a zombie or need a soft hangup */
1959         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1960                 return -1;
1961         /* Wait for a digit, no more than ms milliseconds total. */
1962         while (ms) {
1963                 struct ast_channel *rchan;
1964                 int outfd;
1965
1966                 errno = 0;
1967                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1968                 if (!rchan && outfd < 0 && ms) {
1969                         if (errno == 0 || errno == EINTR)
1970                                 continue;
1971                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1972                         return -1;
1973                 } else if (outfd > -1) {
1974                         /* The FD we were watching has something waiting */
1975                         return 1;
1976                 } else if (rchan) {
1977                         int res;
1978                         struct ast_frame *f = ast_read(c);
1979                         if (!f)
1980                                 return -1;
1981
1982                         switch (f->frametype) {
1983                         case AST_FRAME_DTMF:
1984                                 res = f->subclass;
1985                                 ast_frfree(f);
1986                                 return res;
1987                         case AST_FRAME_CONTROL:
1988                                 switch (f->subclass) {
1989                                 case AST_CONTROL_HANGUP:
1990                                         ast_frfree(f);
1991                                         return -1;
1992                                 case AST_CONTROL_RINGING:
1993                                 case AST_CONTROL_ANSWER:
1994                                         /* Unimportant */
1995                                         break;
1996                                 default:
1997                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1998                                         break;
1999                                 }
2000                                 break;
2001                         case AST_FRAME_VOICE:
2002                                 /* Write audio if appropriate */
2003                                 if (audiofd > -1)
2004                                         write(audiofd, f->data, f->datalen);
2005                         default:
2006                                 /* Ignore */
2007                                 break;
2008                         }
2009                         ast_frfree(f);
2010                 }
2011         }
2012         return 0; /* Time is up */
2013 }
2014
2015 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2016 {
2017         struct ast_frame *f = NULL;     /* the return value */
2018         int blah;
2019         int prestate;
2020
2021         /* this function is very long so make sure there is only one return
2022          * point at the end (there is only one exception to this).
2023          */
2024         ast_channel_lock(chan);
2025         if (chan->masq) {
2026                 if (ast_do_masquerade(chan))
2027                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2028                 else
2029                         f =  &ast_null_frame;
2030                 goto done;
2031         }
2032
2033         /* Stop if we're a zombie or need a soft hangup */
2034         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2035                 if (chan->generator)
2036                         ast_deactivate_generator(chan);
2037                 goto done;
2038         }
2039         prestate = chan->_state;
2040
2041         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
2042             !ast_strlen_zero(chan->dtmfq)) {
2043                 /* We have DTMF that has been deferred.  Return it now */
2044                 chan->dtmff.subclass = chan->dtmfq[0];
2045                 /* Drop first digit from the buffer */
2046                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2047                 f = &chan->dtmff;
2048                 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY))
2049                         chan->dtmff.frametype = AST_FRAME_DTMF_END;
2050                 else {
2051                         chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2052                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2053                         chan->emulate_dtmf_digit = f->subclass;
2054                         chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2055                         chan->dtmf_begin_tv = ast_tvnow();
2056                 }
2057                 goto done;
2058         }
2059         
2060         /* Read and ignore anything on the alertpipe, but read only
2061            one sizeof(blah) per frame that we send from it */
2062         if (chan->alertpipe[0] > -1)
2063                 read(chan->alertpipe[0], &blah, sizeof(blah));
2064
2065 #ifdef HAVE_ZAPTEL
2066         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2067                 int res;
2068
2069                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2070                 blah = -1;
2071                 /* IF we can't get event, assume it's an expired as-per the old interface */
2072                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2073                 if (res)
2074                         blah = ZT_EVENT_TIMER_EXPIRED;
2075
2076                 if (blah == ZT_EVENT_TIMER_PING) {
2077                         if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2078                                 /* Acknowledge PONG unless we need it again */
2079                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2080                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2081                                 }
2082                         }
2083                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2084                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2085                         if (chan->timingfunc) {
2086                                 /* save a copy of func/data before unlocking the channel */
2087                                 int (*func)(void *) = chan->timingfunc;
2088                                 void *data = chan->timingdata;
2089                                 ast_channel_unlock(chan);
2090                                 func(data);
2091                         } else {
2092                                 blah = 0;
2093                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2094                                 chan->timingdata = NULL;
2095                                 ast_channel_unlock(chan);
2096                         }
2097                         /* cannot 'goto done' because the channel is already unlocked */
2098                         return &ast_null_frame;
2099                 } else
2100                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2101         } else
2102 #endif
2103         if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2104                 /* if the AST_GENERATOR_FD is set, call the generator with args
2105                  * set to -1 so it can do whatever it needs to.
2106                  */
2107                 void *tmp = chan->generatordata;
2108                 chan->generatordata = NULL;     /* reset to let ast_write get through */
2109                 chan->generator->generate(chan, tmp, -1, -1);
2110                 chan->generatordata = tmp;
2111                 f = &ast_null_frame;
2112                 goto done;
2113         }
2114
2115         /* Check for pending read queue */
2116         if (!AST_LIST_EMPTY(&chan->readq)) {
2117                 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2118                 /* Interpret hangup and return NULL */
2119                 /* XXX why not the same for frames from the channel ? */
2120                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2121                         ast_frfree(f);
2122                         f = NULL;
2123                 }
2124         } else {
2125                 chan->blocker = pthread_self();
2126                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2127                         if (chan->tech->exception)
2128                                 f = chan->tech->exception(chan);
2129                         else {
2130                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2131                                 f = &ast_null_frame;
2132                         }
2133                         /* Clear the exception flag */
2134                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2135                 } else if (chan->tech->read)
2136                         f = chan->tech->read(chan);
2137                 else
2138                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2139         }
2140
2141         if (f) {
2142                 /* if the channel driver returned more than one frame, stuff the excess
2143                    into the readq for the next ast_read call (note that we can safely assume
2144                    that the readq is empty, because otherwise we would not have called into
2145                    the channel driver and f would be only a single frame)
2146                 */
2147                 if (AST_LIST_NEXT(f, frame_list)) {
2148                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2149                         AST_LIST_NEXT(f, frame_list) = NULL;
2150                 }
2151
2152                 switch (f->frametype) {
2153                 case AST_FRAME_CONTROL:
2154                         if (f->subclass == AST_CONTROL_ANSWER) {
2155                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2156                                         if (option_debug)
2157                                                 ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
2158                                         ast_frfree(f);
2159                                         f = &ast_null_frame;
2160                                 } else if (prestate == AST_STATE_UP) {
2161                                         if (option_debug)
2162                                                 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
2163                                         ast_frfree(f);
2164                                         f = &ast_null_frame;
2165                                 } else {
2166                                         /* Answer the CDR */
2167                                         ast_setstate(chan, AST_STATE_UP);
2168                                         if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2169                                                                                  to keep from throwing off the basic order of the universe,
2170                                                                                  we will try to keep this cdr from getting posted. */
2171                                                 chan->cdr = ast_cdr_alloc();
2172                                                 ast_cdr_init(chan->cdr, chan);
2173                                                 ast_cdr_start(chan->cdr);
2174                                         }
2175                                         
2176                                         ast_cdr_answer(chan->cdr);
2177                                 }
2178                         }
2179                         break;
2180                 case AST_FRAME_DTMF_END:
2181                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2182                         /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2183                          * However, only let emulation be forced if the other end cares about BEGIN frames */
2184                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2185                                 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2186                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2187                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2188                                 else
2189                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2190                                 ast_frfree(f);
2191                                 f = &ast_null_frame;
2192                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2193                                 f->frametype = AST_FRAME_DTMF_BEGIN;
2194                                 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2195                                 chan->emulate_dtmf_digit = f->subclass;
2196                                 chan->dtmf_begin_tv = ast_tvnow();
2197                                 if (f->len)
2198                                         chan->emulate_dtmf_duration = f->len;
2199                                 else
2200                                         chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2201                         } else {
2202                                 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2203                                 if (!f->len)
2204                                         f->len = ast_tvdiff_ms(ast_tvnow(), chan->dtmf_begin_tv);
2205                         }
2206                         break;
2207                 case AST_FRAME_DTMF_BEGIN:
2208                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2209                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2210                                 ast_frfree(f);
2211                                 f = &ast_null_frame;
2212                         } else {
2213                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2214                                 chan->dtmf_begin_tv = ast_tvnow();
2215                         }
2216                         break;
2217                 case AST_FRAME_VOICE:
2218                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the samples
2219                          * first get to zero, because we want to make sure we pass at least one
2220                          * voice frame through before starting the next digit, to ensure a gap
2221                          * between DTMF digits. */
2222                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2223                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2224                                 chan->emulate_dtmf_digit = 0;
2225                         }
2226
2227                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2228                                 ast_frfree(f);
2229                                 f = &ast_null_frame;
2230                         } else if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2231                                 if ((f->samples / 8) >= chan->emulate_dtmf_duration) { /* XXX 8kHz */
2232                                         chan->emulate_dtmf_duration = 0;
2233                                         f->frametype = AST_FRAME_DTMF_END;
2234                                         f->subclass = chan->emulate_dtmf_digit;
2235                                         f->len = ast_tvdiff_ms(ast_tvnow(), chan->dtmf_begin_tv);
2236                                 } else {
2237                                         chan->emulate_dtmf_duration -= f->samples / 8; /* XXX 8kHz */
2238                                         ast_frfree(f);
2239                                         f = &ast_null_frame;
2240                                 }
2241                         } else if (!(f->subclass & chan->nativeformats)) {
2242                                 /* This frame can't be from the current native formats -- drop it on the
2243                                    floor */
2244                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2245                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2246                                 ast_frfree(f);
2247                                 f = &ast_null_frame;
2248                         } else {
2249                                 if (chan->spies)
2250                                         queue_frame_to_spies(chan, f, SPY_READ);
2251                                 
2252                                 if (chan->monitor && chan->monitor->read_stream ) {
2253                                         /* XXX what does this do ? */
2254 #ifndef MONITOR_CONSTANT_DELAY
2255                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2256                                         if (jump >= 0) {
2257                                                 jump = chan->outsmpl - chan->insmpl;
2258                                                 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2259                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2260                                                 chan->insmpl += jump + f->samples;
2261                                         } else
2262                                                 chan->insmpl+= f->samples;
2263 #else
2264                                         int jump = chan->outsmpl - chan->insmpl;
2265                                         if (jump - MONITOR_DELAY >= 0) {
2266                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2267                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2268                                                 chan->insmpl += jump;
2269                                         } else
2270                                                 chan->insmpl += f->samples;
2271 #endif
2272                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2273                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2274                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2275                                         }
2276                                 }
2277
2278                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2279                                         f = &ast_null_frame;
2280
2281                                 /* Run generator sitting on the line if timing device not available
2282                                 * and synchronous generation of outgoing frames is necessary       */
2283                                 if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2284                                         void *tmp = chan->generatordata;
2285                                         int res;
2286
2287                                         if (chan->timingfunc) {
2288                                                 if (option_debug > 1)
2289                                                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2290                                                 ast_settimeout(chan, 0, NULL, NULL);
2291                                         }
2292
2293                                         chan->generatordata = NULL;     /* reset, to let writes go through */
2294                                         res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2295                                         chan->generatordata = tmp;
2296                                         if (res) {
2297                                                 if (option_debug > 1)
2298                                                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2299                                                 ast_deactivate_generator(chan);
2300                                         }
2301
2302                                 } else if (f->frametype == AST_FRAME_CNG) {
2303                                         if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2304                                                 if (option_debug > 1)
2305                                                         ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2306                                                 ast_settimeout(chan, 160, generator_force, chan);
2307                                         }
2308                                 }
2309                         }
2310                 default:
2311                         /* Just pass it on! */
2312                         break;
2313                 }
2314         } else {
2315                 /* Make sure we always return NULL in the future */
2316                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2317                 if (chan->generator)
2318                         ast_deactivate_generator(chan);
2319                 /* End the CDR if appropriate */
2320                 if (chan->cdr)
2321                         ast_cdr_end(chan->cdr);
2322         }
2323
2324         /* High bit prints debugging */
2325         if (chan->fin & DEBUGCHAN_FLAG)
2326                 ast_frame_dump(chan->name, f, "<<");
2327         chan->fin = FRAMECOUNT_INC(chan->fin);
2328
2329 done:
2330         ast_channel_unlock(chan);
2331         return f;
2332 }
2333
2334 int ast_internal_timing_enabled(struct ast_channel *chan)
2335 {
2336         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2337         if (option_debug > 4)
2338                 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);
2339         return ret;
2340 }
2341
2342 struct ast_frame *ast_read(struct ast_channel *chan)
2343 {
2344         return __ast_read(chan, 0);
2345 }
2346
2347 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2348 {
2349         return __ast_read(chan, 1);
2350 }
2351
2352 int ast_indicate(struct ast_channel *chan, int condition)
2353 {
2354         return ast_indicate_data(chan, condition, NULL, 0);
2355 }
2356
2357 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2358 {
2359         int res = -1;
2360
2361         ast_channel_lock(chan);
2362         /* Stop if we're a zombie or need a soft hangup */
2363         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2364                 ast_channel_unlock(chan);
2365                 return -1;
2366         }
2367         if (chan->tech->indicate)
2368                 res = chan->tech->indicate(chan, condition, data, datalen);
2369         ast_channel_unlock(chan);
2370         if (!chan->tech->indicate || res) {
2371                 /*
2372                  * Device does not support (that) indication, lets fake
2373                  * it by doing our own tone generation. (PM2002)
2374                  */
2375                 if (condition < 0)
2376                         ast_playtones_stop(chan);
2377                 else {
2378                         const struct ind_tone_zone_sound *ts = NULL;
2379                         switch (condition) {
2380                         case AST_CONTROL_RINGING:
2381                                 ts = ast_get_indication_tone(chan->zone, "ring");
2382                                 break;
2383                         case AST_CONTROL_BUSY:
2384                                 ts = ast_get_indication_tone(chan->zone, "busy");
2385                                 break;
2386                         case AST_CONTROL_CONGESTION:
2387                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2388                                 break;
2389                         }
2390                         if (ts && ts->data[0]) {
2391                                 if (option_debug)
2392                                         ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2393                                 ast_playtones_start(chan,0,ts->data, 1);
2394                                 res = 0;
2395                         } else if (condition == AST_CONTROL_PROGRESS) {
2396                                 /* ast_playtones_stop(chan); */
2397                         } else if (condition == AST_CONTROL_PROCEEDING) {
2398                                 /* Do nothing, really */
2399                         } else if (condition == AST_CONTROL_HOLD) {
2400                                 /* Do nothing.... */
2401                         } else if (condition == AST_CONTROL_UNHOLD) {
2402                                 /* Do nothing.... */
2403                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2404                                 /* Do nothing.... */
2405                         } else {
2406                                 /* not handled */
2407                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2408                                 res = -1;
2409                         }
2410                 }
2411         }
2412         return res;
2413 }
2414
2415 int ast_recvchar(struct ast_channel *chan, int timeout)
2416 {
2417         int c;
2418         char *buf = ast_recvtext(chan, timeout);
2419         if (buf == NULL)
2420                 return -1;      /* error or timeout */
2421         c = *(unsigned char *)buf;
2422         free(buf);
2423         return c;
2424 }
2425
2426 char *ast_recvtext(struct ast_channel *chan, int timeout)
2427 {
2428         int res, done = 0;
2429         char *buf = NULL;
2430         
2431         while (!done) {
2432                 struct ast_frame *f;
2433                 if (ast_check_hangup(chan))
2434                         break;
2435                 res = ast_waitfor(chan, timeout);
2436                 if (res <= 0) /* timeout or error */
2437                         break;
2438                 timeout = res;  /* update timeout */
2439                 f = ast_read(chan);
2440                 if (f == NULL)
2441                         break; /* no frame */
2442                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2443                         done = 1;       /* force a break */
2444                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2445                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2446                         done = 1;
2447                 }
2448                 ast_frfree(f);
2449         }
2450         return buf;
2451 }
2452
2453 int ast_sendtext(struct ast_channel *chan, const char *text)
2454 {
2455         int res = 0;
2456         /* Stop if we're a zombie or need a soft hangup */
2457         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2458                 return -1;
2459         CHECK_BLOCKING(chan);
2460         if (chan->tech->send_text)
2461                 res = chan->tech->send_text(chan, text);
2462         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2463         return res;
2464 }
2465
2466 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2467 {
2468         int res = -1;
2469
2470         if (chan->tech->send_digit_begin)
2471                 res = chan->tech->send_digit_begin(chan, digit);
2472
2473         if (res) {
2474                 /*
2475                  * Device does not support DTMF tones, lets fake
2476                  * it by doing our own generation. (PM2002)
2477                  */
2478                 static const char* dtmf_tones[] = {
2479                         "!941+1336/100,!0/100", /* 0 */
2480                         "!697+1209/100,!0/100", /* 1 */
2481                         "!697+1336/100,!0/100", /* 2 */
2482                         "!697+1477/100,!0/100", /* 3 */
2483                         "!770+1209/100,!0/100", /* 4 */
2484                         "!770+1336/100,!0/100", /* 5 */
2485                         "!770+1477/100,!0/100", /* 6 */
2486                         "!852+1209/100,!0/100", /* 7 */
2487                         "!852+1336/100,!0/100", /* 8 */
2488                         "!852+1477/100,!0/100", /* 9 */
2489                         "!697+1633/100,!0/100", /* A */
2490                         "!770+1633/100,!0/100", /* B */
2491                         "!852+1633/100,!0/100", /* C */
2492                         "!941+1633/100,!0/100", /* D */
2493                         "!941+1209/100,!0/100", /* * */
2494                         "!941+1477/100,!0/100" };       /* # */
2495                 if (digit >= '0' && digit <='9')
2496                         ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2497                 else if (digit >= 'A' && digit <= 'D')
2498                         ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2499                 else if (digit == '*')
2500                         ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2501                 else if (digit == '#')
2502                         ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2503                 else {
2504                         /* not handled */
2505                         if (option_debug)
2506                                 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2507                 }
2508         }
2509
2510         return 0;
2511 }
2512
2513 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2514 {
2515         int res = -1;
2516
2517         if (chan->tech->send_digit_end)
2518                 res = chan->tech->send_digit_end(chan, digit, duration);
2519
2520         if (res && chan->generator)
2521                 ast_playtones_stop(chan);
2522         
2523         return 0;
2524 }
2525
2526 int ast_senddigit(struct ast_channel *chan, char digit)
2527 {
2528         if (!ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2529                 ast_senddigit_begin(chan, digit);
2530                 ast_safe_sleep(chan, 100); /* XXX 100ms ... probably should be configurable */
2531         }
2532         
2533         return ast_senddigit_end(chan, digit, 100);
2534 }
2535
2536 int ast_prod(struct ast_channel *chan)
2537 {
2538         struct ast_frame a = { AST_FRAME_VOICE };
2539         char nothing[128];
2540
2541         /* Send an empty audio frame to get things moving */
2542         if (chan->_state != AST_STATE_UP) {
2543                 if (option_debug)
2544                         ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2545                 a.subclass = chan->rawwriteformat;
2546                 a.data = nothing + AST_FRIENDLY_OFFSET;
2547                 a.src = "ast_prod";
2548                 if (ast_write(chan, &a))
2549                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2550         }
2551         return 0;
2552 }
2553
2554 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2555 {
2556         int res;
2557         if (!chan->tech->write_video)
2558                 return 0;
2559         res = ast_write(chan, fr);
2560         if (!res)
2561                 res = 1;
2562         return res;
2563 }
2564
2565 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2566 {
2567         int res = -1;
2568         struct ast_frame *f = NULL;
2569
2570         /* Stop if we're a zombie or need a soft hangup */
2571         ast_channel_lock(chan);
2572         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2573                 goto done;
2574
2575         /* Handle any pending masquerades */
2576         if (chan->masq && ast_do_masquerade(chan)) {
2577                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2578                 goto done;
2579         }
2580         if (chan->masqr) {
2581                 res = 0;        /* XXX explain, why 0 ? */
2582                 goto done;
2583         }
2584         if (chan->generatordata) {
2585                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2586                         ast_deactivate_generator(chan);
2587                 else {
2588                         res = 0;        /* XXX explain, why 0 ? */
2589                         goto done;
2590                 }
2591         }
2592         /* High bit prints debugging */
2593         if (chan->fout & DEBUGCHAN_FLAG)
2594                 ast_frame_dump(chan->name, fr, ">>");
2595         CHECK_BLOCKING(chan);
2596         switch (fr->frametype) {
2597         case AST_FRAME_CONTROL:
2598                 res = (chan->tech->indicate == NULL) ? 0 :
2599                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2600                 break;
2601         case AST_FRAME_DTMF_BEGIN:
2602                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2603                 ast_channel_unlock(chan);
2604                 res = ast_senddigit_begin(chan, fr->subclass);
2605                 ast_channel_lock(chan);
2606                 CHECK_BLOCKING(chan);
2607                 break;
2608         case AST_FRAME_DTMF_END:
2609                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2610                 ast_channel_unlock(chan);
2611                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2612                 ast_channel_lock(chan);
2613                 CHECK_BLOCKING(chan);
2614                 break;
2615         case AST_FRAME_TEXT:
2616                 if (fr->subclass == AST_FORMAT_T140) {
2617                         res = (chan->tech->write_text == NULL) ? 0 :
2618                                 chan->tech->write_text(chan, fr);
2619                 } else {
2620                         res = (chan->tech->send_text == NULL) ? 0 :
2621                                 chan->tech->send_text(chan, (char *) fr->data);
2622                 }
2623                 break;
2624         case AST_FRAME_HTML:
2625                 res = (chan->tech->send_html == NULL) ? 0 :
2626                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2627                 break;
2628         case AST_FRAME_VIDEO:
2629                 /* XXX Handle translation of video codecs one day XXX */
2630                 res = (chan->tech->write_video == NULL) ? 0 :
2631                         chan->tech->write_video(chan, fr);
2632                 break;
2633         case AST_FRAME_MODEM:
2634                 res = (chan->tech->write == NULL) ? 0 :
2635                         chan->tech->write(chan, fr);
2636                 break;
2637         case AST_FRAME_VOICE:
2638                 if (chan->tech->write == NULL)
2639                         break;  /*! \todo XXX should return 0 maybe ? */
2640
2641                 /* If someone is whispering on this channel then we must ensure that we are always getting signed linear frames */
2642                 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2643                         if (fr->subclass == AST_FORMAT_SLINEAR)
2644                                 f = fr;
2645                         else {
2646                                 ast_mutex_lock(&chan->whisper->lock);
2647                                 if (chan->writeformat != AST_FORMAT_SLINEAR) {
2648                                         /* Rebuild the translation path and set our write format back to signed linear */
2649                                         chan->whisper->original_format = chan->writeformat;
2650                                         ast_set_write_format(chan, AST_FORMAT_SLINEAR);
2651                                         if (chan->whisper->path)
2652                                                 ast_translator_free_path(chan->whisper->path);
2653                                         chan->whisper->path = ast_translator_build_path(AST_FORMAT_SLINEAR, chan->whisper->original_format);
2654                                 }
2655                                 /* Translate frame using the above translation path */
2656                                 f = (chan->whisper->path) ? ast_translate(chan->whisper->path, fr, 0) : fr;
2657                                 ast_mutex_unlock(&chan->whisper->lock);
2658                         }
2659                 } else {
2660                         /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2661                         if (fr->subclass == chan->rawwriteformat)
2662                                 f = fr;
2663                         else
2664                                 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2665                 }
2666
2667                 /* If we have no frame of audio, then we have to bail out */
2668                 if (f == NULL) {
2669                         res = 0;
2670                         break;
2671                 }
2672
2673                 /* If spies are on the channel then queue the frame out to them */
2674                 if (chan->spies)
2675                         queue_frame_to_spies(chan, f, SPY_WRITE);
2676
2677                 /* If Monitor is running on this channel, then we have to write frames out there too */
2678                 if (chan->monitor && chan->monitor->write_stream) {
2679                         /* XXX must explain this code */
2680 #ifndef MONITOR_CONSTANT_DELAY
2681                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2682                         if (jump >= 0) {
2683                                 jump = chan->insmpl - chan->outsmpl;
2684                                 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2685                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2686                                 chan->outsmpl += jump + f->samples;
2687                         } else
2688                                 chan->outsmpl += f->samples;
2689 #else
2690                         int jump = chan->insmpl - chan->outsmpl;
2691                         if (jump - MONITOR_DELAY >= 0) {
2692                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2693                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2694                                 chan->outsmpl += jump;
2695                         } else
2696                                 chan->outsmpl += f->samples;
2697 #endif
2698                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2699                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2700                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2701                         }
2702                 }
2703
2704                 /* Finally the good part! Write this out to the channel */
2705                 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2706                         /* frame is assumed to be in SLINEAR, since that is
2707                            required for whisper mode */
2708                         ast_frame_adjust_volume(f, -2);
2709                         if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2710                                 short buf[f->samples];
2711                                 struct ast_frame whisper = {
2712                                         .frametype = AST_FRAME_VOICE,
2713                                         .subclass = AST_FORMAT_SLINEAR,
2714                                         .data = buf,
2715                                         .datalen = sizeof(buf),
2716                                         .samples = f->samples,
2717                                 };
2718                                 
2719                                 ast_mutex_lock(&chan->whisper->lock);
2720                                 if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2721                                         ast_frame_slinear_sum(f, &whisper);
2722                                 ast_mutex_unlock(&chan->whisper->lock);
2723                         }
2724                         /* and now put it through the regular translator */
2725                         f = (chan->writetrans) ? ast_translate(chan->writetrans, f, 0) : f;
2726                 }
2727                 res = f ? chan->tech->write(chan, f) : 0;
2728                 break;
2729         case AST_FRAME_NULL:
2730         case AST_FRAME_IAX:
2731                 /* Ignore these */
2732                 res = 0;
2733                 break;
2734         default:
2735                 /* At this point, fr is the incoming frame and f is NULL.  Channels do
2736                  * not expect to get NULL as a frame pointer and will segfault.  Hence,
2737                  * we output the original frame passed in. */
2738                 res = chan->tech->write(chan, fr);
2739                 break;
2740         }
2741
2742         if (f && f != fr)
2743                 ast_frfree(f);
2744         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2745         /* Consider a write failure to force a soft hangup */
2746         if (res < 0)
2747                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2748         else {
2749                 chan->fout = FRAMECOUNT_INC(chan->fout);
2750         }
2751 done:
2752         ast_channel_unlock(chan);
2753         return res;
2754 }
2755
2756 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2757                       struct ast_trans_pvt **trans, const int direction)
2758 {
2759         int native;
2760         int res;
2761         
2762         /* Make sure we only consider audio */
2763         fmt &= AST_FORMAT_AUDIO_MASK;
2764         
2765         native = chan->nativeformats;
2766         /* Find a translation path from the native format to one of the desired formats */
2767         if (!direction)
2768                 /* reading */
2769                 res = ast_translator_best_choice(&fmt, &native);
2770         else
2771                 /* writing */
2772                 res = ast_translator_best_choice(&native, &fmt);
2773
2774         if (res < 0) {
2775                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2776                         ast_getformatname(native), ast_getformatname(fmt));
2777                 return -1;
2778         }
2779         
2780         /* Now we have a good choice for both. */
2781         ast_channel_lock(chan);
2782
2783         if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2784                 /* the channel is already in these formats, so nothing to do */
2785                 ast_channel_unlock(chan);
2786                 return 0;
2787         }
2788
2789         *rawformat = native;
2790         /* User perspective is fmt */
2791         *format = fmt;
2792         /* Free any read translation we have right now */
2793         if (*trans)
2794                 ast_translator_free_path(*trans);
2795         /* Build a translation path from the raw format to the desired format */
2796         if (!direction)
2797                 /* reading */
2798                 *trans = ast_translator_build_path(*format, *rawformat);
2799         else
2800                 /* writing */
2801                 *trans = ast_translator_build_path(*rawformat, *format);
2802         ast_channel_unlock(chan);
2803         if (option_debug)
2804                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2805                         direction ? "write" : "read", ast_getformatname(fmt));
2806         return 0;
2807 }
2808
2809 int ast_set_read_format(struct ast_channel *chan, int fmt)
2810 {
2811         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2812                           &chan->readtrans, 0);
2813 }
2814
2815 int ast_set_write_format(struct ast_channel *chan, int fmt)
2816 {
2817         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2818                           &chan->writetrans, 1);
2819 }
2820
2821 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)
2822 {
2823         int dummy_outstate;
2824         int cause = 0;
2825         struct ast_channel *chan;
2826         int res = 0;
2827         
2828         if (outstate)
2829                 *outstate = 0;
2830         else
2831                 outstate = &dummy_outstate;     /* make outstate always a valid pointer */
2832
2833         chan = ast_request(type, format, data, &cause);
2834         if (!chan) {
2835                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2836                 /* compute error and return */
2837                 if (cause == AST_CAUSE_BUSY)
2838                         *outstate = AST_CONTROL_BUSY;
2839                 else if (cause == AST_CAUSE_CONGESTION)
2840                         *outstate = AST_CONTROL_CONGESTION;
2841                 return NULL;
2842         }
2843
2844         if (oh) {
2845                 if (oh->vars)   
2846                         ast_set_variables(chan, oh->vars);
2847                 /* XXX why is this necessary, for the parent_channel perhaps ? */
2848                 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2849                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2850                 if (oh->parent_channel) {
2851                         ast_channel_inherit_variables(oh->parent_channel, chan);
2852                         ast_channel_datastore_inherit(oh->parent_channel, chan);
2853                 }
2854                 if (oh->account)
2855                         ast_cdr_setaccount(chan, oh->account);  
2856         }
2857         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2858
2859         
2860
2861         if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2862                                 to keep from throwing off the basic order of the universe,
2863                                 we will try to keep this cdr from getting posted. */
2864                 chan->cdr = ast_cdr_alloc();
2865                 ast_cdr_init(chan->cdr, chan);
2866                 ast_cdr_start(chan->cdr);
2867         }
2868         if (ast_call(chan, data, 0)) {  /* ast_call failed... */
2869                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2870         } else {
2871                 res = 1;        /* mark success in case chan->_state is already AST_STATE_UP */
2872                 while (timeout && chan->_state != AST_STATE_UP) {
2873                         struct ast_frame *f;
2874                         res = ast_waitfor(chan, timeout);
2875                         if (res <= 0) /* error, timeout, or done */
2876                                 break;
2877                         if (timeout > -1)
2878                                 timeout = res;
2879                         f = ast_read(chan);
2880                         if (!f) {
2881                                 *outstate = AST_CONTROL_HANGUP;
2882                                 res = 0;
2883                                 break;
2884                         }
2885                         if (f->frametype == AST_FRAME_CONTROL) {
2886                                 switch (f->subclass) {
2887                                 case AST_CONTROL_RINGING:       /* record but keep going */
2888                                         *outstate = f->subclass;
2889                                         break;
2890
2891                                 case AST_CONTROL_BUSY:
2892                                 case AST_CONTROL_CONGESTION:
2893                                 case AST_CONTROL_ANSWER:
2894                                         *outstate = f->subclass;
2895                                         timeout = 0;            /* trick to force exit from the while() */
2896                                         break;
2897
2898                                 /* Ignore these */
2899                                 case AST_CONTROL_PROGRESS:
2900                                 case AST_CONTROL_PROCEEDING:
2901                                 case AST_CONTROL_HOLD:
2902                                 case AST_CONTROL_UNHOLD:
2903                                 case AST_CONTROL_VIDUPDATE:
2904                                 case -1:                        /* Ignore -- just stopping indications */
2905                                         break;
2906
2907                                 default:
2908                                         ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2909                                 }
2910                         }
2911                         ast_frfree(f);
2912                 }
2913         }
2914
2915         /* Final fixups */
2916         if (oh) {
2917                 if (!ast_strlen_zero(oh->context))
2918                         ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2919                 if (!ast_strlen_zero(oh->exten))
2920                         ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2921                 if (oh->priority)       
2922                         chan->priority = oh->priority;
2923         }
2924         if (chan->_state == AST_STATE_UP)
2925                 *outstate = AST_CONTROL_ANSWER;
2926
2927         if (res <= 0) {
2928                 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2929                         ast_cdr_init(chan->cdr, chan);
2930                 if (chan->cdr) {
2931                         char tmp[256];
2932                         snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2933                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2934                         ast_cdr_update(chan);
2935                         ast_cdr_start(chan->cdr);
2936                         ast_cdr_end(chan->cdr);
2937                         /* If the cause wasn't handled properly */
2938                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2939                                 ast_cdr_failed(chan->cdr);
2940                 }
2941                 ast_hangup(chan);
2942                 chan = NULL;
2943         }
2944         return chan;
2945 }
2946
2947 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2948 {
2949         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2950 }
2951
2952 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2953 {
2954         struct chanlist *chan;
2955         struct ast_channel *c;
2956         int capabilities;
2957         int fmt;
2958         int res;
2959         int foo;
2960         int videoformat = format & AST_FORMAT_VIDEO_MASK;
2961         int textformat = format & AST_FORMAT_TEXT_MASK;
2962
2963         if (!cause)
2964                 cause = &foo;
2965         *cause = AST_CAUSE_NOTDEFINED;
2966
2967         if (AST_LIST_LOCK(&channels)) {
2968                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2969                 return NULL;
2970         }
2971
2972         AST_LIST_TRAVERSE(&backends, chan, list) {
2973                 if (strcasecmp(type, chan->tech->type))
2974                         continue;
2975
2976                 capabilities = chan->tech->capabilities;
2977                 fmt = format & AST_FORMAT_AUDIO_MASK;
2978                 res = ast_translator_best_choice(&fmt, &capabilities);
2979                 if (res < 0) {
2980                         ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2981                         AST_LIST_UNLOCK(&channels);
2982                         return NULL;
2983                 }
2984                 AST_LIST_UNLOCK(&channels);
2985                 if (!chan->tech->requester)
2986                         return NULL;
2987                 
2988                 if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, data, cause)))
2989                         return NULL;
2990                 
2991                 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
2992                 return c;
2993         }
2994
2995         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2996         *cause = AST_CAUSE_NOSUCHDRIVER;
2997         AST_LIST_UNLOCK(&channels);
2998
2999         return NULL;
3000 }
3001
3002 int ast_call(struct ast_channel *chan, char *addr, int timeout)
3003 {
3004         /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3005            If the remote end does not answer within the timeout, then do NOT hang up, but
3006            return anyway.  */
3007         int res = -1;
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->call)
3012                         res = chan->tech->call(chan, addr, timeout);
3013                 ast_set_flag(chan, AST_FLAG_OUTGOING);
3014         }
3015         ast_channel_unlock(chan);
3016         return res;
3017 }
3018
3019 /*!
3020   \brief Transfer a call to dest, if the channel supports transfer
3021
3022   Called by:
3023     \arg app_transfer
3024     \arg the manager interface
3025 */
3026 int ast_transfer(struct ast_channel *chan, char *dest)
3027 {
3028         int res = -1;
3029
3030         /* Stop if we're a zombie or need a soft hangup */
3031         ast_channel_lock(chan);
3032         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3033                 if (chan->tech->transfer) {
3034                         res = chan->tech->transfer(chan, dest);
3035                         if (!res)
3036                                 res = 1;
3037                 } else
3038                         res = 0;
3039         }
3040         ast_channel_unlock(chan);
3041         return res;
3042 }
3043
3044 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3045 {
3046         return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3047 }
3048
3049 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3050 {
3051         int pos = 0;    /* index in the buffer where we accumulate digits */
3052         int to = ftimeout;
3053
3054         /* Stop if we're a zombie or need a soft hangup */
3055         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3056                 return -1;
3057         if (!len)
3058                 return -1;
3059         for (;;) {
3060                 int d;
3061                 if (c->stream) {
3062                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3063                         ast_stopstream(c);
3064                         usleep(1000);
3065                         if (!d)
3066                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3067                 } else {
3068                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3069                 }
3070                 if (d < 0)