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