include "asterisk/zapata.h" to get the zaptel headers.
[asterisk/asterisk.git] / main / channel.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Channel Management
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <sys/time.h>
35 #include <signal.h>
36 #include <errno.h>
37 #include <unistd.h>
38 #include <math.h>
39
40 #include "asterisk/zapata.h"
41
42 #include "asterisk/pbx.h"
43 #include "asterisk/frame.h"
44 #include "asterisk/sched.h"
45 #include "asterisk/options.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/chanspy.h"
48 #include "asterisk/musiconhold.h"
49 #include "asterisk/logger.h"
50 #include "asterisk/say.h"
51 #include "asterisk/file.h"
52 #include "asterisk/cli.h"
53 #include "asterisk/translate.h"
54 #include "asterisk/manager.h"
55 #include "asterisk/chanvars.h"
56 #include "asterisk/linkedlists.h"
57 #include "asterisk/indications.h"
58 #include "asterisk/monitor.h"
59 #include "asterisk/causes.h"
60 #include "asterisk/callerid.h"
61 #include "asterisk/utils.h"
62 #include "asterisk/lock.h"
63 #include "asterisk/app.h"
64 #include "asterisk/transcap.h"
65 #include "asterisk/devicestate.h"
66 #include "asterisk/sha1.h"
67 #include "asterisk/threadstorage.h"
68 #include "asterisk/slinfactory.h"
69
70 struct channel_spy_trans {
71         int last_format;
72         struct ast_trans_pvt *path;
73 };
74
75 struct ast_channel_spy_list {
76         struct channel_spy_trans read_translator;
77         struct channel_spy_trans write_translator;
78         AST_LIST_HEAD_NOLOCK(, ast_channel_spy) list;
79 };
80
81 struct ast_channel_whisper_buffer {
82         ast_mutex_t lock;
83         struct ast_slinfactory sf;
84         unsigned int original_format;
85         struct ast_trans_pvt *path;
86 };
87
88 /* uncomment if you have problems with 'monitoring' synchronized files */
89 #if 0
90 #define MONITOR_CONSTANT_DELAY
91 #define MONITOR_DELAY   150 * 8         /* 150 ms of MONITORING DELAY */
92 #endif
93
94 /*! Prevent new channel allocation if shutting down. */
95 static int shutting_down;
96
97 static int uniqueint;
98
99 unsigned long global_fin, global_fout;
100
101 AST_THREADSTORAGE(state2str_threadbuf);
102 #define STATE2STR_BUFSIZE   32
103
104 /* XXX 100ms ... this won't work with wideband support */
105 #define AST_DEFAULT_EMULATE_DTMF_SAMPLES 800
106
107 struct chanlist {
108         const struct ast_channel_tech *tech;
109         AST_LIST_ENTRY(chanlist) list;
110 };
111
112 /*! the list of registered channel types */
113 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
114
115 /*! the list of channels we have. Note that the lock for this list is used for
116     both the channels list and the backends list.  */
117 static AST_LIST_HEAD_STATIC(channels, ast_channel);
118
119 /*! map AST_CAUSE's to readable string representations */
120 const struct ast_cause {
121         int cause;
122         const char *name;
123         const char *desc;
124 } causes[] = {
125         { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
126         { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
127         { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
128         { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
129         { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
130         { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
131         { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
132         { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
133         { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
134         { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
135         { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
136         { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
137         { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
138         { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
139         { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
140         { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
141         { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
142         { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
143         { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
144         { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
145         { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
146         { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
147         { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
148         { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
149         { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
150         { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
151         { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
152         { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
153         { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
154         { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
155         { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
156         { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
157         { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
158         { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
159         { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
160         { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
161         { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
162         { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
163         { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
164         { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
165         { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
166         { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
167         { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
168         { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
169 };
170
171 struct ast_variable *ast_channeltype_list(void)
172 {
173         struct chanlist *cl;
174         struct ast_variable *var=NULL, *prev = NULL;
175         AST_LIST_TRAVERSE(&backends, cl, list) {
176                 if (prev)  {
177                         if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description)))
178                                 prev = prev->next;
179                 } else {
180                         var = ast_variable_new(cl->tech->type, cl->tech->description);
181                         prev = var;
182                 }
183         }
184         return var;
185 }
186
187 static int show_channeltypes(int fd, int argc, char *argv[])
188 {
189 #define FORMAT  "%-10.10s  %-40.40s %-12.12s %-12.12s %-12.12s\n"
190         struct chanlist *cl;
191         int count_chan = 0;
192
193         ast_cli(fd, FORMAT, "Type", "Description",       "Devicestate", "Indications", "Transfer");
194         ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
195         if (AST_LIST_LOCK(&channels)) {
196                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
197                 return -1;
198         }
199         AST_LIST_TRAVERSE(&backends, cl, list) {
200                 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description,
201                         (cl->tech->devicestate) ? "yes" : "no",
202                         (cl->tech->indicate) ? "yes" : "no",
203                         (cl->tech->transfer) ? "yes" : "no");
204                 count_chan++;
205         }
206         AST_LIST_UNLOCK(&channels);
207         ast_cli(fd, "----------\n%d channel drivers registered.\n", count_chan);
208         return RESULT_SUCCESS;
209
210 #undef FORMAT
211
212 }
213
214 static int show_channeltype(int fd, int argc, char *argv[])
215 {
216         struct chanlist *cl = NULL;
217
218         if (argc != 4)
219                 return RESULT_SHOWUSAGE;
220         
221         if (AST_LIST_LOCK(&channels)) {
222                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
223                 return RESULT_FAILURE;
224         }
225
226         AST_LIST_TRAVERSE(&backends, cl, list) {
227                 if (!strncasecmp(cl->tech->type, argv[3], strlen(cl->tech->type))) {
228                         break;
229                 }
230         }
231
232
233         if (!cl) {
234                 ast_cli(fd, "\n%s is not a registered channel driver.\n", argv[3]);
235                 AST_LIST_UNLOCK(&channels);
236                 return RESULT_FAILURE;
237         }
238
239         ast_cli(fd,
240                 "-- Info about channel driver: %s --\n"
241                 "  Device State: %s\n"
242                 "    Indication: %s\n"
243                 "     Transfer : %s\n"
244                 "  Capabilities: %d\n"
245                 "   Digit Begin: %s\n"
246                 "     Digit End: %s\n"
247                 "    Send HTML : %s\n"
248                 " Image Support: %s\n"
249                 "  Text Support: %s\n",
250                 cl->tech->type,
251                 (cl->tech->devicestate) ? "yes" : "no",
252                 (cl->tech->indicate) ? "yes" : "no",
253                 (cl->tech->transfer) ? "yes" : "no",
254                 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
255                 (cl->tech->send_digit_begin) ? "yes" : "no",
256                 (cl->tech->send_digit_end) ? "yes" : "no",
257                 (cl->tech->send_html) ? "yes" : "no",
258                 (cl->tech->send_image) ? "yes" : "no",
259                 (cl->tech->send_text) ? "yes" : "no"
260                 
261         );
262
263         AST_LIST_UNLOCK(&channels);
264         return RESULT_SUCCESS;
265 }
266
267 static char *complete_channeltypes(const char *line, const char *word, int pos, int state)
268 {
269         struct chanlist *cl;
270         int which = 0;
271         int wordlen;
272         char *ret = NULL;
273
274         if (pos != 3)
275                 return NULL;
276
277         wordlen = strlen(word);
278
279         AST_LIST_TRAVERSE(&backends, cl, list) {
280                 if (!strncasecmp(word, cl->tech->type, wordlen) && ++which > state) {
281                         ret = strdup(cl->tech->type);
282                         break;
283                 }
284         }
285         
286         return ret;
287 }
288
289 static const char show_channeltypes_usage[] =
290 "Usage: core show channeltypes\n"
291 "       Lists available channel types registered in your Asterisk server.\n";
292
293 static const char show_channeltype_usage[] =
294 "Usage: core show channeltype <name>\n"
295 "       Show details about the specified channel type, <name>.\n";
296
297 static struct ast_cli_entry cli_channel[] = {
298         { { "core", "show", "channeltypes", NULL },
299         show_channeltypes, "List available channel types",
300         show_channeltypes_usage },
301
302         { { "core", "show", "channeltype", NULL },
303         show_channeltype, "Give more details on that channel type",
304         show_channeltype_usage, complete_channeltypes },
305 };
306
307 /*! \brief Checks to see if a channel is needing hang up */
308 int ast_check_hangup(struct ast_channel *chan)
309 {
310         if (chan->_softhangup)          /* yes if soft hangup flag set */
311                 return 1;
312         if (!chan->tech_pvt)            /* yes if no technology private data */
313                 return 1;
314         if (!chan->whentohangup)        /* no if no hangup scheduled */
315                 return 0;
316         if (chan->whentohangup > time(NULL))    /* no if hangup time has not come yet. */
317                 return 0;
318         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;    /* record event */
319         return 1;
320 }
321
322 static int ast_check_hangup_locked(struct ast_channel *chan)
323 {
324         int res;
325         ast_channel_lock(chan);
326         res = ast_check_hangup(chan);
327         ast_channel_unlock(chan);
328         return res;
329 }
330
331 /*! \brief Initiate system shutdown */
332 void ast_begin_shutdown(int hangup)
333 {
334         struct ast_channel *c;
335         shutting_down = 1;
336         if (hangup) {
337                 AST_LIST_LOCK(&channels);
338                 AST_LIST_TRAVERSE(&channels, c, chan_list)
339                         ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
340                 AST_LIST_UNLOCK(&channels);
341         }
342 }
343
344 /*! \brief returns number of active/allocated channels */
345 int ast_active_channels(void)
346 {
347         struct ast_channel *c;
348         int cnt = 0;
349         AST_LIST_LOCK(&channels);
350         AST_LIST_TRAVERSE(&channels, c, chan_list)
351                 cnt++;
352         AST_LIST_UNLOCK(&channels);
353         return cnt;
354 }
355
356 /*! \brief Cancel a shutdown in progress */
357 void ast_cancel_shutdown(void)
358 {
359         shutting_down = 0;
360 }
361
362 /*! \brief Returns non-zero if Asterisk is being shut down */
363 int ast_shutting_down(void)
364 {
365         return shutting_down;
366 }
367
368 /*! \brief Set when to hangup channel */
369 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
370 {
371         chan->whentohangup = offset ? time(NULL) + offset : 0;
372         ast_queue_frame(chan, &ast_null_frame);
373         return;
374 }
375
376 /*! \brief Compare a offset with when to hangup channel */
377 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
378 {
379         time_t whentohangup;
380
381         if (chan->whentohangup == 0) {
382                 return (offset == 0) ? 0 : -1;
383         } else {
384                 if (offset == 0)        /* XXX why is this special ? */
385                         return (1);
386                 else {
387                         whentohangup = offset + time (NULL);
388                         if (chan->whentohangup < whentohangup)
389                                 return (1);
390                         else if (chan->whentohangup == whentohangup)
391                                 return (0);
392                         else
393                                 return (-1);
394                 }
395         }
396 }
397
398 /*! \brief Register a new telephony channel in Asterisk */
399 int ast_channel_register(const struct ast_channel_tech *tech)
400 {
401         struct chanlist *chan;
402
403         AST_LIST_LOCK(&channels);
404
405         AST_LIST_TRAVERSE(&backends, chan, list) {
406                 if (!strcasecmp(tech->type, chan->tech->type)) {
407                         ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
408                         AST_LIST_UNLOCK(&channels);
409                         return -1;
410                 }
411         }
412         
413         if (!(chan = ast_calloc(1, sizeof(*chan)))) {
414                 AST_LIST_UNLOCK(&channels);
415                 return -1;
416         }
417         chan->tech = tech;
418         AST_LIST_INSERT_HEAD(&backends, chan, list);
419
420         if (option_debug)
421                 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
422
423         if (option_verbose > 1)
424                 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
425                             chan->tech->description);
426
427         AST_LIST_UNLOCK(&channels);
428         return 0;
429 }
430
431 void ast_channel_unregister(const struct ast_channel_tech *tech)
432 {
433         struct chanlist *chan;
434
435         if (option_debug)
436                 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
437
438         AST_LIST_LOCK(&channels);
439
440         AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
441                 if (chan->tech == tech) {
442                         AST_LIST_REMOVE_CURRENT(&backends, list);
443                         free(chan);
444                         if (option_verbose > 1)
445                                 ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
446                         break;  
447                 }
448         }
449         AST_LIST_TRAVERSE_SAFE_END
450
451         AST_LIST_UNLOCK(&channels);
452 }
453
454 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
455 {
456         struct chanlist *chanls;
457         const struct ast_channel_tech *ret = NULL;
458
459         if (AST_LIST_LOCK(&channels)) {
460                 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
461                 return NULL;
462         }
463
464         AST_LIST_TRAVERSE(&backends, chanls, list) {
465                 if (!strcasecmp(name, chanls->tech->type)) {
466                         ret = chanls->tech;
467                         break;
468                 }
469         }
470
471         AST_LIST_UNLOCK(&channels);
472         
473         return ret;
474 }
475
476 /*! \brief Gives the string form of a given hangup cause */
477 const char *ast_cause2str(int cause)
478 {
479         int x;
480
481         for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
482                 if (causes[x].cause == cause)
483                         return causes[x].desc;
484         }
485
486         return "Unknown";
487 }
488
489 /*! \brief Convert a symbolic hangup cause to number */
490 int ast_str2cause(const char *name)
491 {
492         int x;
493
494         for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
495                 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
496                         return causes[x].cause;
497
498         return -1;
499 }
500
501 /*! \brief Gives the string form of a given channel state.
502         \note This function is not reentrant.
503  */
504 const char *ast_state2str(enum ast_channel_state state)
505 {
506         char *buf;
507
508         switch(state) {
509         case AST_STATE_DOWN:
510                 return "Down";
511         case AST_STATE_RESERVED:
512                 return "Rsrvd";
513         case AST_STATE_OFFHOOK:
514                 return "OffHook";
515         case AST_STATE_DIALING:
516                 return "Dialing";
517         case AST_STATE_RING:
518                 return "Ring";
519         case AST_STATE_RINGING:
520                 return "Ringing";
521         case AST_STATE_UP:
522                 return "Up";
523         case AST_STATE_BUSY:
524                 return "Busy";
525         case AST_STATE_DIALING_OFFHOOK:
526                 return "Dialing Offhook";
527         case AST_STATE_PRERING:
528                 return "Pre-ring";
529         default:
530                 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
531                         return "Unknown";
532                 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
533                 return buf;
534         }
535 }
536
537 /*! \brief Gives the string form of a given transfer capability */
538 char *ast_transfercapability2str(int transfercapability)
539 {
540         switch(transfercapability) {
541         case AST_TRANS_CAP_SPEECH:
542                 return "SPEECH";
543         case AST_TRANS_CAP_DIGITAL:
544                 return "DIGITAL";
545         case AST_TRANS_CAP_RESTRICTED_DIGITAL:
546                 return "RESTRICTED_DIGITAL";
547         case AST_TRANS_CAP_3_1K_AUDIO:
548                 return "3K1AUDIO";
549         case AST_TRANS_CAP_DIGITAL_W_TONES:
550                 return "DIGITAL_W_TONES";
551         case AST_TRANS_CAP_VIDEO:
552                 return "VIDEO";
553         default:
554                 return "UNKNOWN";
555         }
556 }
557
558 /*! \brief Pick the best audio codec */
559 int ast_best_codec(int fmts)
560 {
561         /* This just our opinion, expressed in code.  We are asked to choose
562            the best codec to use, given no information */
563         int x;
564         static int prefs[] =
565         {
566                 /*! Okay, ulaw is used by all telephony equipment, so start with it */
567                 AST_FORMAT_ULAW,
568                 /*! Unless of course, you're a silly European, so then prefer ALAW */
569                 AST_FORMAT_ALAW,
570                 /*! Okay, well, signed linear is easy to translate into other stuff */
571                 AST_FORMAT_SLINEAR,
572                 /*! G.726 is standard ADPCM, in RFC3551 packing order */
573                 AST_FORMAT_G726,
574                 /*! G.726 is standard ADPCM, in AAL2 packing order */
575                 AST_FORMAT_G726_AAL2,
576                 /*! ADPCM has great sound quality and is still pretty easy to translate */
577                 AST_FORMAT_ADPCM,
578                 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
579                     translate and sounds pretty good */
580                 AST_FORMAT_GSM,
581                 /*! iLBC is not too bad */
582                 AST_FORMAT_ILBC,
583                 /*! Speex is free, but computationally more expensive than GSM */
584                 AST_FORMAT_SPEEX,
585                 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
586                     to use it */
587                 AST_FORMAT_LPC10,
588                 /*! G.729a is faster than 723 and slightly less expensive */
589                 AST_FORMAT_G729A,
590                 /*! Down to G.723.1 which is proprietary but at least designed for voice */
591                 AST_FORMAT_G723_1,
592         };
593
594         /* Strip out video */
595         fmts &= AST_FORMAT_AUDIO_MASK;
596         
597         /* Find the first preferred codec in the format given */
598         for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
599                 if (fmts & prefs[x])
600                         return prefs[x];
601         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
602         return 0;
603 }
604
605 static const struct ast_channel_tech null_tech = {
606         .type = "NULL",
607         .description = "Null channel (should not see this)",
608 };
609
610 /*! \brief Create a new channel structure */
611 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num, const char *cid_name, const char *name_fmt, ...)
612 {
613         struct ast_channel *tmp;
614         int x;
615         int flags;
616         struct varshead *headp;
617         va_list ap1, ap2;
618
619         /* If shutting down, don't allocate any new channels */
620         if (shutting_down) {
621                 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
622                 return NULL;
623         }
624
625         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
626                 return NULL;
627
628         if (!(tmp->sched = sched_context_create())) {
629                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
630                 free(tmp);
631                 return NULL;
632         }
633         
634         ast_string_field_init(tmp, 128);
635
636         /* Don't bother initializing the last two FD here, because they
637            will *always* be set just a few lines down (AST_TIMING_FD,
638            AST_ALERT_FD). */
639         for (x = 0; x < AST_MAX_FDS - 2; x++)
640                 tmp->fds[x] = -1;
641
642 #ifdef HAVE_ZAPTEL
643         tmp->timingfd = open("/dev/zap/timer", O_RDWR);
644         if (tmp->timingfd > -1) {
645                 /* Check if timing interface supports new
646                    ping/pong scheme */
647                 flags = 1;
648                 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
649                         needqueue = 0;
650         }
651 #else
652         tmp->timingfd = -1;                                     
653 #endif                                  
654
655         if (needqueue) {
656                 if (pipe(tmp->alertpipe)) {
657                         ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
658                         ast_string_field_free_pools(tmp);
659                         free(tmp);
660                         return NULL;
661                 } else {
662                         flags = fcntl(tmp->alertpipe[0], F_GETFL);
663                         fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
664                         flags = fcntl(tmp->alertpipe[1], F_GETFL);
665                         fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
666                 }
667         } else  /* Make sure we've got it done right if they don't */
668                 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
669
670         /* Always watch the alertpipe */
671         tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
672         /* And timing pipe */
673         tmp->fds[AST_TIMING_FD] = tmp->timingfd;
674         ast_string_field_set(tmp, name, "**Unknown**");
675
676         /* Initial state */
677         tmp->_state = state;
678
679         tmp->streamid = -1;
680         
681         tmp->fin = global_fin;
682         tmp->fout = global_fout;
683
684         if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
685                 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), 
686                                        ast_atomic_fetchadd_int(&uniqueint, 1));
687         } else {
688                 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, 
689                                        (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
690         }
691
692         if (!ast_strlen_zero(name_fmt)) {
693                 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
694                  * And they all use slightly different formats for their name string.
695                  * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
696                  * This means, that the stringfields must have a routine that takes the va_lists directly, and 
697                  * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
698                  * This new function was written so this can be accomplished.
699                  */
700                 va_start(ap1, name_fmt);
701                 va_start(ap2, name_fmt);
702                 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
703                 va_end(ap1);
704                 va_end(ap2);
705
706                 /* and now, since the channel structure is built, and has its name, let's call the
707                  * manager event generator with this Newchannel event. This is the proper and correct
708                  * place to make this call, but you sure do have to pass a lot of data into this func
709                  * to do it here!
710                  */
711                 manager_event(EVENT_FLAG_CALL, "Newchannel",
712                               "Channel: %s\r\n"
713                               "State: %s\r\n"
714                               "CallerIDNum: %s\r\n"
715                               "CallerIDName: %s\r\n"
716                               "Uniqueid: %s\r\n",
717                               tmp->name, ast_state2str(state),
718                               S_OR(cid_num, "<unknown>"),
719                               S_OR(cid_name, "<unknown>"),
720                               tmp->uniqueid);
721         }
722         
723         headp = &tmp->varshead;
724         AST_LIST_HEAD_INIT_NOLOCK(headp);
725         
726         ast_mutex_init(&tmp->lock);
727         
728         AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
729         
730         strcpy(tmp->context, "default");
731         strcpy(tmp->exten, "s");
732         tmp->priority = 1;
733         
734         ast_string_field_set(tmp, language, defaultlanguage);
735         tmp->amaflags = ast_default_amaflags;
736         ast_string_field_set(tmp, accountcode, ast_default_accountcode);
737
738         tmp->tech = &null_tech;
739
740         AST_LIST_LOCK(&channels);
741         AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
742         AST_LIST_UNLOCK(&channels);
743
744         return tmp;
745 }
746
747 /*! \brief Queue an outgoing media frame */
748 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
749 {
750         struct ast_frame *f;
751         struct ast_frame *cur;
752         int blah = 1;
753         int qlen = 0;
754
755         /* Build us a copy and free the original one */
756         if (!(f = ast_frdup(fin))) {
757                 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
758                 return -1;
759         }
760         ast_channel_lock(chan);
761
762         /* See if the last frame on the queue is a hangup, if so don't queue anything */
763         if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
764                 ast_frfree(f);
765                 ast_channel_unlock(chan);
766                 return 0;
767         }
768
769         /* Count how many frames exist on the queue */
770         AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
771                 qlen++;
772         }
773
774         /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
775         if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen  > 128)) {
776                 if (fin->frametype != AST_FRAME_VOICE) {
777                         ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
778                         CRASH;
779                 } else {
780                         if (option_debug)
781                                 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
782                         ast_frfree(f);
783                         ast_channel_unlock(chan);
784                         return 0;
785                 }
786         }
787         AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
788         if (chan->alertpipe[1] > -1) {
789                 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
790                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
791                                 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
792 #ifdef HAVE_ZAPTEL
793         } else if (chan->timingfd > -1) {
794                 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
795 #endif                          
796         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
797                 pthread_kill(chan->blocker, SIGURG);
798         }
799         ast_channel_unlock(chan);
800         return 0;
801 }
802
803 /*! \brief Queue a hangup frame for channel */
804 int ast_queue_hangup(struct ast_channel *chan)
805 {
806         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
807         /* Yeah, let's not change a lock-critical value without locking */
808         if (!ast_channel_trylock(chan)) {
809                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
810                 ast_channel_unlock(chan);
811         }
812         return ast_queue_frame(chan, &f);
813 }
814
815 /*! \brief Queue a control frame */
816 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
817 {
818         struct ast_frame f = { AST_FRAME_CONTROL, };
819
820         f.subclass = control;
821
822         return ast_queue_frame(chan, &f);
823 }
824
825 /*! \brief Queue a control frame with payload */
826 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
827                            const void *data, size_t datalen)
828 {
829         struct ast_frame f = { AST_FRAME_CONTROL, };
830
831         f.subclass = control;
832         f.data = (void *) data;
833         f.datalen = datalen;
834
835         return ast_queue_frame(chan, &f);
836 }
837
838 /*! \brief Set defer DTMF flag on channel */
839 int ast_channel_defer_dtmf(struct ast_channel *chan)
840 {
841         int pre = 0;
842
843         if (chan) {
844                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
845                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
846         }
847         return pre;
848 }
849
850 /*! \brief Unset defer DTMF flag on channel */
851 void ast_channel_undefer_dtmf(struct ast_channel *chan)
852 {
853         if (chan)
854                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
855 }
856
857 /*!
858  * \brief Helper function to find channels.
859  *
860  * It supports these modes:
861  *
862  * prev != NULL : get channel next in list after prev
863  * name != NULL : get channel with matching name
864  * name != NULL && namelen != 0 : get channel whose name starts with prefix
865  * exten != NULL : get channel whose exten or macroexten matches
866  * context != NULL && exten != NULL : get channel whose context or macrocontext
867  *
868  * It returns with the channel's lock held. If getting the individual lock fails,
869  * unlock and retry quickly up to 10 times, then give up.
870  *
871  * \note XXX Note that this code has cost O(N) because of the need to verify
872  * that the object is still on the global list.
873  *
874  * \note XXX also note that accessing fields (e.g. c->name in ast_log())
875  * can only be done with the lock held or someone could delete the
876  * object while we work on it. This causes some ugliness in the code.
877  * Note that removing the first ast_log() may be harmful, as it would
878  * shorten the retry period and possibly cause failures.
879  * We should definitely go for a better scheme that is deadlock-free.
880  */
881 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
882                                                const char *name, const int namelen,
883                                                const char *context, const char *exten)
884 {
885         const char *msg = prev ? "deadlock" : "initial deadlock";
886         int retries;
887         struct ast_channel *c;
888
889         for (retries = 0; retries < 10; retries++) {
890                 int done;
891                 AST_LIST_LOCK(&channels);
892                 AST_LIST_TRAVERSE(&channels, c, chan_list) {
893                         if (prev) {     /* look for next item */
894                                 if (c != prev)  /* not this one */
895                                         continue;
896                                 /* found, prepare to return c->next */
897                                 c = AST_LIST_NEXT(c, chan_list);
898                         }
899                         if (name) { /* want match by name */
900                                 if ((!namelen && strcasecmp(c->name, name)) ||
901                                     (namelen && strncasecmp(c->name, name, namelen)))
902                                         continue;       /* name match failed */
903                         } else if (exten) {
904                                 if (context && strcasecmp(c->context, context) &&
905                                     strcasecmp(c->macrocontext, context))
906                                         continue;       /* context match failed */
907                                 if (strcasecmp(c->exten, exten) &&
908                                     strcasecmp(c->macroexten, exten))
909                                         continue;       /* exten match failed */
910                         }
911                         /* if we get here, c points to the desired record */
912                         break;
913                 }
914                 /* exit if chan not found or mutex acquired successfully */
915                 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
916                 done = c == NULL || ast_channel_trylock(c) == 0;
917                 if (!done) {
918                         if (option_debug)
919                                 ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
920                 }
921                 AST_LIST_UNLOCK(&channels);
922                 if (done)
923                         return c;
924                 usleep(1);      /* give other threads a chance before retrying */
925         }
926         /*
927          * c is surely not null, but we don't have the lock so cannot
928          * access c->name
929          */
930         if (option_debug)
931                 ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n",
932                         c, retries);
933
934         return NULL;
935 }
936
937 /*! \brief Browse channels in use */
938 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
939 {
940         return channel_find_locked(prev, NULL, 0, NULL, NULL);
941 }
942
943 /*! \brief Get channel by name and lock it */
944 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
945 {
946         return channel_find_locked(NULL, name, 0, NULL, NULL);
947 }
948
949 /*! \brief Get channel by name prefix and lock it */
950 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
951 {
952         return channel_find_locked(NULL, name, namelen, NULL, NULL);
953 }
954
955 /*! \brief Get next channel by name prefix and lock it */
956 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
957                                                            const int namelen)
958 {
959         return channel_find_locked(chan, name, namelen, NULL, NULL);
960 }
961
962 /*! \brief Get channel by exten (and optionally context) and lock it */
963 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
964 {
965         return channel_find_locked(NULL, NULL, 0, context, exten);
966 }
967
968 /*! \brief Get next channel by exten (and optionally context) and lock it */
969 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
970                                                      const char *context)
971 {
972         return channel_find_locked(chan, NULL, 0, context, exten);
973 }
974
975 /*! \brief Wait, look for hangups and condition arg */
976 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
977 {
978         struct ast_frame *f;
979
980         while (ms > 0) {
981                 if (cond && ((*cond)(data) == 0))
982                         return 0;
983                 ms = ast_waitfor(chan, ms);
984                 if (ms < 0)
985                         return -1;
986                 if (ms > 0) {
987                         f = ast_read(chan);
988                         if (!f)
989                                 return -1;
990                         ast_frfree(f);
991                 }
992         }
993         return 0;
994 }
995
996 /*! \brief Wait, look for hangups */
997 int ast_safe_sleep(struct ast_channel *chan, int ms)
998 {
999         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1000 }
1001
1002 static void free_cid(struct ast_callerid *cid)
1003 {
1004         if (cid->cid_dnid)
1005                 free(cid->cid_dnid);
1006         if (cid->cid_num)
1007                 free(cid->cid_num);     
1008         if (cid->cid_name)
1009                 free(cid->cid_name);    
1010         if (cid->cid_ani)
1011                 free(cid->cid_ani);
1012         if (cid->cid_rdnis)
1013                 free(cid->cid_rdnis);
1014         cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1015 }
1016
1017 /*! \brief Free a channel structure */
1018 void ast_channel_free(struct ast_channel *chan)
1019 {
1020         int fd;
1021         struct ast_var_t *vardata;
1022         struct ast_frame *f;
1023         struct varshead *headp;
1024         struct ast_datastore *datastore = NULL;
1025         char name[AST_CHANNEL_NAME];
1026         
1027         headp=&chan->varshead;
1028         
1029         AST_LIST_LOCK(&channels);
1030         AST_LIST_REMOVE(&channels, chan, chan_list);
1031         /* Lock and unlock the channel just to be sure nobody
1032            has it locked still */
1033         ast_channel_lock(chan);
1034         ast_channel_unlock(chan);
1035         if (chan->tech_pvt) {
1036                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1037                 free(chan->tech_pvt);
1038         }
1039
1040         if (chan->sched)
1041                 sched_context_destroy(chan->sched);
1042
1043         ast_copy_string(name, chan->name, sizeof(name));
1044
1045         /* Stop monitoring */
1046         if (chan->monitor)
1047                 chan->monitor->stop( chan, 0 );
1048
1049         /* If there is native format music-on-hold state, free it */
1050         if (chan->music_state)
1051                 ast_moh_cleanup(chan);
1052
1053         /* if someone is whispering on the channel, stop them */
1054         if (chan->whisper)
1055                 ast_channel_whisper_stop(chan);
1056
1057         /* Free translators */
1058         if (chan->readtrans)
1059                 ast_translator_free_path(chan->readtrans);
1060         if (chan->writetrans)
1061                 ast_translator_free_path(chan->writetrans);
1062         if (chan->pbx)
1063                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1064         free_cid(&chan->cid);
1065         ast_mutex_destroy(&chan->lock);
1066         /* Close pipes if appropriate */
1067         if ((fd = chan->alertpipe[0]) > -1)
1068                 close(fd);
1069         if ((fd = chan->alertpipe[1]) > -1)
1070                 close(fd);
1071         if ((fd = chan->timingfd) > -1)
1072                 close(fd);
1073         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1074                 ast_frfree(f);
1075         
1076         /* Get rid of each of the data stores on the channel */
1077         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1078                 /* Free the data store */
1079                 ast_channel_datastore_free(datastore);
1080         AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1081
1082         /* loop over the variables list, freeing all data and deleting list items */
1083         /* no need to lock the list, as the channel is already locked */
1084         
1085         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1086                 ast_var_delete(vardata);
1087
1088         /* Destroy the jitterbuffer */
1089         ast_jb_destroy(chan);
1090
1091         ast_string_field_free_pools(chan);
1092         free(chan);
1093         AST_LIST_UNLOCK(&channels);
1094
1095         ast_device_state_changed_literal(name);
1096 }
1097
1098 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1099 {
1100         struct ast_datastore *datastore = NULL;
1101
1102         /* Make sure we at least have type so we can identify this */
1103         if (info == NULL) {
1104                 return NULL;
1105         }
1106
1107         /* Allocate memory for datastore and clear it */
1108         datastore = ast_calloc(1, sizeof(*datastore));
1109         if (datastore == NULL) {
1110                 return NULL;
1111         }
1112
1113         datastore->info = info;
1114
1115         datastore->uid = ast_strdup(uid);
1116
1117         return datastore;
1118 }
1119
1120 int ast_channel_datastore_free(struct ast_datastore *datastore)
1121 {
1122         int res = 0;
1123
1124         /* Using the destroy function (if present) destroy the data */
1125         if (datastore->info->destroy != NULL && datastore->data != NULL) {
1126                 datastore->info->destroy(datastore->data);
1127                 datastore->data = NULL;
1128         }
1129
1130         /* Free allocated UID memory */
1131         if (datastore->uid != NULL) {
1132                 free(datastore->uid);
1133                 datastore->uid = NULL;
1134         }
1135
1136         /* Finally free memory used by ourselves */
1137         free(datastore);
1138
1139         return res;
1140 }
1141
1142 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1143 {
1144         int res = 0;
1145
1146         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1147
1148         return res;
1149 }
1150
1151 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1152 {
1153         struct ast_datastore *datastore2 = NULL;
1154         int res = -1;
1155
1156         /* Find our position and remove ourselves */
1157         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1158                 if (datastore2 == datastore) {
1159                         AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1160                         res = 0;
1161                         break;
1162                 }
1163         }
1164         AST_LIST_TRAVERSE_SAFE_END
1165
1166         return res;
1167 }
1168
1169 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1170 {
1171         struct ast_datastore *datastore = NULL;
1172         
1173         if (info == NULL)
1174                 return NULL;
1175
1176         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1177                 if (datastore->info == info) {
1178                         if (uid != NULL && datastore->uid != NULL) {
1179                                 if (!strcasecmp(uid, datastore->uid)) {
1180                                         /* Matched by type AND uid */
1181                                         break;
1182                                 }
1183                         } else {
1184                                 /* Matched by type at least */
1185                                 break;
1186                         }
1187                 }
1188         }
1189         AST_LIST_TRAVERSE_SAFE_END
1190
1191         return datastore;
1192 }
1193
1194 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1195 {
1196         /* Link the owner channel to the spy */
1197         spy->chan = chan;
1198
1199         if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1200                 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1201                         spy->type, chan->name);
1202                 return -1;
1203         }
1204
1205         if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1206                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1207                         ast_getformatname(spy->read_queue.format));
1208                 return -1;
1209         }
1210
1211         if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1212                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1213                         ast_getformatname(spy->write_queue.format));
1214                 return -1;
1215         }
1216
1217         if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1218             ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1219              (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1220                 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1221                         ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1222                 return -1;
1223         }
1224
1225         if (!chan->spies) {
1226                 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1227                         return -1;
1228                 }
1229
1230                 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1231                 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1232         } else {
1233                 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1234         }
1235
1236         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1237                 ast_cond_init(&spy->trigger, NULL);
1238                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1239                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1240         }
1241
1242         if (option_debug)
1243                 ast_log(LOG_DEBUG, "Spy %s added to channel %s\n",
1244                         spy->type, chan->name);
1245
1246         return 0;
1247 }
1248
1249 /* Clean up a channel's spy information */
1250 static void spy_cleanup(struct ast_channel *chan)
1251 {
1252         if (!AST_LIST_EMPTY(&chan->spies->list))
1253                 return;
1254         if (chan->spies->read_translator.path)
1255                 ast_translator_free_path(chan->spies->read_translator.path);
1256         if (chan->spies->write_translator.path)
1257                 ast_translator_free_path(chan->spies->write_translator.path);
1258         free(chan->spies);
1259         chan->spies = NULL;
1260         return;
1261 }
1262
1263 /* Detach a spy from it's channel */
1264 static void spy_detach(struct ast_channel_spy *spy, struct ast_channel *chan)
1265 {
1266         ast_mutex_lock(&spy->lock);
1267
1268         /* We only need to poke them if they aren't already done */
1269         if (spy->status != CHANSPY_DONE) {
1270                 /* Indicate to the spy to stop */
1271                 spy->status = CHANSPY_STOP;
1272                 spy->chan = NULL;
1273                 /* Poke the spy if needed */
1274                 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1275                         ast_cond_signal(&spy->trigger);
1276         }
1277
1278         /* Print it out while we still have a lock so the structure can't go away (if signalled above) */
1279         if (option_debug)
1280                 ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n", spy->type, chan->name);
1281
1282         ast_mutex_unlock(&spy->lock);
1283
1284         return;
1285 }
1286
1287 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1288 {
1289         struct ast_channel_spy *spy = NULL;
1290         
1291         if (!chan->spies)
1292                 return;
1293
1294         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1295                 ast_mutex_lock(&spy->lock);
1296                 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1297                         ast_mutex_unlock(&spy->lock);
1298                         AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1299                         spy_detach(spy, chan);
1300                 } else
1301                         ast_mutex_unlock(&spy->lock);
1302         }
1303         AST_LIST_TRAVERSE_SAFE_END
1304         spy_cleanup(chan);
1305 }
1306
1307 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1308 {
1309         struct timeval tv;
1310         struct timespec ts;
1311
1312         tv = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1313         ts.tv_sec = tv.tv_sec;
1314         ts.tv_nsec = tv.tv_usec * 1000;
1315
1316         ast_cond_timedwait(&spy->trigger, &spy->lock, &ts);
1317 }
1318
1319 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1320 {
1321         if (!chan->spies)
1322                 return;
1323
1324         AST_LIST_REMOVE(&chan->spies->list, spy, list);
1325         spy_detach(spy, chan);
1326         spy_cleanup(chan);
1327 }
1328
1329 void ast_channel_spy_free(struct ast_channel_spy *spy)
1330 {
1331         struct ast_frame *f = NULL;
1332
1333         if (spy->status == CHANSPY_DONE)
1334                 return;
1335
1336         /* Switch status to done in case we get called twice */
1337         spy->status = CHANSPY_DONE;
1338
1339         /* Drop any frames in the queue */
1340         while ((f = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list)))
1341                 ast_frfree(f);
1342         while ((f = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list)))
1343                 ast_frfree(f);
1344
1345         /* Destroy the condition if in use */
1346         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1347                 ast_cond_destroy(&spy->trigger);
1348
1349         /* Destroy our mutex since it is no longer in use */
1350         ast_mutex_destroy(&spy->lock);
1351
1352         return;
1353 }
1354
1355 static void detach_spies(struct ast_channel *chan)
1356 {
1357         struct ast_channel_spy *spy = NULL;
1358
1359         if (!chan->spies)
1360                 return;
1361
1362         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1363                 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1364                 spy_detach(spy, chan);
1365         }
1366         AST_LIST_TRAVERSE_SAFE_END
1367
1368         spy_cleanup(chan);
1369 }
1370
1371 /*! \brief Softly hangup a channel, don't lock */
1372 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1373 {
1374         if (option_debug)
1375                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1376         /* Inform channel driver that we need to be hung up, if it cares */
1377         chan->_softhangup |= cause;
1378         ast_queue_frame(chan, &ast_null_frame);
1379         /* Interrupt any poll call or such */
1380         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1381                 pthread_kill(chan->blocker, SIGURG);
1382         return 0;
1383 }
1384
1385 /*! \brief Softly hangup a channel, lock */
1386 int ast_softhangup(struct ast_channel *chan, int cause)
1387 {
1388         int res;
1389         ast_channel_lock(chan);
1390         res = ast_softhangup_nolock(chan, cause);
1391         ast_channel_unlock(chan);
1392         return res;
1393 }
1394
1395 enum spy_direction {
1396         SPY_READ,
1397         SPY_WRITE,
1398 };
1399
1400 #define SPY_QUEUE_SAMPLE_LIMIT 4000                     /* half of one second */
1401
1402 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1403 {
1404         struct ast_frame *translated_frame = NULL;
1405         struct ast_channel_spy *spy;
1406         struct channel_spy_trans *trans;
1407
1408         trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1409
1410         AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1411                 struct ast_channel_spy_queue *queue;
1412                 struct ast_frame *duped_fr;
1413
1414                 ast_mutex_lock(&spy->lock);
1415
1416                 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1417
1418                 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1419                         if (!translated_frame) {
1420                                 if (trans->path && (trans->last_format != f->subclass)) {
1421                                         ast_translator_free_path(trans->path);
1422                                         trans->path = NULL;
1423                                 }
1424                                 if (!trans->path) {
1425                                         if (option_debug)
1426                                                 ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1427                                                         ast_getformatname(f->subclass), chan->name);
1428                                         if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1429                                                 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1430                                                         ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1431                                                 ast_mutex_unlock(&spy->lock);
1432                                                 continue;
1433                                         } else {
1434                                                 trans->last_format = f->subclass;
1435                                         }
1436                                 }
1437                                 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1438                                         ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1439                                                 ast_getformatname(AST_FORMAT_SLINEAR));
1440                                         ast_mutex_unlock(&spy->lock);
1441                                         break;
1442                                 }
1443                         }
1444                         duped_fr = ast_frdup(translated_frame);
1445                 } else if (f->subclass != queue->format) {
1446                         ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1447                                 spy->type, chan->name,
1448                                 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1449                         ast_mutex_unlock(&spy->lock);
1450                         continue;
1451                 } else
1452                         duped_fr = ast_frdup(f);
1453
1454                 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1455
1456                 queue->samples += f->samples;
1457
1458                 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1459                         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1460                                 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1461                                 case CHANSPY_TRIGGER_READ:
1462                                         if (dir == SPY_WRITE) {
1463                                                 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1464                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1465                                                 if (option_debug)
1466                                                         ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1467                                                                 spy->type, chan->name);
1468                                         }
1469                                         break;
1470                                 case CHANSPY_TRIGGER_WRITE:
1471                                         if (dir == SPY_READ) {
1472                                                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1473                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1474                                                 if (option_debug)
1475                                                         ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1476                                                                 spy->type, chan->name);
1477                                         }
1478                                         break;
1479                                 }
1480                                 if (option_debug)
1481                                         ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1482                                                 spy->type, chan->name);
1483                                 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1484                                 ast_cond_signal(&spy->trigger);
1485                         } else {
1486                                 if (option_debug)
1487                                         ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1488                                                 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1489                                 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1490                                         struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1491                                         queue->samples -= drop->samples;
1492                                         ast_frfree(drop);
1493                                 }
1494                         }
1495                 } else {
1496                         switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1497                         case CHANSPY_TRIGGER_READ:
1498                                 if (dir == SPY_READ)
1499                                         ast_cond_signal(&spy->trigger);
1500                                 break;
1501                         case CHANSPY_TRIGGER_WRITE:
1502                                 if (dir == SPY_WRITE)
1503                                         ast_cond_signal(&spy->trigger);
1504                                 break;
1505                         }
1506                 }
1507
1508                 ast_mutex_unlock(&spy->lock);
1509         }
1510
1511         if (translated_frame)
1512                 ast_frfree(translated_frame);
1513 }
1514
1515 static void free_translation(struct ast_channel *clone)
1516 {
1517         if (clone->writetrans)
1518                 ast_translator_free_path(clone->writetrans);
1519         if (clone->readtrans)
1520                 ast_translator_free_path(clone->readtrans);
1521         clone->writetrans = NULL;
1522         clone->readtrans = NULL;
1523         clone->rawwriteformat = clone->nativeformats;
1524         clone->rawreadformat = clone->nativeformats;
1525 }
1526
1527 /*! \brief Hangup a channel */
1528 int ast_hangup(struct ast_channel *chan)
1529 {
1530         int res = 0;
1531
1532         /* Don't actually hang up a channel that will masquerade as someone else, or
1533            if someone is going to masquerade as us */
1534         ast_channel_lock(chan);
1535
1536         detach_spies(chan);             /* get rid of spies */
1537
1538         if (chan->masq) {
1539                 if (ast_do_masquerade(chan))
1540                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1541         }
1542
1543         if (chan->masq) {
1544                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1545                 ast_channel_unlock(chan);
1546                 return 0;
1547         }
1548         /* If this channel is one which will be masqueraded into something,
1549            mark it as a zombie already, so we know to free it later */
1550         if (chan->masqr) {
1551                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1552                 ast_channel_unlock(chan);
1553                 return 0;
1554         }
1555         free_translation(chan);
1556         /* Close audio stream */
1557         if (chan->stream) {
1558                 ast_closestream(chan->stream);
1559                 chan->stream = NULL;
1560         }
1561         /* Close video stream */
1562         if (chan->vstream) {
1563                 ast_closestream(chan->vstream);
1564                 chan->vstream = NULL;
1565         }
1566         if (chan->sched) {
1567                 sched_context_destroy(chan->sched);
1568                 chan->sched = NULL;
1569         }
1570         
1571         if (chan->generatordata)        /* Clear any tone stuff remaining */
1572                 if (chan->generator && chan->generator->release)
1573                         chan->generator->release(chan, chan->generatordata);
1574         chan->generatordata = NULL;
1575         chan->generator = NULL;
1576         if (chan->cdr) {                /* End the CDR if it hasn't already */
1577                 ast_cdr_end(chan->cdr);
1578                 ast_cdr_detach(chan->cdr);      /* Post and Free the CDR */
1579                 chan->cdr = NULL;
1580         }
1581         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1582                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1583                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1584                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1585                 CRASH;
1586         }
1587         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1588                 if (option_debug)
1589                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1590                 if (chan->tech->hangup)
1591                         res = chan->tech->hangup(chan);
1592         } else {
1593                 if (option_debug)
1594                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1595         }
1596                         
1597         ast_channel_unlock(chan);
1598         manager_event(EVENT_FLAG_CALL, "Hangup",
1599                         "Channel: %s\r\n"
1600                         "Uniqueid: %s\r\n"
1601                         "Cause: %d\r\n"
1602                         "Cause-txt: %s\r\n",
1603                         chan->name,
1604                         chan->uniqueid,
1605                         chan->hangupcause,
1606                         ast_cause2str(chan->hangupcause)
1607                         );
1608         ast_channel_free(chan);
1609         return res;
1610 }
1611
1612 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1613 {
1614         int res = 0;
1615
1616         ast_channel_lock(chan);
1617
1618         /* You can't answer an outbound call */
1619         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1620                 ast_channel_unlock(chan);
1621                 return 0;
1622         }
1623
1624         /* Stop if we're a zombie or need a soft hangup */
1625         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1626                 ast_channel_unlock(chan);
1627                 return -1;
1628         }
1629
1630         switch(chan->_state) {
1631         case AST_STATE_RINGING:
1632         case AST_STATE_RING:
1633                 if (chan->tech->answer)
1634                         res = chan->tech->answer(chan);
1635                 ast_setstate(chan, AST_STATE_UP);
1636                 ast_cdr_answer(chan->cdr);
1637                 ast_channel_unlock(chan);
1638                 if (delay)
1639                         ast_safe_sleep(chan, delay);
1640                 return res;
1641                 break;
1642         case AST_STATE_UP:
1643                 ast_cdr_answer(chan->cdr);
1644                 break;
1645         default:
1646                 break;
1647         }
1648
1649         ast_channel_unlock(chan);
1650
1651         return res;
1652 }
1653
1654 int ast_answer(struct ast_channel *chan)
1655 {
1656         return __ast_answer(chan, 500);
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 ind_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                 if (f)
2659                         res = chan->tech->write(chan, f);
2660                 else
2661                         res = 0;
2662                 break;
2663         case AST_FRAME_NULL:
2664         case AST_FRAME_IAX:
2665                 /* Ignore these */
2666                 res = 0;
2667                 break;
2668         default:
2669                 /* At this point, fr is the incoming frame and f is NULL.  Channels do
2670                  * not expect to get NULL as a frame pointer and will segfault.  Hence,
2671                  * we output the original frame passed in. */
2672                 res = chan->tech->write(chan, fr);
2673                 break;
2674         }
2675
2676         if (f && f != fr)
2677                 ast_frfree(f);
2678         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2679         /* Consider a write failure to force a soft hangup */
2680         if (res < 0)
2681                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2682         else {
2683                 chan->fout = FRAMECOUNT_INC(chan->fout);
2684         }
2685 done:
2686         ast_channel_unlock(chan);
2687         return res;
2688 }
2689
2690 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2691                       struct ast_trans_pvt **trans, const int direction)
2692 {
2693         int native;
2694         int res;
2695         
2696         /* Make sure we only consider audio */
2697         fmt &= AST_FORMAT_AUDIO_MASK;
2698         
2699         native = chan->nativeformats;
2700         /* Find a translation path from the native format to one of the desired formats */
2701         if (!direction)
2702                 /* reading */
2703                 res = ast_translator_best_choice(&fmt, &native);
2704         else
2705                 /* writing */
2706                 res = ast_translator_best_choice(&native, &fmt);
2707
2708         if (res < 0) {
2709                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2710                         ast_getformatname(native), ast_getformatname(fmt));
2711                 return -1;
2712         }
2713         
2714         /* Now we have a good choice for both. */
2715         ast_channel_lock(chan);
2716
2717         if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2718                 /* the channel is already in these formats, so nothing to do */
2719                 ast_channel_unlock(chan);
2720                 return 0;
2721         }
2722
2723         *rawformat = native;
2724         /* User perspective is fmt */
2725         *format = fmt;
2726         /* Free any read translation we have right now */
2727         if (*trans)
2728                 ast_translator_free_path(*trans);
2729         /* Build a translation path from the raw format to the desired format */
2730         if (!direction)
2731                 /* reading */
2732                 *trans = ast_translator_build_path(*format, *rawformat);
2733         else
2734                 /* writing */
2735                 *trans = ast_translator_build_path(*rawformat, *format);
2736         ast_channel_unlock(chan);
2737         if (option_debug)
2738                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2739                         direction ? "write" : "read", ast_getformatname(fmt));
2740         return 0;
2741 }
2742
2743 int ast_set_read_format(struct ast_channel *chan, int fmt)
2744 {
2745         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2746                           &chan->readtrans, 0);
2747 }
2748
2749 int ast_set_write_format(struct ast_channel *chan, int fmt)
2750 {
2751         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2752                           &chan->writetrans, 1);
2753 }
2754
2755 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)
2756 {
2757         int dummy_outstate;
2758         int cause = 0;
2759         struct ast_channel *chan;
2760         int res = 0;
2761         
2762         if (outstate)
2763                 *outstate = 0;
2764         else
2765                 outstate = &dummy_outstate;     /* make outstate always a valid pointer */
2766
2767         chan = ast_request(type, format, data, &cause);
2768         if (!chan) {
2769                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2770                 /* compute error and return */
2771                 if (cause == AST_CAUSE_BUSY)
2772                         *outstate = AST_CONTROL_BUSY;
2773                 else if (cause == AST_CAUSE_CONGESTION)
2774                         *outstate = AST_CONTROL_CONGESTION;
2775                 return NULL;
2776         }
2777
2778         if (oh) {
2779                 if (oh->vars)   
2780                         ast_set_variables(chan, oh->vars);
2781                 /* XXX why is this necessary, for the parent_channel perhaps ? */
2782                 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2783                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2784                 if (oh->parent_channel)
2785                         ast_channel_inherit_variables(oh->parent_channel, chan);
2786                 if (oh->account)
2787                         ast_cdr_setaccount(chan, oh->account);  
2788         }
2789         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2790
2791         if (ast_call(chan, data, 0)) {  /* ast_call failed... */
2792                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2793         } else {
2794                 res = 1;        /* mark success in case chan->_state is already AST_STATE_UP */
2795                 while (timeout && chan->_state != AST_STATE_UP) {
2796                         struct ast_frame *f;
2797                         res = ast_waitfor(chan, timeout);
2798                         if (res <= 0) /* error, timeout, or done */
2799                                 break;
2800                         if (timeout > -1)
2801                                 timeout = res;
2802                         f = ast_read(chan);
2803                         if (!f) {
2804                                 *outstate = AST_CONTROL_HANGUP;
2805                                 res = 0;
2806                                 break;
2807                         }
2808                         if (f->frametype == AST_FRAME_CONTROL) {
2809                                 switch (f->subclass) {
2810                                 case AST_CONTROL_RINGING:       /* record but keep going */
2811                                         *outstate = f->subclass;
2812                                         break;
2813
2814                                 case AST_CONTROL_BUSY:
2815                                 case AST_CONTROL_CONGESTION:
2816                                 case AST_CONTROL_ANSWER:
2817                                         *outstate = f->subclass;
2818                                         timeout = 0;            /* trick to force exit from the while() */
2819                                         break;
2820
2821                                 /* Ignore these */
2822                                 case AST_CONTROL_PROGRESS:
2823                                 case AST_CONTROL_PROCEEDING:
2824                                 case AST_CONTROL_HOLD:
2825                                 case AST_CONTROL_UNHOLD:
2826                                 case AST_CONTROL_VIDUPDATE:
2827                                 case -1:                        /* Ignore -- just stopping indications */
2828                                         break;
2829
2830                                 default:
2831                                         ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2832                                 }
2833                         }
2834                         ast_frfree(f);
2835                 }
2836         }
2837
2838         /* Final fixups */
2839         if (oh) {
2840                 if (!ast_strlen_zero(oh->context))
2841                         ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2842                 if (!ast_strlen_zero(oh->exten))
2843                         ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2844                 if (oh->priority)       
2845                         chan->priority = oh->priority;
2846         }
2847         if (chan->_state == AST_STATE_UP)
2848                 *outstate = AST_CONTROL_ANSWER;
2849
2850         if (res <= 0) {
2851                 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2852                         ast_cdr_init(chan->cdr, chan);
2853                 if (chan->cdr) {
2854                         char tmp[256];
2855                         snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2856                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2857                         ast_cdr_update(chan);
2858                         ast_cdr_start(chan->cdr);
2859                         ast_cdr_end(chan->cdr);
2860                         /* If the cause wasn't handled properly */
2861                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2862                                 ast_cdr_failed(chan->cdr);
2863                 }
2864                 ast_hangup(chan);
2865                 chan = NULL;
2866         }
2867         return chan;
2868 }
2869
2870 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2871 {
2872         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2873 }
2874
2875 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2876 {
2877         struct chanlist *chan;
2878         struct ast_channel *c;
2879         int capabilities;
2880         int fmt;
2881         int res;
2882         int foo;
2883         int videoformat = format & AST_FORMAT_VIDEO_MASK;
2884
2885         if (!cause)
2886                 cause = &foo;
2887         *cause = AST_CAUSE_NOTDEFINED;
2888
2889         if (AST_LIST_LOCK(&channels)) {
2890                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2891                 return NULL;
2892         }
2893
2894         AST_LIST_TRAVERSE(&backends, chan, list) {
2895                 if (strcasecmp(type, chan->tech->type))
2896                         continue;
2897
2898                 capabilities = chan->tech->capabilities;
2899                 fmt = format & AST_FORMAT_AUDIO_MASK;
2900                 res = ast_translator_best_choice(&fmt, &capabilities);
2901                 if (res < 0) {
2902                         ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2903                         AST_LIST_UNLOCK(&channels);
2904                         return NULL;
2905                 }
2906                 AST_LIST_UNLOCK(&channels);
2907                 if (!chan->tech->requester)
2908                         return NULL;
2909                 
2910                 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
2911                         return NULL;
2912                 
2913                 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
2914                 return c;
2915         }
2916
2917         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2918         *cause = AST_CAUSE_NOSUCHDRIVER;
2919         AST_LIST_UNLOCK(&channels);
2920
2921         return NULL;
2922 }
2923
2924 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2925 {
2926         /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2927            If the remote end does not answer within the timeout, then do NOT hang up, but
2928            return anyway.  */
2929         int res = -1;
2930         /* Stop if we're a zombie or need a soft hangup */
2931         ast_channel_lock(chan);
2932         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2933                 if (chan->tech->call)
2934                         res = chan->tech->call(chan, addr, timeout);
2935                 ast_set_flag(chan, AST_FLAG_OUTGOING);
2936         }
2937         ast_channel_unlock(chan);
2938         return res;
2939 }
2940
2941 /*!
2942   \brief Transfer a call to dest, if the channel supports transfer
2943
2944   Called by:
2945     \arg app_transfer
2946     \arg the manager interface
2947 */
2948 int ast_transfer(struct ast_channel *chan, char *dest)
2949 {
2950         int res = -1;
2951
2952         /* Stop if we're a zombie or need a soft hangup */
2953         ast_channel_lock(chan);
2954         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2955                 if (chan->tech->transfer) {
2956                         res = chan->tech->transfer(chan, dest);
2957                         if (!res)
2958                                 res = 1;
2959                 } else
2960                         res = 0;
2961         }
2962         ast_channel_unlock(chan);
2963         return res;
2964 }
2965
2966 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2967 {
2968         return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
2969 }
2970
2971 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2972 {
2973         int pos = 0;    /* index in the buffer where we accumulate digits */
2974         int to = ftimeout;
2975
2976         /* Stop if we're a zombie or need a soft hangup */
2977         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2978                 return -1;
2979         if (!len)
2980                 return -1;
2981         for (;;) {
2982                 int d;
2983                 if (c->stream) {
2984                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2985                         ast_stopstream(c);
2986                         usleep(1000);
2987                         if (!d)
2988                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2989                 } else {
2990                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2991                 }
2992                 if (d < 0)
2993                         return -1;
2994                 if (d == 0) {
2995                         s[pos]='\0';
2996                         return 1;
2997                 }
2998                 if (d == 1) {
2999                         s[pos]='\0';
3000                         return 2;
3001                 }
3002                 if (!strchr(enders, d))
3003                         s[pos++] = d;
3004                 if (strchr(enders, d) || (pos >= len)) {
3005                         s[pos]='\0';
3006                         return 0;
3007                 }
3008                 to = timeout;
3009         }
3010         /* Never reached */
3011         return 0;
3012 }
3013
3014 int ast_channel_supports_html(struct ast_channel *chan)
3015 {
3016         return (chan->tech->send_html) ? 1 : 0;
3017 }
3018
3019 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3020 {
3021         if (chan->tech->send_html)
3022                 return chan->tech->send_html(chan, subclass, data, datalen);
3023         return -1;
3024 }
3025
3026 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3027 {
3028         return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3029 }
3030
3031 /*! \brief Set up translation from one channel to another */
3032 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
3033 {
3034         int src;
3035         int dst;
3036
3037         /* Set up translation from the 'from' channel to the 'to' channel */
3038         src = from->nativeformats;
3039         dst = to->nativeformats;
3040         if (ast_translator_best_choice(&dst, &src) < 0) {
3041                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", from->name, src, to->name, dst);
3042                 return -1;
3043         }
3044
3045         /* if the best path is not 'pass through', then
3046            transcoding is needed; if desired, force transcode path
3047            to use SLINEAR between channels, but only if there is
3048            no direct conversion available */
3049         if ((src != dst) && ast_opt_transcode_via_slin &&
3050             (ast_translate_path_steps(dst, src) != 1))
3051                 dst = AST_FORMAT_SLINEAR;
3052         if (ast_set_read_format(from, dst) < 0) {
3053                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", from->name, dst);
3054                 return -1;
3055         }
3056         if (ast_set_write_format(to, dst) < 0) {
3057                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", to->name, dst);
3058                 return -1;
3059         }
3060         return 0;
3061 }
3062
3063 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3064 {
3065         /* Some callers do not check return code, and we must try to set all call legs correctly */
3066         int rc = 0;
3067
3068         /* Set up translation from the chan to the peer */
3069         rc = ast_channel_make_compatible_helper(chan, peer);
3070
3071         if (rc < 0)
3072                 return rc;
3073
3074         /* Set up translation from the peer to the chan */
3075         rc = ast_channel_make_compatible_helper(peer, chan);
3076
3077         return rc;
3078 }
3079
3080 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3081 {
3082         int res = -1;
3083         struct ast_channel *final_orig = original, *final_clone = clone;
3084
3085         ast_channel_lock(original);
3086         while (ast_channel_trylock(clone)) {
3087                 ast_channel_unlock(original);
3088                 usleep(1);
3089                 ast_channel_lock(original);
3090         }
3091
3092         /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3093            and if so, we don't really want to masquerade it, but its proxy */
3094         if (original->_bridge && (original->_bridge != ast_bridged_channel(original)))