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