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