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