Merged revisions 43779 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_all(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                         ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
749                         ast_frfree(f);
750                         ast_channel_unlock(chan);
751                         return 0;
752                 }
753         }
754         AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
755         if (chan->alertpipe[1] > -1) {
756                 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
757                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
758                                 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
759 #ifdef HAVE_ZAPTEL
760         } else if (chan->timingfd > -1) {
761                 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
762 #endif                          
763         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
764                 pthread_kill(chan->blocker, SIGURG);
765         }
766         ast_channel_unlock(chan);
767         return 0;
768 }
769
770 /*! \brief Queue a hangup frame for channel */
771 int ast_queue_hangup(struct ast_channel *chan)
772 {
773         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
774         /* Yeah, let's not change a lock-critical value without locking */
775         if (!ast_channel_trylock(chan)) {
776                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
777                 ast_channel_unlock(chan);
778         }
779         return ast_queue_frame(chan, &f);
780 }
781
782 /*! \brief Queue a control frame */
783 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
784 {
785         struct ast_frame f = { AST_FRAME_CONTROL, };
786
787         f.subclass = control;
788
789         return ast_queue_frame(chan, &f);
790 }
791
792 /*! \brief Queue a control frame with payload */
793 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
794                            const void *data, size_t datalen)
795 {
796         struct ast_frame f = { AST_FRAME_CONTROL, };
797
798         f.subclass = control;
799         f.data = (void *) data;
800         f.datalen = datalen;
801
802         return ast_queue_frame(chan, &f);
803 }
804
805 /*! \brief Set defer DTMF flag on channel */
806 int ast_channel_defer_dtmf(struct ast_channel *chan)
807 {
808         int pre = 0;
809
810         if (chan) {
811                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
812                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
813         }
814         return pre;
815 }
816
817 /*! \brief Unset defer DTMF flag on channel */
818 void ast_channel_undefer_dtmf(struct ast_channel *chan)
819 {
820         if (chan)
821                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
822 }
823
824 /*!
825  * \brief Helper function to find channels.
826  *
827  * It supports these modes:
828  *
829  * prev != NULL : get channel next in list after prev
830  * name != NULL : get channel with matching name
831  * name != NULL && namelen != 0 : get channel whose name starts with prefix
832  * exten != NULL : get channel whose exten or macroexten matches
833  * context != NULL && exten != NULL : get channel whose context or macrocontext
834  *
835  * It returns with the channel's lock held. If getting the individual lock fails,
836  * unlock and retry quickly up to 10 times, then give up.
837  *
838  * \note XXX Note that this code has cost O(N) because of the need to verify
839  * that the object is still on the global list.
840  *
841  * \note XXX also note that accessing fields (e.g. c->name in ast_log())
842  * can only be done with the lock held or someone could delete the
843  * object while we work on it. This causes some ugliness in the code.
844  * Note that removing the first ast_log() may be harmful, as it would
845  * shorten the retry period and possibly cause failures.
846  * We should definitely go for a better scheme that is deadlock-free.
847  */
848 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
849                                                const char *name, const int namelen,
850                                                const char *context, const char *exten)
851 {
852         const char *msg = prev ? "deadlock" : "initial deadlock";
853         int retries;
854         struct ast_channel *c;
855
856         for (retries = 0; retries < 10; retries++) {
857                 int done;
858                 AST_LIST_LOCK(&channels);
859                 AST_LIST_TRAVERSE(&channels, c, chan_list) {
860                         if (prev) {     /* look for next item */
861                                 if (c != prev)  /* not this one */
862                                         continue;
863                                 /* found, prepare to return c->next */
864                                 c = AST_LIST_NEXT(c, chan_list);
865                         }
866                         if (name) { /* want match by name */
867                                 if ((!namelen && strcasecmp(c->name, name)) ||
868                                     (namelen && strncasecmp(c->name, name, namelen)))
869                                         continue;       /* name match failed */
870                         } else if (exten) {
871                                 if (context && strcasecmp(c->context, context) &&
872                                     strcasecmp(c->macrocontext, context))
873                                         continue;       /* context match failed */
874                                 if (strcasecmp(c->exten, exten) &&
875                                     strcasecmp(c->macroexten, exten))
876                                         continue;       /* exten match failed */
877                         }
878                         /* if we get here, c points to the desired record */
879                         break;
880                 }
881                 /* exit if chan not found or mutex acquired successfully */
882                 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
883                 done = c == NULL || ast_channel_trylock(c) == 0;
884                 if (!done)
885                         ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
886                 AST_LIST_UNLOCK(&channels);
887                 if (done)
888                         return c;
889                 usleep(1);      /* give other threads a chance before retrying */
890         }
891         /*
892          * c is surely not null, but we don't have the lock so cannot
893          * access c->name
894          */
895         ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n",
896                 c, retries);
897
898         return NULL;
899 }
900
901 /*! \brief Browse channels in use */
902 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
903 {
904         return channel_find_locked(prev, NULL, 0, NULL, NULL);
905 }
906
907 /*! \brief Get channel by name and lock it */
908 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
909 {
910         return channel_find_locked(NULL, name, 0, NULL, NULL);
911 }
912
913 /*! \brief Get channel by name prefix and lock it */
914 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
915 {
916         return channel_find_locked(NULL, name, namelen, NULL, NULL);
917 }
918
919 /*! \brief Get next channel by name prefix and lock it */
920 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
921                                                            const int namelen)
922 {
923         return channel_find_locked(chan, name, namelen, NULL, NULL);
924 }
925
926 /*! \brief Get channel by exten (and optionally context) and lock it */
927 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
928 {
929         return channel_find_locked(NULL, NULL, 0, context, exten);
930 }
931
932 /*! \brief Get next channel by exten (and optionally context) and lock it */
933 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
934                                                      const char *context)
935 {
936         return channel_find_locked(chan, NULL, 0, context, exten);
937 }
938
939 /*! \brief Wait, look for hangups and condition arg */
940 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
941 {
942         struct ast_frame *f;
943
944         while (ms > 0) {
945                 if (cond && ((*cond)(data) == 0))
946                         return 0;
947                 ms = ast_waitfor(chan, ms);
948                 if (ms < 0)
949                         return -1;
950                 if (ms > 0) {
951                         f = ast_read(chan);
952                         if (!f)
953                                 return -1;
954                         ast_frfree(f);
955                 }
956         }
957         return 0;
958 }
959
960 /*! \brief Wait, look for hangups */
961 int ast_safe_sleep(struct ast_channel *chan, int ms)
962 {
963         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
964 }
965
966 static void free_cid(struct ast_callerid *cid)
967 {
968         if (cid->cid_dnid)
969                 free(cid->cid_dnid);
970         if (cid->cid_num)
971                 free(cid->cid_num);     
972         if (cid->cid_name)
973                 free(cid->cid_name);    
974         if (cid->cid_ani)
975                 free(cid->cid_ani);
976         if (cid->cid_rdnis)
977                 free(cid->cid_rdnis);
978 }
979
980 /*! \brief Free a channel structure */
981 void ast_channel_free(struct ast_channel *chan)
982 {
983         int fd;
984         struct ast_var_t *vardata;
985         struct ast_frame *f;
986         struct varshead *headp;
987         struct ast_datastore *datastore = NULL;
988         char name[AST_CHANNEL_NAME];
989         
990         headp=&chan->varshead;
991         
992         AST_LIST_LOCK(&channels);
993         AST_LIST_REMOVE(&channels, chan, chan_list);
994         /* Lock and unlock the channel just to be sure nobody
995            has it locked still */
996         ast_channel_lock(chan);
997         ast_channel_unlock(chan);
998         if (chan->tech_pvt) {
999                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1000                 free(chan->tech_pvt);
1001         }
1002
1003         if (chan->sched)
1004                 sched_context_destroy(chan->sched);
1005
1006         ast_copy_string(name, chan->name, sizeof(name));
1007
1008         /* Stop monitoring */
1009         if (chan->monitor)
1010                 chan->monitor->stop( chan, 0 );
1011
1012         /* If there is native format music-on-hold state, free it */
1013         if (chan->music_state)
1014                 ast_moh_cleanup(chan);
1015
1016         /* if someone is whispering on the channel, stop them */
1017         if (chan->whisper)
1018                 ast_channel_whisper_stop(chan);
1019
1020         /* Free translators */
1021         if (chan->readtrans)
1022                 ast_translator_free_path(chan->readtrans);
1023         if (chan->writetrans)
1024                 ast_translator_free_path(chan->writetrans);
1025         if (chan->pbx)
1026                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1027         free_cid(&chan->cid);
1028         ast_mutex_destroy(&chan->lock);
1029         /* Close pipes if appropriate */
1030         if ((fd = chan->alertpipe[0]) > -1)
1031                 close(fd);
1032         if ((fd = chan->alertpipe[1]) > -1)
1033                 close(fd);
1034         if ((fd = chan->timingfd) > -1)
1035                 close(fd);
1036         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1037                 ast_frfree(f);
1038         
1039         /* Get rid of each of the data stores on the channel */
1040         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1041                 /* Free the data store */
1042                 ast_channel_datastore_free(datastore);
1043         AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1044
1045         /* loop over the variables list, freeing all data and deleting list items */
1046         /* no need to lock the list, as the channel is already locked */
1047         
1048         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1049                 ast_var_delete(vardata);
1050
1051         /* Destroy the jitterbuffer */
1052         ast_jb_destroy(chan);
1053
1054         ast_string_field_free_all(chan);
1055         free(chan);
1056         AST_LIST_UNLOCK(&channels);
1057
1058         ast_device_state_changed_literal(name);
1059 }
1060
1061 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1062 {
1063         struct ast_datastore *datastore = NULL;
1064
1065         /* Make sure we at least have type so we can identify this */
1066         if (info == NULL) {
1067                 return NULL;
1068         }
1069
1070         /* Allocate memory for datastore and clear it */
1071         datastore = ast_calloc(1, sizeof(*datastore));
1072         if (datastore == NULL) {
1073                 return NULL;
1074         }
1075
1076         datastore->info = info;
1077
1078         datastore->uid = ast_strdup(uid);
1079
1080         return datastore;
1081 }
1082
1083 int ast_channel_datastore_free(struct ast_datastore *datastore)
1084 {
1085         int res = 0;
1086
1087         /* Using the destroy function (if present) destroy the data */
1088         if (datastore->info->destroy != NULL && datastore->data != NULL) {
1089                 datastore->info->destroy(datastore->data);
1090                 datastore->data = NULL;
1091         }
1092
1093         /* Free allocated UID memory */
1094         if (datastore->uid != NULL) {
1095                 free(datastore->uid);
1096                 datastore->uid = NULL;
1097         }
1098
1099         /* Finally free memory used by ourselves */
1100         free(datastore);
1101
1102         return res;
1103 }
1104
1105 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1106 {
1107         int res = 0;
1108
1109         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1110
1111         return res;
1112 }
1113
1114 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1115 {
1116         struct ast_datastore *datastore2 = NULL;
1117         int res = -1;
1118
1119         /* Find our position and remove ourselves */
1120         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1121                 if (datastore2 == datastore) {
1122                         AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1123                         res = 0;
1124                         break;
1125                 }
1126         }
1127         AST_LIST_TRAVERSE_SAFE_END
1128
1129         return res;
1130 }
1131
1132 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1133 {
1134         struct ast_datastore *datastore = NULL;
1135         
1136         if (info == NULL)
1137                 return NULL;
1138
1139         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1140                 if (datastore->info == info) {
1141                         if (uid != NULL && datastore->uid != NULL) {
1142                                 if (!strcasecmp(uid, datastore->uid)) {
1143                                         /* Matched by type AND uid */
1144                                         break;
1145                                 }
1146                         } else {
1147                                 /* Matched by type at least */
1148                                 break;
1149                         }
1150                 }
1151         }
1152         AST_LIST_TRAVERSE_SAFE_END
1153
1154         return datastore;
1155 }
1156
1157 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1158 {
1159         /* Link the owner channel to the spy */
1160         spy->chan = chan;
1161
1162         if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1163                 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1164                         spy->type, chan->name);
1165                 return -1;
1166         }
1167
1168         if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1169                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1170                         ast_getformatname(spy->read_queue.format));
1171                 return -1;
1172         }
1173
1174         if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1175                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1176                         ast_getformatname(spy->write_queue.format));
1177                 return -1;
1178         }
1179
1180         if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1181             ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1182              (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1183                 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1184                         ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1185                 return -1;
1186         }
1187
1188         if (!chan->spies) {
1189                 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1190                         return -1;
1191                 }
1192
1193                 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1194                 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1195         } else {
1196                 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1197         }
1198
1199         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1200                 ast_cond_init(&spy->trigger, NULL);
1201                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1202                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1203         }
1204
1205         ast_log(LOG_DEBUG, "Spy %s added to channel %s\n",
1206                 spy->type, chan->name);
1207
1208         return 0;
1209 }
1210
1211 /* Clean up a channel's spy information */
1212 static void spy_cleanup(struct ast_channel *chan)
1213 {
1214         if (!AST_LIST_EMPTY(&chan->spies->list))
1215                 return;
1216         if (chan->spies->read_translator.path)
1217                 ast_translator_free_path(chan->spies->read_translator.path);
1218         if (chan->spies->write_translator.path)
1219                 ast_translator_free_path(chan->spies->write_translator.path);
1220         free(chan->spies);
1221         chan->spies = NULL;
1222         return;
1223 }
1224
1225 /* Detach a spy from it's channel */
1226 static void spy_detach(struct ast_channel_spy *spy, struct ast_channel *chan)
1227 {
1228         ast_mutex_lock(&spy->lock);
1229
1230         /* We only need to poke them if they aren't already done */
1231         if (spy->status != CHANSPY_DONE) {
1232                 /* Indicate to the spy to stop */
1233                 spy->status = CHANSPY_STOP;
1234                 spy->chan = NULL;
1235                 /* Poke the spy if needed */
1236                 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1237                         ast_cond_signal(&spy->trigger);
1238         }
1239
1240         /* Print it out while we still have a lock so the structure can't go away (if signalled above) */
1241         ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n", spy->type, chan->name);
1242
1243         ast_mutex_unlock(&spy->lock);
1244
1245         return;
1246 }
1247
1248 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1249 {
1250         struct ast_channel_spy *spy = NULL;
1251         
1252         if (!chan->spies)
1253                 return;
1254
1255         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1256                 ast_mutex_lock(&spy->lock);
1257                 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1258                         ast_mutex_unlock(&spy->lock);
1259                         AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1260                         spy_detach(spy, chan);
1261                 } else
1262                         ast_mutex_unlock(&spy->lock);
1263         }
1264         AST_LIST_TRAVERSE_SAFE_END
1265         spy_cleanup(chan);
1266 }
1267
1268 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1269 {
1270         struct timeval tv;
1271         struct timespec ts;
1272
1273         tv = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1274         ts.tv_sec = tv.tv_sec;
1275         ts.tv_nsec = tv.tv_usec * 1000;
1276
1277         ast_cond_timedwait(&spy->trigger, &spy->lock, &ts);
1278 }
1279
1280 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1281 {
1282         if (!chan->spies)
1283                 return;
1284
1285         AST_LIST_REMOVE(&chan->spies->list, spy, list);
1286         spy_detach(spy, chan);
1287         spy_cleanup(chan);
1288 }
1289
1290 void ast_channel_spy_free(struct ast_channel_spy *spy)
1291 {
1292         struct ast_frame *f = NULL;
1293
1294         if (spy->status == CHANSPY_DONE)
1295                 return;
1296
1297         /* Switch status to done in case we get called twice */
1298         spy->status = CHANSPY_DONE;
1299
1300         /* Drop any frames in the queue */
1301         while ((f = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list)))
1302                 ast_frfree(f);
1303         while ((f = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list)))
1304                 ast_frfree(f);
1305
1306         /* Destroy the condition if in use */
1307         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1308                 ast_cond_destroy(&spy->trigger);
1309
1310         /* Destroy our mutex since it is no longer in use */
1311         ast_mutex_destroy(&spy->lock);
1312
1313         return;
1314 }
1315
1316 static void detach_spies(struct ast_channel *chan)
1317 {
1318         struct ast_channel_spy *spy = NULL;
1319
1320         if (!chan->spies)
1321                 return;
1322
1323         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1324                 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1325                 spy_detach(spy, chan);
1326         }
1327         AST_LIST_TRAVERSE_SAFE_END
1328
1329         spy_cleanup(chan);
1330 }
1331
1332 /*! \brief Softly hangup a channel, don't lock */
1333 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1334 {
1335         if (option_debug)
1336                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1337         /* Inform channel driver that we need to be hung up, if it cares */
1338         chan->_softhangup |= cause;
1339         ast_queue_frame(chan, &ast_null_frame);
1340         /* Interrupt any poll call or such */
1341         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1342                 pthread_kill(chan->blocker, SIGURG);
1343         return 0;
1344 }
1345
1346 /*! \brief Softly hangup a channel, lock */
1347 int ast_softhangup(struct ast_channel *chan, int cause)
1348 {
1349         int res;
1350         ast_channel_lock(chan);
1351         res = ast_softhangup_nolock(chan, cause);
1352         ast_channel_unlock(chan);
1353         return res;
1354 }
1355
1356 enum spy_direction {
1357         SPY_READ,
1358         SPY_WRITE,
1359 };
1360
1361 #define SPY_QUEUE_SAMPLE_LIMIT 4000                     /* half of one second */
1362
1363 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1364 {
1365         struct ast_frame *translated_frame = NULL;
1366         struct ast_channel_spy *spy;
1367         struct channel_spy_trans *trans;
1368
1369         trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1370
1371         AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1372                 struct ast_channel_spy_queue *queue;
1373                 struct ast_frame *duped_fr;
1374
1375                 ast_mutex_lock(&spy->lock);
1376
1377                 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1378
1379                 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1380                         if (!translated_frame) {
1381                                 if (trans->path && (trans->last_format != f->subclass)) {
1382                                         ast_translator_free_path(trans->path);
1383                                         trans->path = NULL;
1384                                 }
1385                                 if (!trans->path) {
1386                                         ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1387                                                 ast_getformatname(f->subclass), chan->name);
1388                                         if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1389                                                 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1390                                                         ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1391                                                 ast_mutex_unlock(&spy->lock);
1392                                                 continue;
1393                                         } else {
1394                                                 trans->last_format = f->subclass;
1395                                         }
1396                                 }
1397                                 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1398                                         ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1399                                                 ast_getformatname(AST_FORMAT_SLINEAR));
1400                                         ast_mutex_unlock(&spy->lock);
1401                                         break;
1402                                 }
1403                         }
1404                         duped_fr = ast_frdup(translated_frame);
1405                 } else if (f->subclass != queue->format) {
1406                         ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1407                                 spy->type, chan->name,
1408                                 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1409                         ast_mutex_unlock(&spy->lock);
1410                         continue;
1411                 } else
1412                         duped_fr = ast_frdup(f);
1413
1414                 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1415
1416                 queue->samples += f->samples;
1417
1418                 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1419                         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1420                                 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1421                                 case CHANSPY_TRIGGER_READ:
1422                                         if (dir == SPY_WRITE) {
1423                                                 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1424                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1425                                                 if (option_debug)
1426                                                         ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1427                                                                 spy->type, chan->name);
1428                                         }
1429                                         break;
1430                                 case CHANSPY_TRIGGER_WRITE:
1431                                         if (dir == SPY_READ) {
1432                                                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1433                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1434                                                 if (option_debug)
1435                                                         ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1436                                                                 spy->type, chan->name);
1437                                         }
1438                                         break;
1439                                 }
1440                                 if (option_debug)
1441                                         ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1442                                                 spy->type, chan->name);
1443                                 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1444                                 ast_cond_signal(&spy->trigger);
1445                         } else {
1446                                 if (option_debug)
1447                                         ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1448                                                 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1449                                 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1450                                         struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1451                                         queue->samples -= drop->samples;
1452                                         ast_frfree(drop);
1453                                 }
1454                         }
1455                 } else {
1456                         switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1457                         case CHANSPY_TRIGGER_READ:
1458                                 if (dir == SPY_READ)
1459                                         ast_cond_signal(&spy->trigger);
1460                                 break;
1461                         case CHANSPY_TRIGGER_WRITE:
1462                                 if (dir == SPY_WRITE)
1463                                         ast_cond_signal(&spy->trigger);
1464                                 break;
1465                         }
1466                 }
1467
1468                 ast_mutex_unlock(&spy->lock);
1469         }
1470
1471         if (translated_frame)
1472                 ast_frfree(translated_frame);
1473 }
1474
1475 static void free_translation(struct ast_channel *clone)
1476 {
1477         if (clone->writetrans)
1478                 ast_translator_free_path(clone->writetrans);
1479         if (clone->readtrans)
1480                 ast_translator_free_path(clone->readtrans);
1481         clone->writetrans = NULL;
1482         clone->readtrans = NULL;
1483         clone->rawwriteformat = clone->nativeformats;
1484         clone->rawreadformat = clone->nativeformats;
1485 }
1486
1487 /*! \brief Hangup a channel */
1488 int ast_hangup(struct ast_channel *chan)
1489 {
1490         int res = 0;
1491
1492         /* Don't actually hang up a channel that will masquerade as someone else, or
1493            if someone is going to masquerade as us */
1494         ast_channel_lock(chan);
1495
1496         detach_spies(chan);             /* get rid of spies */
1497
1498         if (chan->masq) {
1499                 if (ast_do_masquerade(chan))
1500                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1501         }
1502
1503         if (chan->masq) {
1504                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1505                 ast_channel_unlock(chan);
1506                 return 0;
1507         }
1508         /* If this channel is one which will be masqueraded into something,
1509            mark it as a zombie already, so we know to free it later */
1510         if (chan->masqr) {
1511                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1512                 ast_channel_unlock(chan);
1513                 return 0;
1514         }
1515         free_translation(chan);
1516         /* Close audio stream */
1517         if (chan->stream) {
1518                 ast_closestream(chan->stream);
1519                 chan->stream = NULL;
1520         }
1521         /* Close video stream */
1522         if (chan->vstream) {
1523                 ast_closestream(chan->vstream);
1524                 chan->vstream = NULL;
1525         }
1526         if (chan->sched) {
1527                 sched_context_destroy(chan->sched);
1528                 chan->sched = NULL;
1529         }
1530         
1531         if (chan->generatordata)        /* Clear any tone stuff remaining */
1532                 chan->generator->release(chan, chan->generatordata);
1533         chan->generatordata = NULL;
1534         chan->generator = NULL;
1535         if (chan->cdr) {                /* End the CDR if it hasn't already */
1536                 ast_cdr_end(chan->cdr);
1537                 ast_cdr_detach(chan->cdr);      /* Post and Free the CDR */
1538                 chan->cdr = NULL;
1539         }
1540         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1541                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1542                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1543                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1544                 CRASH;
1545         }
1546         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1547                 if (option_debug)
1548                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1549                 if (chan->tech->hangup)
1550                         res = chan->tech->hangup(chan);
1551         } else {
1552                 if (option_debug)
1553                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1554         }
1555                         
1556         ast_channel_unlock(chan);
1557         manager_event(EVENT_FLAG_CALL, "Hangup",
1558                         "Channel: %s\r\n"
1559                         "Uniqueid: %s\r\n"
1560                         "Cause: %d\r\n"
1561                         "Cause-txt: %s\r\n",
1562                         chan->name,
1563                         chan->uniqueid,
1564                         chan->hangupcause,
1565                         ast_cause2str(chan->hangupcause)
1566                         );
1567         ast_channel_free(chan);
1568         return res;
1569 }
1570
1571 int ast_answer(struct ast_channel *chan)
1572 {
1573         int res = 0;
1574         ast_channel_lock(chan);
1575         /* You can't answer an outbound call */
1576         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1577                 ast_channel_unlock(chan);
1578                 return 0;
1579         }
1580         /* Stop if we're a zombie or need a soft hangup */
1581         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1582                 ast_channel_unlock(chan);
1583                 return -1;
1584         }
1585         switch(chan->_state) {
1586         case AST_STATE_RINGING:
1587         case AST_STATE_RING:
1588                 if (chan->tech->answer)
1589                         res = chan->tech->answer(chan);
1590                 ast_setstate(chan, AST_STATE_UP);
1591                 ast_cdr_answer(chan->cdr);
1592                 break;
1593         case AST_STATE_UP:
1594                 ast_cdr_answer(chan->cdr);
1595                 break;
1596         default:
1597                 break;
1598         }
1599         ast_channel_unlock(chan);
1600         return res;
1601 }
1602
1603 void ast_deactivate_generator(struct ast_channel *chan)
1604 {
1605         ast_channel_lock(chan);
1606         if (chan->generatordata) {
1607                 if (chan->generator && chan->generator->release)
1608                         chan->generator->release(chan, chan->generatordata);
1609                 chan->generatordata = NULL;
1610                 chan->generator = NULL;
1611                 chan->fds[AST_GENERATOR_FD] = -1;
1612                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1613                 ast_settimeout(chan, 0, NULL, NULL);
1614         }
1615         ast_channel_unlock(chan);
1616 }
1617
1618 static int generator_force(void *data)
1619 {
1620         /* Called if generator doesn't have data */
1621         void *tmp;
1622         int res;
1623         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1624         struct ast_channel *chan = data;
1625         tmp = chan->generatordata;
1626         chan->generatordata = NULL;
1627         generate = chan->generator->generate;
1628         res = generate(chan, tmp, 0, 160);
1629         chan->generatordata = tmp;
1630         if (res) {
1631                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1632                 ast_deactivate_generator(chan);
1633         }
1634         return 0;
1635 }
1636
1637 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1638 {
1639         int res = 0;
1640
1641         ast_channel_lock(chan);
1642
1643         if (chan->generatordata) {
1644                 if (chan->generator && chan->generator->release)
1645                         chan->generator->release(chan, chan->generatordata);
1646                 chan->generatordata = NULL;
1647         }
1648
1649         ast_prod(chan);
1650         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1651                 res = -1;
1652         }
1653         
1654         if (!res) {
1655                 ast_settimeout(chan, 160, generator_force, chan);
1656                 chan->generator = gen;
1657         }
1658
1659         ast_channel_unlock(chan);
1660
1661         return res;
1662 }
1663
1664 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1665 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1666 {
1667         int winner = -1;
1668         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1669         return winner;
1670 }
1671
1672 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1673 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1674         int *exception, int *outfd, int *ms)
1675 {
1676         struct timeval start = { 0 , 0 };
1677         struct pollfd *pfds;
1678         int res;
1679         long rms;
1680         int x, y, max;
1681         int sz;
1682         time_t now = 0;
1683         long whentohangup = 0, diff;
1684         struct ast_channel *winner = NULL;
1685         struct fdmap {
1686                 int chan;
1687                 int fdno;
1688         } *fdmap;
1689
1690         sz = n * AST_MAX_FDS + nfds;
1691         pfds = alloca(sizeof(*pfds) * sz);
1692         fdmap = alloca(sizeof(*fdmap) * sz);
1693
1694         if (outfd)
1695                 *outfd = -99999;
1696         if (exception)
1697                 *exception = 0;
1698         
1699         /* Perform any pending masquerades */
1700         for (x=0; x < n; x++) {
1701                 ast_channel_lock(c[x]);
1702                 if (c[x]->masq) {
1703                         if (ast_do_masquerade(c[x])) {
1704                                 ast_log(LOG_WARNING, "Masquerade failed\n");
1705                                 *ms = -1;
1706                                 ast_channel_unlock(c[x]);
1707                                 return NULL;
1708                         }
1709                 }
1710                 if (c[x]->whentohangup) {
1711                         if (!whentohangup)
1712                                 time(&now);
1713                         diff = c[x]->whentohangup - now;
1714                         if (diff < 1) {
1715                                 /* Should already be hungup */
1716                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1717                                 ast_channel_unlock(c[x]);
1718                                 return c[x];
1719                         }
1720                         if (!whentohangup || (diff < whentohangup))
1721                                 whentohangup = diff;
1722                 }
1723                 ast_channel_unlock(c[x]);
1724         }
1725         /* Wait full interval */
1726         rms = *ms;
1727         if (whentohangup) {
1728                 rms = whentohangup * 1000;              /* timeout in milliseconds */
1729                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1730                         rms =  *ms;
1731         }
1732         /*
1733          * Build the pollfd array, putting the channels' fds first,
1734          * followed by individual fds. Order is important because
1735          * individual fd's must have priority over channel fds.
1736          */
1737         max = 0;
1738         for (x=0; x<n; x++) {
1739                 for (y=0; y<AST_MAX_FDS; y++) {
1740                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1741                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1742                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1743                 }
1744                 CHECK_BLOCKING(c[x]);
1745         }
1746         /* Add the individual fds */
1747         for (x=0; x<nfds; x++) {
1748                 fdmap[max].chan = -1;
1749                 max += ast_add_fd(&pfds[max], fds[x]);
1750         }
1751
1752         if (*ms > 0)
1753                 start = ast_tvnow();
1754         
1755         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1756                 do {
1757                         int kbrms = rms;
1758                         if (kbrms > 600000)
1759                                 kbrms = 600000;
1760                         res = poll(pfds, max, kbrms);
1761                         if (!res)
1762                                 rms -= kbrms;
1763                 } while (!res && (rms > 0));
1764         } else {
1765                 res = poll(pfds, max, rms);
1766         }
1767         for (x=0; x<n; x++)
1768                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1769         if (res < 0) { /* Simulate a timeout if we were interrupted */
1770                 if (errno != EINTR)
1771                         *ms = -1;
1772                 return NULL;
1773         }
1774         if (whentohangup) {   /* if we have a timeout, check who expired */
1775                 time(&now);
1776                 for (x=0; x<n; x++) {
1777                         if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1778                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1779                                 if (winner == NULL)
1780                                         winner = c[x];
1781                         }
1782                 }
1783         }
1784         if (res == 0) { /* no fd ready, reset timeout and done */
1785                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1786                 return winner;
1787         }
1788         /*
1789          * Then check if any channel or fd has a pending event.
1790          * Remember to check channels first and fds last, as they
1791          * must have priority on setting 'winner'
1792          */
1793         for (x = 0; x < max; x++) {
1794                 res = pfds[x].revents;
1795                 if (res == 0)
1796                         continue;
1797                 if (fdmap[x].chan >= 0) {       /* this is a channel */
1798                         winner = c[fdmap[x].chan];      /* override previous winners */
1799                         if (res & POLLPRI)
1800                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1801                         else
1802                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1803                         winner->fdno = fdmap[x].fdno;
1804                 } else {                        /* this is an fd */
1805                         if (outfd)
1806                                 *outfd = pfds[x].fd;
1807                         if (exception)
1808                                 *exception = (res & POLLPRI) ? -1 : 0;
1809                         winner = NULL;
1810                 }
1811         }
1812         if (*ms > 0) {
1813                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1814                 if (*ms < 0)
1815                         *ms = 0;
1816         }
1817         return winner;
1818 }
1819
1820 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1821 {
1822         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1823 }
1824
1825 int ast_waitfor(struct ast_channel *c, int ms)
1826 {
1827         int oldms = ms; /* -1 if no timeout */
1828
1829         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1830         if ((ms < 0) && (oldms < 0))
1831                 ms = 0;
1832         return ms;
1833 }
1834
1835 /* XXX never to be called with ms = -1 */
1836 int ast_waitfordigit(struct ast_channel *c, int ms)
1837 {
1838         return ast_waitfordigit_full(c, ms, -1, -1);
1839 }
1840
1841 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1842 {
1843         int res = -1;
1844 #ifdef HAVE_ZAPTEL
1845         if (c->timingfd > -1) {
1846                 if (!func) {
1847                         samples = 0;
1848                         data = 0;
1849                 }
1850                 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1851                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1852                 c->timingfunc = func;
1853                 c->timingdata = data;
1854         }
1855 #endif  
1856         return res;
1857 }
1858
1859 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1860 {
1861
1862         /* Stop if we're a zombie or need a soft hangup */
1863         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1864                 return -1;
1865         /* Wait for a digit, no more than ms milliseconds total. */
1866         while (ms) {
1867                 struct ast_channel *rchan;
1868                 int outfd;
1869
1870                 errno = 0;
1871                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1872                 if (!rchan && outfd < 0 && ms) {
1873                         if (errno == 0 || errno == EINTR)
1874                                 continue;
1875                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1876                         return -1;
1877                 } else if (outfd > -1) {
1878                         /* The FD we were watching has something waiting */
1879                         return 1;
1880                 } else if (rchan) {
1881                         int res;
1882                         struct ast_frame *f = ast_read(c);
1883                         if (!f)
1884                                 return -1;
1885
1886                         switch(f->frametype) {
1887                         case AST_FRAME_DTMF:
1888                                 res = f->subclass;
1889                                 ast_frfree(f);
1890                                 return res;
1891                         case AST_FRAME_CONTROL:
1892                                 switch(f->subclass) {
1893                                 case AST_CONTROL_HANGUP:
1894                                         ast_frfree(f);
1895                                         return -1;
1896                                 case AST_CONTROL_RINGING:
1897                                 case AST_CONTROL_ANSWER:
1898                                         /* Unimportant */
1899                                         break;
1900                                 default:
1901                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1902                                         break;
1903                                 }
1904                                 break;
1905                         case AST_FRAME_VOICE:
1906                                 /* Write audio if appropriate */
1907                                 if (audiofd > -1)
1908                                         write(audiofd, f->data, f->datalen);
1909                         default:
1910                                 /* Ignore */
1911                                 break;
1912                         }
1913                         ast_frfree(f);
1914                 }
1915         }
1916         return 0; /* Time is up */
1917 }
1918
1919 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1920 {
1921         struct ast_frame *f = NULL;     /* the return value */
1922         int blah;
1923         int prestate;
1924
1925         /* this function is very long so make sure there is only one return
1926          * point at the end (there is only one exception to this).
1927          */
1928         ast_channel_lock(chan);
1929         if (chan->masq) {
1930                 if (ast_do_masquerade(chan))
1931                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1932                 else
1933                         f =  &ast_null_frame;
1934                 goto done;
1935         }
1936
1937         /* Stop if we're a zombie or need a soft hangup */
1938         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1939                 if (chan->generator)
1940                         ast_deactivate_generator(chan);
1941                 goto done;
1942         }
1943         prestate = chan->_state;
1944
1945         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
1946             !ast_strlen_zero(chan->dtmfq)) {
1947                 /* We have DTMF that has been deferred.  Return it now */
1948                 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
1949                 chan->dtmff.subclass = chan->dtmfq[0];
1950                 /* Drop first digit from the buffer */
1951                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1952                 f = &chan->dtmff;
1953                 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
1954                 chan->emulate_dtmf_digit = f->subclass;
1955                 chan->emulate_dtmf_samples = AST_DEFAULT_EMULATE_DTMF_SAMPLES;
1956                 goto done;
1957         }
1958         
1959         /* Read and ignore anything on the alertpipe, but read only
1960            one sizeof(blah) per frame that we send from it */
1961         if (chan->alertpipe[0] > -1)
1962                 read(chan->alertpipe[0], &blah, sizeof(blah));
1963
1964 #ifdef HAVE_ZAPTEL
1965         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1966                 int res;
1967
1968                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1969                 blah = -1;
1970                 /* IF we can't get event, assume it's an expired as-per the old interface */
1971                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1972                 if (res)
1973                         blah = ZT_EVENT_TIMER_EXPIRED;
1974
1975                 if (blah == ZT_EVENT_TIMER_PING) {
1976                         if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
1977                                 /* Acknowledge PONG unless we need it again */
1978                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1979                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1980                                 }
1981                         }
1982                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1983                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1984                         if (chan->timingfunc) {
1985                                 /* save a copy of func/data before unlocking the channel */
1986                                 int (*func)(void *) = chan->timingfunc;
1987                                 void *data = chan->timingdata;
1988                                 ast_channel_unlock(chan);
1989                                 func(data);
1990                         } else {
1991                                 blah = 0;
1992                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1993                                 chan->timingdata = NULL;
1994                                 ast_channel_unlock(chan);
1995                         }
1996                         /* cannot 'goto done' because the channel is already unlocked */
1997                         return &ast_null_frame;
1998                 } else
1999                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2000         } else
2001 #endif
2002         if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2003                 /* if the AST_GENERATOR_FD is set, call the generator with args
2004                  * set to -1 so it can do whatever it needs to.
2005                  */
2006                 void *tmp = chan->generatordata;
2007                 chan->generatordata = NULL;     /* reset to let ast_write get through */
2008                 chan->generator->generate(chan, tmp, -1, -1);
2009                 chan->generatordata = tmp;
2010                 f = &ast_null_frame;
2011                 goto done;
2012         }
2013
2014         /* Check for pending read queue */
2015         if (!AST_LIST_EMPTY(&chan->readq)) {
2016                 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2017                 /* Interpret hangup and return NULL */
2018                 /* XXX why not the same for frames from the channel ? */
2019                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2020                         ast_frfree(f);
2021                         f = NULL;
2022                 }
2023         } else {
2024                 chan->blocker = pthread_self();
2025                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2026                         if (chan->tech->exception)
2027                                 f = chan->tech->exception(chan);
2028                         else {
2029                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2030                                 f = &ast_null_frame;
2031                         }
2032                         /* Clear the exception flag */
2033                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2034                 } else if (chan->tech->read)
2035                         f = chan->tech->read(chan);
2036                 else
2037                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2038         }
2039
2040         if (f) {
2041                 /* if the channel driver returned more than one frame, stuff the excess
2042                    into the readq for the next ast_read call (note that we can safely assume
2043                    that the readq is empty, because otherwise we would not have called into
2044                    the channel driver and f would be only a single frame)
2045                 */
2046                 if (AST_LIST_NEXT(f, frame_list)) {
2047                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2048                         AST_LIST_NEXT(f, frame_list) = NULL;
2049                 }
2050
2051                 switch (f->frametype) {
2052                 case AST_FRAME_CONTROL:
2053                         if (f->subclass == AST_CONTROL_ANSWER) {
2054                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2055                                         ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
2056                                         ast_frfree(f);
2057                                         f = &ast_null_frame;
2058                                 } else if (prestate == AST_STATE_UP) {
2059                                         ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
2060                                         ast_frfree(f);
2061                                         f = &ast_null_frame;
2062                                 } else {
2063                                         /* Answer the CDR */
2064                                         ast_setstate(chan, AST_STATE_UP);
2065                                         ast_cdr_answer(chan->cdr);
2066                                 }
2067                         }
2068                         break;
2069                 case AST_FRAME_DTMF_END:
2070                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s\n", f->subclass, chan->name);
2071                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
2072                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2073                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2074                                 else
2075                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2076                                 ast_frfree(f);
2077                                 f = &ast_null_frame;
2078                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2079                                 f->frametype = AST_FRAME_DTMF_BEGIN;
2080                                 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2081                                 chan->emulate_dtmf_digit = f->subclass;
2082                                 if (f->samples)
2083                                         chan->emulate_dtmf_samples = f->samples;
2084                                 else
2085                                         chan->emulate_dtmf_samples = AST_DEFAULT_EMULATE_DTMF_SAMPLES;
2086                         } else 
2087                                 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2088                         break;
2089                 case AST_FRAME_DTMF_BEGIN:
2090                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2091                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF)) {
2092                                 ast_frfree(f);
2093                                 f = &ast_null_frame;
2094                         } else 
2095                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2096                         break;
2097                 case AST_FRAME_VOICE:
2098                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the samples
2099                          * first get to zero, because we want to make sure we pass at least one
2100                          * voice frame through before starting the next digit, to ensure a gap
2101                          * between DTMF digits. */
2102                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_samples) {
2103                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2104                                 chan->emulate_dtmf_digit = 0;
2105                         }
2106
2107                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2108                                 ast_frfree(f);
2109                                 f = &ast_null_frame;
2110                         } else if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2111                                 if (f->samples >= chan->emulate_dtmf_samples) {
2112                                         chan->emulate_dtmf_samples = 0;
2113                                         f->frametype = AST_FRAME_DTMF_END;
2114                                         f->subclass = chan->emulate_dtmf_digit;
2115                                 } else {
2116                                         chan->emulate_dtmf_samples -= f->samples;
2117                                         ast_frfree(f);
2118                                         f = &ast_null_frame;
2119                                 }
2120                         } else if (!(f->subclass & chan->nativeformats)) {
2121                                 /* This frame can't be from the current native formats -- drop it on the
2122                                    floor */
2123                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2124                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2125                                 ast_frfree(f);
2126                                 f = &ast_null_frame;
2127                         } else {
2128                                 if (chan->spies)
2129                                         queue_frame_to_spies(chan, f, SPY_READ);
2130                                 
2131                                 if (chan->monitor && chan->monitor->read_stream ) {
2132                                         /* XXX what does this do ? */
2133 #ifndef MONITOR_CONSTANT_DELAY
2134                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2135                                         if (jump >= 0) {
2136                                                 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2137                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2138                                                 chan->insmpl += jump + 4 * f->samples;
2139                                         } else
2140                                                 chan->insmpl+= f->samples;
2141 #else
2142                                         int jump = chan->outsmpl - chan->insmpl;
2143                                         if (jump - MONITOR_DELAY >= 0) {
2144                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2145                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2146                                                 chan->insmpl += jump;
2147                                         } else
2148                                                 chan->insmpl += f->samples;
2149 #endif
2150                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2151                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2152                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2153                                         }
2154                                 }
2155
2156                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2157                                         f = &ast_null_frame;
2158
2159                                 /* Run generator sitting on the line if timing device not available
2160                                 * and synchronous generation of outgoing frames is necessary       */
2161                                 if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2162                                         void *tmp = chan->generatordata;
2163                                         int res;
2164
2165                                         if (chan->timingfunc) {
2166                                                 if (option_debug > 1)
2167                                                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2168                                                 ast_settimeout(chan, 0, NULL, NULL);
2169                                         }
2170
2171                                         chan->generatordata = NULL;     /* reset, to let writes go through */
2172                                         res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2173                                         chan->generatordata = tmp;
2174                                         if (res) {
2175                                                 if (option_debug > 1)
2176                                                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2177                                                 ast_deactivate_generator(chan);
2178                                         }
2179
2180                                 } else if (f->frametype == AST_FRAME_CNG) {
2181                                         if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2182                                                 if (option_debug > 1)
2183                                                         ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2184                                                 ast_settimeout(chan, 160, generator_force, chan);
2185                                         }
2186                                 }
2187                         }
2188                 default:
2189                         /* Just pass it on! */
2190                         break;
2191                 }
2192         } else {
2193                 /* Make sure we always return NULL in the future */
2194                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2195                 if (chan->generator)
2196                         ast_deactivate_generator(chan);
2197                 /* End the CDR if appropriate */
2198                 if (chan->cdr)
2199                         ast_cdr_end(chan->cdr);
2200         }
2201
2202         /* High bit prints debugging */
2203         if (chan->fin & DEBUGCHAN_FLAG)
2204                 ast_frame_dump(chan->name, f, "<<");
2205         chan->fin = FRAMECOUNT_INC(chan->fin);
2206
2207 done:
2208         ast_channel_unlock(chan);
2209         return f;
2210 }
2211
2212 int ast_internal_timing_enabled(struct ast_channel *chan)
2213 {
2214         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2215         if (option_debug > 4)
2216                 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);
2217         return ret;
2218 }
2219
2220 struct ast_frame *ast_read(struct ast_channel *chan)
2221 {
2222         return __ast_read(chan, 0);
2223 }
2224
2225 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2226 {
2227         return __ast_read(chan, 1);
2228 }
2229
2230 int ast_indicate(struct ast_channel *chan, int condition)
2231 {
2232         return ast_indicate_data(chan, condition, NULL, 0);
2233 }
2234
2235 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2236 {
2237         int res = -1;
2238
2239         ast_channel_lock(chan);
2240         /* Stop if we're a zombie or need a soft hangup */
2241         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2242                 ast_channel_unlock(chan);
2243                 return -1;
2244         }
2245         if (chan->tech->indicate)
2246                 res = chan->tech->indicate(chan, condition, data, datalen);
2247         ast_channel_unlock(chan);
2248         if (!chan->tech->indicate || res) {
2249                 /*
2250                  * Device does not support (that) indication, lets fake
2251                  * it by doing our own tone generation. (PM2002)
2252                  */
2253                 if (condition < 0)
2254                         ast_playtones_stop(chan);
2255                 else {
2256                         const struct tone_zone_sound *ts = NULL;
2257                         switch (condition) {
2258                         case AST_CONTROL_RINGING:
2259                                 ts = ast_get_indication_tone(chan->zone, "ring");
2260                                 break;
2261                         case AST_CONTROL_BUSY:
2262                                 ts = ast_get_indication_tone(chan->zone, "busy");
2263                                 break;
2264                         case AST_CONTROL_CONGESTION:
2265                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2266                                 break;
2267                         }
2268                         if (ts && ts->data[0]) {
2269                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2270                                 ast_playtones_start(chan,0,ts->data, 1);
2271                                 res = 0;
2272                         } else if (condition == AST_CONTROL_PROGRESS) {
2273                                 /* ast_playtones_stop(chan); */
2274                         } else if (condition == AST_CONTROL_PROCEEDING) {
2275                                 /* Do nothing, really */
2276                         } else if (condition == AST_CONTROL_HOLD) {
2277                                 /* Do nothing.... */
2278                         } else if (condition == AST_CONTROL_UNHOLD) {
2279                                 /* Do nothing.... */
2280                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2281                                 /* Do nothing.... */
2282                         } else {
2283                                 /* not handled */
2284                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2285                                 res = -1;
2286                         }
2287                 }
2288         }
2289         return res;
2290 }
2291
2292 int ast_recvchar(struct ast_channel *chan, int timeout)
2293 {
2294         int c;
2295         char *buf = ast_recvtext(chan, timeout);
2296         if (buf == NULL)
2297                 return -1;      /* error or timeout */
2298         c = *(unsigned char *)buf;
2299         free(buf);
2300         return c;
2301 }
2302
2303 char *ast_recvtext(struct ast_channel *chan, int timeout)
2304 {
2305         int res, done = 0;
2306         char *buf = NULL;
2307         
2308         while (!done) {
2309                 struct ast_frame *f;
2310                 if (ast_check_hangup(chan))
2311                         break;
2312                 res = ast_waitfor(chan, timeout);
2313                 if (res <= 0) /* timeout or error */
2314                         break;
2315                 timeout = res;  /* update timeout */
2316                 f = ast_read(chan);
2317                 if (f == NULL)
2318                         break; /* no frame */
2319                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2320                         done = 1;       /* force a break */
2321                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2322                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2323                         done = 1;
2324                 }
2325                 ast_frfree(f);
2326         }
2327         return buf;
2328 }
2329
2330 int ast_sendtext(struct ast_channel *chan, const char *text)
2331 {
2332         int res = 0;
2333         /* Stop if we're a zombie or need a soft hangup */
2334         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2335                 return -1;
2336         CHECK_BLOCKING(chan);
2337         if (chan->tech->send_text)
2338                 res = chan->tech->send_text(chan, text);
2339         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2340         return res;
2341 }
2342
2343 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2344 {
2345         int res = -1;
2346
2347         if (chan->tech->send_digit_begin)
2348                 res = chan->tech->send_digit_begin(chan, digit);
2349
2350         if (res) {
2351                 /*
2352                  * Device does not support DTMF tones, lets fake
2353                  * it by doing our own generation. (PM2002)
2354                  */
2355                 static const char* dtmf_tones[] = {
2356                         "!941+1336/100,!0/100", /* 0 */
2357                         "!697+1209/100,!0/100", /* 1 */
2358                         "!697+1336/100,!0/100", /* 2 */
2359                         "!697+1477/100,!0/100", /* 3 */
2360                         "!770+1209/100,!0/100", /* 4 */
2361                         "!770+1336/100,!0/100", /* 5 */
2362                         "!770+1477/100,!0/100", /* 6 */
2363                         "!852+1209/100,!0/100", /* 7 */
2364                         "!852+1336/100,!0/100", /* 8 */
2365                         "!852+1477/100,!0/100", /* 9 */
2366                         "!697+1633/100,!0/100", /* A */
2367                         "!770+1633/100,!0/100", /* B */
2368                         "!852+1633/100,!0/100", /* C */
2369                         "!941+1633/100,!0/100", /* D */
2370                         "!941+1209/100,!0/100", /* * */
2371                         "!941+1477/100,!0/100" };       /* # */
2372                 if (digit >= '0' && digit <='9')
2373                         ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2374                 else if (digit >= 'A' && digit <= 'D')
2375                         ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2376                 else if (digit == '*')
2377                         ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2378                 else if (digit == '#')
2379                         ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2380                 else {
2381                         /* not handled */
2382                         ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2383                 }
2384         }
2385
2386         return 0;
2387 }
2388
2389 int ast_senddigit_end(struct ast_channel *chan, char digit)
2390 {
2391         int res = -1;
2392
2393         if (chan->tech->send_digit_end)
2394                 res = chan->tech->send_digit_end(chan, digit);
2395
2396         if (res && chan->generator)
2397                 ast_playtones_stop(chan);
2398         
2399         return 0;
2400 }
2401
2402 int ast_senddigit(struct ast_channel *chan, char digit)
2403 {
2404         ast_senddigit_begin(chan, digit);
2405         
2406         ast_safe_sleep(chan, 100); /* XXX 100ms ... probably should be configurable */
2407         
2408         return ast_senddigit_end(chan, digit);
2409 }
2410
2411 int ast_prod(struct ast_channel *chan)
2412 {
2413         struct ast_frame a = { AST_FRAME_VOICE };
2414         char nothing[128];
2415
2416         /* Send an empty audio frame to get things moving */
2417         if (chan->_state != AST_STATE_UP) {
2418                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2419                 a.subclass = chan->rawwriteformat;
2420                 a.data = nothing + AST_FRIENDLY_OFFSET;
2421                 a.src = "ast_prod";
2422                 if (ast_write(chan, &a))
2423                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2424         }
2425         return 0;
2426 }
2427
2428 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2429 {
2430         int res;
2431         if (!chan->tech->write_video)
2432                 return 0;
2433         res = ast_write(chan, fr);
2434         if (!res)
2435                 res = 1;
2436         return res;
2437 }
2438
2439 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2440 {
2441         int res = -1;
2442         struct ast_frame *f = NULL;
2443
2444         /* Stop if we're a zombie or need a soft hangup */
2445         ast_channel_lock(chan);
2446         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2447                 goto done;
2448
2449         /* Handle any pending masquerades */
2450         if (chan->masq && ast_do_masquerade(chan)) {
2451                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2452                 goto done;
2453         }
2454         if (chan->masqr) {
2455                 res = 0;        /* XXX explain, why 0 ? */
2456                 goto done;
2457         }
2458         if (chan->generatordata) {
2459                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2460                         ast_deactivate_generator(chan);
2461                 else {
2462                         res = 0;        /* XXX explain, why 0 ? */
2463                         goto done;
2464                 }
2465         }
2466         /* High bit prints debugging */
2467         if (chan->fout & DEBUGCHAN_FLAG)
2468                 ast_frame_dump(chan->name, fr, ">>");
2469         CHECK_BLOCKING(chan);
2470         switch(fr->frametype) {
2471         case AST_FRAME_CONTROL:
2472                 res = (chan->tech->indicate == NULL) ? 0 :
2473                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2474                 break;
2475         case AST_FRAME_DTMF_BEGIN:
2476                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2477                 ast_channel_unlock(chan);
2478                 res = ast_senddigit_begin(chan, fr->subclass);
2479                 ast_channel_lock(chan);
2480                 CHECK_BLOCKING(chan);
2481                 break;
2482         case AST_FRAME_DTMF_END:
2483                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2484                 ast_channel_unlock(chan);
2485                 res = ast_senddigit_end(chan, fr->subclass);
2486                 ast_channel_lock(chan);
2487                 CHECK_BLOCKING(chan);
2488                 break;
2489         case AST_FRAME_TEXT:
2490                 res = (chan->tech->send_text == NULL) ? 0 :
2491                         chan->tech->send_text(chan, (char *) fr->data);
2492                 break;
2493         case AST_FRAME_HTML:
2494                 res = (chan->tech->send_html == NULL) ? 0 :
2495                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2496                 break;
2497         case AST_FRAME_VIDEO:
2498                 /* XXX Handle translation of video codecs one day XXX */
2499                 res = (chan->tech->write_video == NULL) ? 0 :
2500                         chan->tech->write_video(chan, fr);
2501                 break;
2502         case AST_FRAME_MODEM:
2503                 res = (chan->tech->write == NULL) ? 0 :
2504                         chan->tech->write(chan, fr);
2505                 break;
2506         case AST_FRAME_VOICE:
2507                 if (chan->tech->write == NULL)
2508                         break;  /*! \todo XXX should return 0 maybe ? */
2509
2510                 /* If someone is whispering on this channel then we must ensure that we are always getting signed linear frames */
2511                 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2512                         if (fr->subclass == AST_FORMAT_SLINEAR)
2513                                 f = fr;
2514                         else {
2515                                 ast_mutex_lock(&chan->whisper->lock);
2516                                 if (chan->writeformat != AST_FORMAT_SLINEAR) {
2517                                         /* Rebuild the translation path and set our write format back to signed linear */
2518                                         chan->whisper->original_format = chan->writeformat;
2519                                         ast_set_write_format(chan, AST_FORMAT_SLINEAR);
2520                                         if (chan->whisper->path)
2521                                                 ast_translator_free_path(chan->whisper->path);
2522                                         chan->whisper->path = ast_translator_build_path(AST_FORMAT_SLINEAR, chan->whisper->original_format);
2523                                 }
2524                                 /* Translate frame using the above translation path */
2525                                 f = (chan->whisper->path) ? ast_translate(chan->whisper->path, fr, 0) : fr;
2526                                 ast_mutex_unlock(&chan->whisper->lock);
2527                         }
2528                 } else {
2529                         /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2530                         if (fr->subclass == chan->rawwriteformat)
2531                                 f = fr;
2532                         else
2533                                 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2534                 }
2535
2536                 /* If we have no frame of audio, then we have to bail out */
2537                 if (f == NULL) {
2538                         res = 0;
2539                         break;
2540                 }
2541
2542                 /* If spies are on the channel then queue the frame out to them */
2543                 if (chan->spies)
2544                         queue_frame_to_spies(chan, f, SPY_WRITE);
2545
2546                 /* If Monitor is running on this channel, then we have to write frames out there too */
2547                 if (chan->monitor && chan->monitor->write_stream) {
2548                         /* XXX must explain this code */
2549 #ifndef MONITOR_CONSTANT_DELAY
2550                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2551                         if (jump >= 0) {
2552                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2553                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2554                                 chan->outsmpl += jump + 4 * f->samples;
2555                         } else
2556                                 chan->outsmpl += f->samples;
2557 #else
2558                         int jump = chan->insmpl - chan->outsmpl;
2559                         if (jump - MONITOR_DELAY >= 0) {
2560                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2561                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2562                                 chan->outsmpl += jump;
2563                         } else
2564                                 chan->outsmpl += f->samples;
2565 #endif
2566                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2567                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2568                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2569                         }
2570                 }
2571
2572                 /* Finally the good part! Write this out to the channel */
2573                 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2574                         /* frame is assumed to be in SLINEAR, since that is
2575                            required for whisper mode */
2576                         ast_frame_adjust_volume(f, -2);
2577                         if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2578                                 short buf[f->samples];
2579                                 struct ast_frame whisper = {
2580                                         .frametype = AST_FRAME_VOICE,
2581                                         .subclass = AST_FORMAT_SLINEAR,
2582                                         .data = buf,
2583                                         .datalen = sizeof(buf),
2584                                         .samples = f->samples,
2585                                 };
2586                                 
2587                                 ast_mutex_lock(&chan->whisper->lock);
2588                                 if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2589                                         ast_frame_slinear_sum(f, &whisper);
2590                                 ast_mutex_unlock(&chan->whisper->lock);
2591                         }
2592                         /* and now put it through the regular translator */
2593                         f = (chan->writetrans) ? ast_translate(chan->writetrans, f, 0) : f;
2594                 }
2595                 
2596                 res = chan->tech->write(chan, f);
2597                 break;
2598         case AST_FRAME_NULL:
2599         case AST_FRAME_IAX:
2600                 /* Ignore these */
2601                 res = 0;
2602                 break;
2603         default:
2604                 res = chan->tech->write(chan, f);
2605                 break;
2606         }
2607
2608         if (f && f != fr)
2609                 ast_frfree(f);
2610         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2611         /* Consider a write failure to force a soft hangup */
2612         if (res < 0)
2613                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2614         else {
2615                 chan->fout = FRAMECOUNT_INC(chan->fout);
2616         }
2617 done:
2618         ast_channel_unlock(chan);
2619         return res;
2620 }
2621
2622 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2623                       struct ast_trans_pvt **trans, const int direction)
2624 {
2625         int native;
2626         int res;
2627         
2628         /* Make sure we only consider audio */
2629         fmt &= AST_FORMAT_AUDIO_MASK;
2630         
2631         native = chan->nativeformats;
2632         /* Find a translation path from the native format to one of the desired formats */
2633         if (!direction)
2634                 /* reading */
2635                 res = ast_translator_best_choice(&fmt, &native);
2636         else
2637                 /* writing */
2638                 res = ast_translator_best_choice(&native, &fmt);
2639
2640         if (res < 0) {
2641                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2642                         ast_getformatname(native), ast_getformatname(fmt));
2643                 return -1;
2644         }
2645         
2646         /* Now we have a good choice for both. */
2647         ast_channel_lock(chan);
2648
2649         if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2650                 /* the channel is already in these formats, so nothing to do */
2651                 ast_channel_unlock(chan);
2652                 return 0;
2653         }
2654
2655         *rawformat = native;
2656         /* User perspective is fmt */
2657         *format = fmt;
2658         /* Free any read translation we have right now */
2659         if (*trans)
2660                 ast_translator_free_path(*trans);
2661         /* Build a translation path from the raw format to the desired format */
2662         if (!direction)
2663                 /* reading */
2664                 *trans = ast_translator_build_path(*format, *rawformat);
2665         else
2666                 /* writing */
2667                 *trans = ast_translator_build_path(*rawformat, *format);
2668         ast_channel_unlock(chan);
2669         if (option_debug)
2670                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2671                         direction ? "write" : "read", ast_getformatname(fmt));
2672         return 0;
2673 }
2674
2675 int ast_set_read_format(struct ast_channel *chan, int fmt)
2676 {
2677         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2678                           &chan->readtrans, 0);
2679 }
2680
2681 int ast_set_write_format(struct ast_channel *chan, int fmt)
2682 {
2683         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2684                           &chan->writetrans, 1);
2685 }
2686
2687 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)
2688 {
2689         int dummy_outstate;
2690         int cause = 0;
2691         struct ast_channel *chan;
2692         int res = 0;
2693         
2694         if (outstate)
2695                 *outstate = 0;
2696         else
2697                 outstate = &dummy_outstate;     /* make outstate always a valid pointer */
2698
2699         chan = ast_request(type, format, data, &cause);
2700         if (!chan) {
2701                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2702                 /* compute error and return */
2703                 if (cause == AST_CAUSE_BUSY)
2704                         *outstate = AST_CONTROL_BUSY;
2705                 else if (cause == AST_CAUSE_CONGESTION)
2706                         *outstate = AST_CONTROL_CONGESTION;
2707                 return NULL;
2708         }
2709
2710         if (oh) {
2711                 if (oh->vars)   
2712                         ast_set_variables(chan, oh->vars);
2713                 /* XXX why is this necessary, for the parent_channel perhaps ? */
2714                 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2715                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2716                 if (oh->parent_channel)
2717                         ast_channel_inherit_variables(oh->parent_channel, chan);
2718                 if (oh->account)
2719                         ast_cdr_setaccount(chan, oh->account);  
2720         }
2721         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2722
2723         if (ast_call(chan, data, 0)) {  /* ast_call failed... */
2724                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2725         } else {
2726                 res = 1;        /* mark success in case chan->_state is already AST_STATE_UP */
2727                 while (timeout && chan->_state != AST_STATE_UP) {
2728                         struct ast_frame *f;
2729                         res = ast_waitfor(chan, timeout);
2730                         if (res <= 0) /* error, timeout, or done */
2731                                 break;
2732                         if (timeout > -1)
2733                                 timeout = res;
2734                         f = ast_read(chan);
2735                         if (!f) {
2736                                 *outstate = AST_CONTROL_HANGUP;
2737                                 res = 0;
2738                                 break;
2739                         }
2740                         if (f->frametype == AST_FRAME_CONTROL) {
2741                                 switch (f->subclass) {
2742                                 case AST_CONTROL_RINGING:       /* record but keep going */
2743                                         *outstate = f->subclass;
2744                                         break;
2745
2746                                 case AST_CONTROL_BUSY:
2747                                 case AST_CONTROL_CONGESTION:
2748                                 case AST_CONTROL_ANSWER:
2749                                         *outstate = f->subclass;
2750                                         timeout = 0;            /* trick to force exit from the while() */
2751                                         break;
2752
2753                                 /* Ignore these */
2754                                 case AST_CONTROL_PROGRESS:
2755                                 case AST_CONTROL_PROCEEDING:
2756                                 case AST_CONTROL_HOLD:
2757                                 case AST_CONTROL_UNHOLD:
2758                                 case AST_CONTROL_VIDUPDATE:
2759                                 case -1:                        /* Ignore -- just stopping indications */
2760                                         break;
2761
2762                                 default:
2763                                         ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2764                                 }
2765                         }
2766                         ast_frfree(f);
2767                 }
2768         }
2769
2770         /* Final fixups */
2771         if (oh) {
2772                 if (!ast_strlen_zero(oh->context))
2773                         ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2774                 if (!ast_strlen_zero(oh->exten))
2775                         ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2776                 if (oh->priority)       
2777                         chan->priority = oh->priority;
2778         }
2779         if (chan->_state == AST_STATE_UP)
2780                 *outstate = AST_CONTROL_ANSWER;
2781
2782         if (res <= 0) {
2783                 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2784                         ast_cdr_init(chan->cdr, chan);
2785                 if (chan->cdr) {
2786                         char tmp[256];
2787                         snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2788                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2789                         ast_cdr_update(chan);
2790                         ast_cdr_start(chan->cdr);
2791                         ast_cdr_end(chan->cdr);
2792                         /* If the cause wasn't handled properly */
2793                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2794                                 ast_cdr_failed(chan->cdr);
2795                 }
2796                 ast_hangup(chan);
2797                 chan = NULL;
2798         }
2799         return chan;
2800 }
2801
2802 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2803 {
2804         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2805 }
2806
2807 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2808 {
2809         struct chanlist *chan;
2810         struct ast_channel *c;
2811         int capabilities;
2812         int fmt;
2813         int res;
2814         int foo;
2815         int videoformat = format & AST_FORMAT_VIDEO_MASK;
2816
2817         if (!cause)
2818                 cause = &foo;
2819         *cause = AST_CAUSE_NOTDEFINED;
2820
2821         if (AST_LIST_LOCK(&channels)) {
2822                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2823                 return NULL;
2824         }
2825
2826         AST_LIST_TRAVERSE(&backends, chan, list) {
2827                 if (strcasecmp(type, chan->tech->type))
2828                         continue;
2829
2830                 capabilities = chan->tech->capabilities;
2831                 fmt = format & AST_FORMAT_AUDIO_MASK;
2832                 res = ast_translator_best_choice(&fmt, &capabilities);
2833                 if (res < 0) {
2834                         ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2835                         AST_LIST_UNLOCK(&channels);
2836                         return NULL;
2837                 }
2838                 AST_LIST_UNLOCK(&channels);
2839                 if (!chan->tech->requester)
2840                         return NULL;
2841                 
2842                 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
2843                         return NULL;
2844
2845                 if (c->_state == AST_STATE_DOWN) {
2846                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2847                                       "Channel: %s\r\n"
2848                                       "State: %s\r\n"
2849                                       "CallerID: %s\r\n"
2850                                       "CallerIDName: %s\r\n"
2851                                       "Uniqueid: %s\r\n",
2852                                       c->name, ast_state2str(c->_state),
2853                                       S_OR(c->cid.cid_num, "<unknown>"),
2854                                       S_OR(c->cid.cid_name, "<unknown>"),
2855                                       c->uniqueid);
2856                 }
2857                 return c;
2858         }
2859
2860         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2861         *cause = AST_CAUSE_NOSUCHDRIVER;
2862         AST_LIST_UNLOCK(&channels);
2863
2864         return NULL;
2865 }
2866
2867 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2868 {
2869         /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2870            If the remote end does not answer within the timeout, then do NOT hang up, but
2871            return anyway.  */
2872         int res = -1;
2873         /* Stop if we're a zombie or need a soft hangup */
2874         ast_channel_lock(chan);
2875         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2876                 if (chan->tech->call)
2877                         res = chan->tech->call(chan, addr, timeout);
2878                 ast_set_flag(chan, AST_FLAG_OUTGOING);
2879         }
2880         ast_channel_unlock(chan);
2881         return res;
2882 }
2883
2884 /*!
2885   \brief Transfer a call to dest, if the channel supports transfer
2886
2887   Called by:
2888     \arg app_transfer
2889     \arg the manager interface
2890 */
2891 int ast_transfer(struct ast_channel *chan, char *dest)
2892 {
2893         int res = -1;
2894
2895         /* Stop if we're a zombie or need a soft hangup */
2896         ast_channel_lock(chan);
2897         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2898                 if (chan->tech->transfer) {
2899                         res = chan->tech->transfer(chan, dest);
2900                         if (!res)
2901                                 res = 1;
2902                 } else
2903                         res = 0;
2904         }
2905         ast_channel_unlock(chan);
2906         return res;
2907 }
2908
2909 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2910 {
2911         return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
2912 }
2913
2914 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2915 {
2916         int pos = 0;    /* index in the buffer where we accumulate digits */
2917         int to = ftimeout;
2918
2919         /* Stop if we're a zombie or need a soft hangup */
2920         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2921                 return -1;
2922         if (!len)
2923                 return -1;
2924         for (;;) {
2925                 int d;
2926                 if (c->stream) {
2927                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2928                         ast_stopstream(c);
2929                         usleep(1000);
2930                         if (!d)
2931                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2932                 } else {
2933                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2934                 }
2935                 if (d < 0)
2936                         return -1;
2937                 if (d == 0) {
2938                         s[pos]='\0';
2939                         return 1;
2940                 }
2941                 if (d == 1) {
2942                         s[pos]='\0';
2943                         return 2;
2944                 }
2945                 if (!strchr(enders, d))
2946                         s[pos++] = d;
2947                 if (strchr(enders, d) || (pos >= len)) {
2948                         s[pos]='\0';
2949                         return 0;
2950                 }
2951                 to = timeout;
2952         }
2953         /* Never reached */
2954         return 0;
2955 }
2956
2957 int ast_channel_supports_html(struct ast_channel *chan)
2958 {
2959         return (chan->tech->send_html) ? 1 : 0;
2960 }
2961
2962 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2963 {
2964         if (chan->tech->send_html)
2965                 return chan->tech->send_html(chan, subclass, data, datalen);
2966         return -1;
2967 }
2968
2969 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2970 {
2971         return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
2972 }
2973
2974 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2975 {
2976         int src;
2977         int dst;
2978
2979         /* Set up translation from the chan to the peer */
2980         src = chan->nativeformats;
2981         dst = peer->nativeformats;
2982         if (ast_translator_best_choice(&dst, &src) < 0) {
2983                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2984                 return -1;
2985         }
2986
2987         /* if the best path is not 'pass through', then
2988            transcoding is needed; if desired, force transcode path
2989            to use SLINEAR between channels, but only if there is
2990            no direct conversion available */
2991         if ((src != dst) && ast_opt_transcode_via_slin &&
2992             (ast_translate_path_steps(dst, src) != 1))
2993                 dst = AST_FORMAT_SLINEAR;
2994         if (ast_set_read_format(chan, dst) < 0) {
2995                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2996                 return -1;
2997         }
2998         if (ast_set_write_format(peer, dst) < 0) {
2999                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
3000                 return -1;
3001         }
3002
3003         /* Set up translation from the peer to the chan */
3004         src = peer->nativeformats;
3005         dst = chan->nativeformats;
3006         if (ast_translator_best_choice(&dst, &src) < 0) {
3007                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
3008                 return -1;
3009         }
3010
3011         /* if the best path is not 'pass through', then
3012            transcoding is needed; if desired, force transcode path
3013            to use SLINEAR between channels, but only if there is
3014            no direct conversion available */
3015         if ((src != dst) && ast_opt_transcode_via_slin &&
3016             (ast_translate_path_steps(dst, src) != 1))
3017                 dst = AST_FORMAT_SLINEAR;
3018         if (ast_set_read_format(peer, dst) < 0) {
3019                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
3020                 return -1;
3021         }
3022         if (ast_set_write_format(chan, dst) < 0) {
3023                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
3024                 return -1;
3025         }
3026         return 0;
3027 }
3028
3029 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3030 {
3031         int res = -1;
3032         struct ast_channel *final_orig = original, *final_clone = clone;
3033
3034         ast_channel_lock(original);
3035         while (ast_channel_trylock(clone)) {
3036                 ast_channel_unlock(original);
3037                 usleep(1);
3038                 ast_channel_lock(original);
3039         }
3040
3041         /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3042            and if so, we don't really want to masquerade it, but its proxy */
3043         if (original->_bridge && (original->_bridge != ast_bridged_channel(original)))
3044                 final_orig = original->_bridge;
3045
3046         if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)))
3047                 final_clone = clone->_bridge;
3048
3049         if ((final_orig != original) || (final_clone != clone)) {
3050                 ast_channel_lock(final_orig);
3051                 while (ast_channel_trylock(final_clone)) {
3052                         ast_channel_unlock(final_orig);
3053                         usleep(1);
3054                         ast_channel_lock(final_orig);
3055                 }
3056                 ast_channel_unlock(clone);
3057                 ast_channel_unlock(original);
3058                 original = final_orig;
3059                 clone = final_clone;
3060         }
3061
3062         if (original == clone) {
3063                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3064                 ast_channel_unlock(clone);
3065                 ast_channel_unlock(original);
3066                 return -1;
3067         }
3068
3069         ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
3070                 clone->name, original->name);
3071         if (original->masq) {
3072                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3073                         original->masq->name, original->name);
3074         } else if (clone->masqr) {
3075                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3076                         clone->name, clone->masqr->name);
3077         } else {
3078                 original->masq = clone;
3079                 clone->masqr = original;
3080                 ast_queue_frame(original, &ast_null_frame);
3081                 ast_queue_frame(clone, &ast_null_frame);
3082                 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3083                 res = 0;
3084         }
3085
3086         ast_channel_unlock(clone);
3087         ast_channel_unlock(original);
3088
3089         return res;
3090 }
3091
3092 void ast_change_name(struct ast_channel *chan, char *newname)
3093 {
3094         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3095         ast_string_field_set(chan, name, newname);
3096 }
3097
3098 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3099 {
3100         struct ast_var_t *current, *newvar;
3101         const char *varname;
3102
3103         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3104                 int vartype = 0;
3105
3106                 varname = ast_var_full_name(current);
3107                 if (!varname)
3108                         continue;
3109
3110                 if (varname[0] == '_') {
3111                         vartype = 1;
3112                         if (varname[1] == '_')
3113                                 vartype = 2;
3114                 }
3115
3116                 switch (vartype) {
3117                 case 1:
3118                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
3119                         if (newvar) {
3120                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3121                                 if (option_debug)
3122                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3123                         }
3124                         break;
3125                 case 2:
3126                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
3127                         if (newvar) {
3128                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3129                                 if (option_debug)
3130                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3131                         }
3132                         break;
3133                 default:
3134                         if (option_debug)
3135                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
3136                         break;
3137                 }
3138         }
3139 }
3140
3141 /*!
3142   \brief Clone channel variables from 'clone' channel into 'original' channel
3143
3144   All variables except those related to app_groupcount are cloned.
3145   Variables are actually _removed_ from 'clone' channel, presumably
3146   because it will subsequently be destroyed.
3147
3148   \note Assumes locks will be in place on both channels when called.
3149 */
3150 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3151 {
3152         struct ast_var_t *varptr;
3153
3154         /* we need to remove all app_groupcount related variables from the original
3155            channel before merging in the clone's variables; any groups assigned to the
3156            original channel should be released, only those assigned to the clone
3157            should remain
3158         */
3159
3160         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
3161                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
3162                         AST_LIST_REMOVE_CURRENT(&original->varshead, entries);
3163                         ast_var_delete(varptr);
3164                 }
3165         }
3166         AST_LIST_TRAVERSE_SAFE_END;
3167
3168         /* Append variables from clone channel into original channel */
3169         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
3170         if (AST_LIST_FIRST(&clone->varshead))
3171                 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3172 }
3173
3174 /*!
3175   \brief Masquerade a channel
3176
3177   \note Assumes channel will be locked when called
3178 */
3179 int ast_do_masquerade(struct ast_channel *original)
3180 {
3181         int x,i;
3182         int res=0;
3183         int origstate;
3184         struct ast_frame *cur;
3185         const struct ast_channel_tech *t;
3186         void *t_pvt;
3187         struct ast_callerid tmpcid;
3188         struct ast_channel *clone = original->masq;
3189         struct ast_channel_spy_list *spy_list = NULL;
3190         struct ast_channel_spy *spy = NULL;
3191         int rformat = original->readformat;
3192         int wformat = original->writeformat;
3193         char newn[100];
3194         char orig[100];
3195         char masqn[100];
3196         char zombn[100];
3197
3198         if (option_debug > 3)
3199                 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3200                         clone->name, clone->_state, original->name, original->_state);
3201
3202         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
3203            the clone channel into the original channel.  Start by killing off the original
3204            channel's backend.   I'm not sure we're going to keep this function, because
3205            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3206
3207         /* We need the clone's lock, too */
3208         ast_channel_lock(clone);
3209
3210         if (option_debug > 1)
3211                 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3212
3213         /* Having remembered the original read/write formats, we turn off any translation on either
3214            one */
3215         free_translation(clone);
3216         free_translation(original);
3217
3218
3219         /* Unlink the masquerade */
3220         original->masq = NULL;
3221         clone->masqr = NULL;
3222         
3223         /* Save the original name */
3224         ast_copy_string(orig, original->name, sizeof(orig));
3225         /* Save the new name */
3226         ast_copy_string(newn, clone->name, sizeof(newn));
3227         /* Create the masq name */
3228         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3229                 
3230         /* Copy the name from the clone channel */
3231         ast_string_field_set(original, name, newn);
3232
3233         /* Mangle the name of the clone channel */
3234         ast_string_field_set(clone, name, masqn);
3235         
3236         /* Notify any managers of the change, first the masq then the other */
3237         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3238         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3239
3240         /* Swap the technologies */     
3241         t = original->tech;
3242         original->tech = clone->tech;
3243         clone->tech = t;
3244
3245         t_pvt = original->tech_pvt;
3246         original->tech_pvt = clone->tech_pvt;
3247         clone->tech_pvt = t_pvt;
3248
3249         /* Swap the readq's */
3250         cur = AST_LIST_FIRST(&original->readq);
3251         AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3252         AST_LIST_HEAD_SET_NOLOCK(&clone->readq, cur);
3253
3254         /* Swap the alertpipes */
3255         for (i = 0; i < 2; i++) {
3256                 x = original->alertpipe[i];
3257                 original->alertpipe[i] = clone->alertpipe[i];
3258                 clone->alertpipe[i] = x;
3259         }
3260
3261         /* Swap the raw formats */
3262         x = original->rawreadformat;
3263         original->rawreadformat = clone->rawreadformat;
3264         clone->rawreadformat = x;
3265         x = original->rawwriteformat;
3266         original->rawwriteformat = clone->rawwriteformat;
3267         clone->rawwriteformat = x;
3268
3269         /* Swap the spies */
3270         spy_list = original->spies;
3271         original->spies = clone->spies;
3272         clone->spies = spy_list;
3273
3274         /* Update channel on respective spy lists if present */
3275         if (original->spies) {
3276                 AST_LIST_TRAVERSE(&original->spies->list, spy, list) {
3277                         ast_mutex_lock(&spy->lock);
3278                         spy->chan = original;
3279                         ast_mutex_unlock(&spy->lock);
3280                 }
3281         }
3282         if (clone->spies) {
3283                 AST_LIST_TRAVERSE(&clone->spies->list, spy, list) {
3284                         ast_mutex_lock(&spy->lock);
3285                         spy->chan = clone;
3286                         ast_mutex_unlock(&spy->lock);
3287                 }
3288         }
3289
3290         /* Save any pending frames on both sides.  Start by counting
3291          * how many we're going to need... */
3292         x = 0;
3293         if (original->alertpipe[1] > -1) {
3294                 AST_LIST_TRAVERSE(&clone->readq, cur, frame_list)
3295                         x++;
3296         }
3297
3298         /* If we had any, prepend them to the ones already in the queue, and 
3299          * load up the alertpipe */
3300         if (AST_LIST_FIRST(&clone->readq)) {
3301                 AST_LIST_INSERT_TAIL(&clone->readq, AST_LIST_FIRST(&original->readq), frame_list);
3302                 AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3303                 AST_LIST_HEAD_SET_NOLOCK(&clone->readq, NULL);
3304                 for (i = 0; i < x; i++)
3305                         write(original->alertpipe[1], &x, sizeof(x));
3306         }
3307         
3308         clone->_softhangup = AST_SOFTHANGUP_DEV;
3309
3310
3311         /* And of course, so does our current state.  Note we need not
3312            call ast_setstate since the event manager doesn't really consider
3313            these separate.  We do this early so that the clone has the proper
3314            state of the original channel. */
3315         origstate = original->_state;
3316         original->_state = clone->_state;
3317         clone->_state = origstate;
3318
3319         if (clone->tech->fixup){
3320                 res = clone->tech->fixup(original, clone);
3321                 if (res)
3322                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3323         }
3324
3325         /* Start by disconnecting the original's physical side */
3326         if (clone->tech->hangup)
3327                 res = clone->tech->hangup(clone);
3328         if (res) {
3329                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
3330                 ast_channel_unlock(clone);
3331                 return -1;
3332         }
3333         
3334         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3335         /* Mangle the name of the clone channel */
3336         ast_string_field_set(clone, name, zombn);
3337         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3338
3339         /* Update the type. */
3340         t_pvt = original->monitor;
3341         original->monitor = clone->monitor;
3342         clone->monitor = t_pvt;
3343         
3344         /* Keep the same language.  */
3345         ast_string_field_set(original, language, clone->language);
3346         /* Copy the FD's other than the generator fd */
3347         for (x = 0; x < AST_MAX_FDS; x++) {
3348                 if (x != AST_GENERATOR_FD)
3349                         original->fds[x] = clone->fds[x];
3350         }
3351
3352         /* move any whisperer over */
3353         ast_channel_whisper_stop(original);
3354         if (ast_test_flag(clone, AST_FLAG_WHISPER)) {
3355                 original->whisper = clone->whisper;
3356                 ast_set_flag(original, AST_FLAG_WHISPER);
3357                 clone->whisper = NULL;
3358                 ast_clear_flag(clone, AST_FLAG_WHISPER);
3359         }
3360
3361         /* Move data stores over */
3362         if (AST_LIST_FIRST(&clone->datastores))
3363                 AST_LIST_INSERT_TAIL(&original->datastores, AST_LIST_FIRST(&clone->datastores), entry);
3364         AST_LIST_HEAD_INIT_NOLOCK(&clone->datastores);
3365
3366         clone_variables(original, clone);
3367         AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3368         /* Presense of ADSI capable CPE follows clone */
3369         original->adsicpe = clone->adsicpe;
3370         /* Bridge remains the same */
3371         /* CDR fields remain the same */
3372         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3373         /* Application and data remain the same */
3374         /* Clone exception  becomes real one, as with fdno */
3375         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3376         original->fdno = clone->fdno;
3377         /* Schedule context remains the same */
3378         /* Stream stuff stays the same */
3379         /* Keep the original state.  The fixup code will need to work with it most likely */
3380
3381         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3382            out. */
3383         tmpcid = original->cid;
3384         original->cid = clone->cid;
3385         clone->cid = tmpcid;
3386         
3387         /* Restore original timing file descriptor */
3388         original->fds[AST_TIMING_FD] = original->timingfd;
3389         
3390         /* Our native formats are different now */
3391         original->nativeformats = clone->nativeformats;
3392         
3393         /* Context, extension, priority, app data, jump table,  remain the same */
3394         /* pvt switches.  pbx stays the same, as does next */
3395         
3396         /* Set the write format */
3397         ast_set_write_format(original, wformat);
3398
3399         /* Set the read format */
3400         ast_set_read_format(original, rformat);
3401
3402         /* Copy the music class */
3403         ast_string_field_set(original, musicclass, clone->musicclass);
3404
3405         if (option_debug)
3406                 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3407
3408         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
3409            can fix up everything as best as possible */
3410         if (original->tech->fixup) {
3411                 res = original->tech->fixup(clone, original);
3412                 if (res) {
3413                         ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3414                                 original->tech->type, original->name);
3415                         ast_channel_unlock(clone);
3416                         return -1;
3417                 }
3418         } else
3419                 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
3420                         original->tech->type, original->name);
3421         
3422         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
3423            a zombie so nothing tries to touch it.  If it's already been marked as a
3424            zombie, then free it now (since it already is considered invalid). */
3425         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3426                 if (option_debug)
3427                         ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3428                 ast_channel_unlock(clone);
3429                 manager_event(EVENT_FLAG_CALL, "Hangup",
3430                         "Channel: %s\r\n"
3431                         "Uniqueid: %s\r\n"
3432                         "Cause: %d\r\n"
3433                         "Cause-txt: %s\r\n",
3434                         clone->name,
3435                         clone->uniqueid,
3436                         clone->hangupcause,
3437                         ast_cause2str(clone->hangupcause)
3438                         );
3439                 ast_channel_free(clone);
3440         } else {
3441                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3442                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3443                 ast_queue_frame(clone, &ast_null_frame);
3444                 ast_channel_unlock(clone);
3445         }
3446         
3447         /* Signal any blocker */
3448         if (ast_test_flag(original, AST_FLAG_BLOCKING))
3449                 pthread_kill(original->blocker, SIGURG);
3450         if (option_debug)
3451                 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3452         return 0;
3453 }
3454
3455 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3456 {
3457         if (callerid) {
3458                 if (chan->cid.cid_num)
3459                         free(chan->cid.cid_num);
3460                 chan->cid.cid_num = ast_strdup(callerid);
3461         }
3462         if (calleridname) {
3463                 if (chan->cid.cid_name)
3464                         free(chan->cid.cid_name);
3465                 chan->cid.cid_name = ast_strdup(calleridname);
3466         }
3467         if (ani) {
3468                 if (chan->cid.cid_ani)
3469                         free(chan->cid.cid_ani);
3470                 chan->cid.cid_ani = ast_strdup(ani);
3471         }
3472         if (chan->cdr)
3473                 ast_cdr_setcid(chan->cdr, chan);
3474         manager_event(EVENT_FLAG_CALL, "Newcallerid",
3475                                 "Channel: %s\r\n"
3476                                 "CallerID: %s\r\n"
3477                                 "CallerIDName: %s\r\n"
3478                                 "Uniqueid: %s\r\n"
3479                                 "CID-CallingPres: %d (%s)\r\n",
3480                                 chan->name,
3481                                 S_OR(chan->cid.cid_num, "<Unknown>"),
3482                                 S_OR(chan->cid.cid_name, "<Unknown>"),
3483                                 chan->uniqueid,
3484                                 chan->cid.cid_pres,
3485                                 ast_describe_caller_presentation(chan->cid.cid_pres)
3486                                 );
3487 }
3488
3489 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
3490 {
3491         int oldstate = chan->_state;
3492
3493         if (oldstate == state)
3494                 return 0;
3495
3496         chan->_state = state;
3497         ast_device_state_changed_literal(chan->name);
3498         manager_event(EVENT_FLAG_CALL,
3499                       (oldstate == AST_STATE_DOWN) ? "Newchannel" : "Newstate",
3500                       "Channel: %s\r\n"
3501                       "State: %s\r\n"
3502                       "CallerID: %s\r\n"
3503                       "CallerIDName: %s\r\n"
3504                       "Uniqueid: %s\r\n",
3505                       chan->name, ast_state2str(chan->_state),
3506                       S_OR(chan->cid.cid_num, "<unknown>"),
3507                       S_OR(chan->cid.cid_name, "<unknown>"),
3508                       chan->uniqueid);
3509
3510         return 0;
3511 }
3512
3513 /*! \brief Find bridged channel */
3514 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3515 {
3516         struct ast_channel *bridged;
3517         bridged = chan->_bridge;
3518         if (bridged && bridged->tech->bridged_channel)
3519                 bridged = bridged->tech->bridged_channel(chan, bridged);
3520         return bridged;
3521 }
3522
3523 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3524 {
3525         int min = 0, sec = 0, check;
3526
3527         check = ast_autoservice_start(peer);
3528         if (check)
3529                 return;
3530
3531         if (remain > 0) {
3532                 if (remain / 60 > 1) {
3533                         min = remain / 60;
3534                         sec = remain % 60;
3535                 } else {
3536                         sec = remain;
3537                 }
3538         }
3539         
3540         if (!strcmp(sound,"timeleft")) {        /* Queue support */
3541                 ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
3542                 if (min) {
3543                         ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
3544                         ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
3545                 }
3546                 if (sec) {
3547                         ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
3548                         ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
3549                 }
3550         } else {
3551                 ast_stream_and_wait(chan, sound, chan->language, "");
3552         }
3553
3554         ast_autoservice_stop(peer);
3555 }
3556
3557 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3558                                                  struct ast_bridge_config *config, struct ast_frame **fo,
3559                                                  struct ast_channel **rc, struct timeval bridge_end)
3560 {
3561         /* Copy voice back and forth between the two channels. */