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