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