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