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