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