Tweak the if statement a bit
[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                 struct ast_frame *duped_fr;
1338
1339                 ast_mutex_lock(&spy->lock);
1340
1341                 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1342
1343                 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1344                         if (!translated_frame) {
1345                                 if (trans->path && (trans->last_format != f->subclass)) {
1346                                         ast_translator_free_path(trans->path);
1347                                         trans->path = NULL;
1348                                 }
1349                                 if (!trans->path) {
1350                                         ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1351                                                 ast_getformatname(f->subclass), chan->name);
1352                                         if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1353                                                 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1354                                                         ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1355                                                 ast_mutex_unlock(&spy->lock);
1356                                                 continue;
1357                                         } else {
1358                                                 trans->last_format = f->subclass;
1359                                         }
1360                                 }
1361                                 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1362                                         ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1363                                                 ast_getformatname(AST_FORMAT_SLINEAR));
1364                                         ast_mutex_unlock(&spy->lock);
1365                                         break;
1366                                 }
1367                         }
1368                         duped_fr = ast_frdup(translated_frame);
1369                 } else 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                 } else
1376                         duped_fr = ast_frdup(f);
1377
1378                 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1379
1380                 queue->samples += f->samples;
1381
1382                 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1383                         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1384                                 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1385                                 case CHANSPY_TRIGGER_READ:
1386                                         if (dir == SPY_WRITE) {
1387                                                 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1388                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1389                                                 if (option_debug)
1390                                                         ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1391                                                                 spy->type, chan->name);
1392                                         }
1393                                         break;
1394                                 case CHANSPY_TRIGGER_WRITE:
1395                                         if (dir == SPY_READ) {
1396                                                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1397                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1398                                                 if (option_debug)
1399                                                         ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1400                                                                 spy->type, chan->name);
1401                                         }
1402                                         break;
1403                                 }
1404                                 if (option_debug)
1405                                         ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1406                                                 spy->type, chan->name);
1407                                 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1408                                 ast_cond_signal(&spy->trigger);
1409                         } else {
1410                                 if (option_debug)
1411                                         ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1412                                                 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1413                                 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1414                                         struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1415                                         queue->samples -= drop->samples;
1416                                         ast_frfree(drop);
1417                                 }
1418                         }
1419                 } else {
1420                         switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1421                         case CHANSPY_TRIGGER_READ:
1422                                 if (dir == SPY_READ)
1423                                         ast_cond_signal(&spy->trigger);
1424                                 break;
1425                         case CHANSPY_TRIGGER_WRITE:
1426                                 if (dir == SPY_WRITE)
1427                                         ast_cond_signal(&spy->trigger);
1428                                 break;
1429                         }
1430                 }
1431
1432                 ast_mutex_unlock(&spy->lock);
1433         }
1434
1435         if (translated_frame)
1436                 ast_frfree(translated_frame);
1437 }
1438
1439 static void free_translation(struct ast_channel *clone)
1440 {
1441         if (clone->writetrans)
1442                 ast_translator_free_path(clone->writetrans);
1443         if (clone->readtrans)
1444                 ast_translator_free_path(clone->readtrans);
1445         clone->writetrans = NULL;
1446         clone->readtrans = NULL;
1447         clone->rawwriteformat = clone->nativeformats;
1448         clone->rawreadformat = clone->nativeformats;
1449 }
1450
1451 /*! \brief Hangup a channel */
1452 int ast_hangup(struct ast_channel *chan)
1453 {
1454         int res = 0;
1455
1456         /* Don't actually hang up a channel that will masquerade as someone else, or
1457            if someone is going to masquerade as us */
1458         ast_channel_lock(chan);
1459
1460         detach_spies(chan);             /* get rid of spies */
1461
1462         if (chan->masq) {
1463                 if (ast_do_masquerade(chan))
1464                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1465         }
1466
1467         if (chan->masq) {
1468                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1469                 ast_channel_unlock(chan);
1470                 return 0;
1471         }
1472         /* If this channel is one which will be masqueraded into something,
1473            mark it as a zombie already, so we know to free it later */
1474         if (chan->masqr) {
1475                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1476                 ast_channel_unlock(chan);
1477                 return 0;
1478         }
1479         free_translation(chan);
1480         /* Close audio stream */
1481         if (chan->stream) {
1482                 ast_closestream(chan->stream);
1483                 chan->stream = NULL;
1484         }
1485         /* Close video stream */
1486         if (chan->vstream) {
1487                 ast_closestream(chan->vstream);
1488                 chan->vstream = NULL;
1489         }
1490         if (chan->sched) {
1491                 sched_context_destroy(chan->sched);
1492                 chan->sched = NULL;
1493         }
1494         
1495         if (chan->generatordata)        /* Clear any tone stuff remaining */
1496                 chan->generator->release(chan, chan->generatordata);
1497         chan->generatordata = NULL;
1498         chan->generator = NULL;
1499         if (chan->cdr) {                /* End the CDR if it hasn't already */
1500                 ast_cdr_end(chan->cdr);
1501                 ast_cdr_detach(chan->cdr);      /* Post and Free the CDR */
1502                 chan->cdr = NULL;
1503         }
1504         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1505                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1506                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1507                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1508                 CRASH;
1509         }
1510         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1511                 if (option_debug)
1512                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1513                 if (chan->tech->hangup)
1514                         res = chan->tech->hangup(chan);
1515         } else {
1516                 if (option_debug)
1517                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1518         }
1519                         
1520         ast_channel_unlock(chan);
1521         manager_event(EVENT_FLAG_CALL, "Hangup",
1522                         "Channel: %s\r\n"
1523                         "Uniqueid: %s\r\n"
1524                         "Cause: %d\r\n"
1525                         "Cause-txt: %s\r\n",
1526                         chan->name,
1527                         chan->uniqueid,
1528                         chan->hangupcause,
1529                         ast_cause2str(chan->hangupcause)
1530                         );
1531         ast_channel_free(chan);
1532         return res;
1533 }
1534
1535 int ast_answer(struct ast_channel *chan)
1536 {
1537         int res = 0;
1538         ast_channel_lock(chan);
1539         /* You can't answer an outbound call */
1540         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1541                 ast_channel_unlock(chan);
1542                 return 0;
1543         }
1544         /* Stop if we're a zombie or need a soft hangup */
1545         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1546                 ast_channel_unlock(chan);
1547                 return -1;
1548         }
1549         switch(chan->_state) {
1550         case AST_STATE_RINGING:
1551         case AST_STATE_RING:
1552                 if (chan->tech->answer)
1553                         res = chan->tech->answer(chan);
1554                 ast_setstate(chan, AST_STATE_UP);
1555                 ast_cdr_answer(chan->cdr);
1556                 break;
1557         case AST_STATE_UP:
1558                 ast_cdr_answer(chan->cdr);
1559                 break;
1560         default:
1561                 break;
1562         }
1563         ast_channel_unlock(chan);
1564         return res;
1565 }
1566
1567 void ast_deactivate_generator(struct ast_channel *chan)
1568 {
1569         ast_channel_lock(chan);
1570         if (chan->generatordata) {
1571                 if (chan->generator && chan->generator->release)
1572                         chan->generator->release(chan, chan->generatordata);
1573                 chan->generatordata = NULL;
1574                 chan->generator = NULL;
1575                 chan->fds[AST_GENERATOR_FD] = -1;
1576                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1577                 ast_settimeout(chan, 0, NULL, NULL);
1578         }
1579         ast_channel_unlock(chan);
1580 }
1581
1582 static int generator_force(void *data)
1583 {
1584         /* Called if generator doesn't have data */
1585         void *tmp;
1586         int res;
1587         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1588         struct ast_channel *chan = data;
1589         tmp = chan->generatordata;
1590         chan->generatordata = NULL;
1591         generate = chan->generator->generate;
1592         res = generate(chan, tmp, 0, 160);
1593         chan->generatordata = tmp;
1594         if (res) {
1595                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1596                 ast_deactivate_generator(chan);
1597         }
1598         return 0;
1599 }
1600
1601 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1602 {
1603         int res = 0;
1604
1605         ast_channel_lock(chan);
1606
1607         if (chan->generatordata) {
1608                 if (chan->generator && chan->generator->release)
1609                         chan->generator->release(chan, chan->generatordata);
1610                 chan->generatordata = NULL;
1611         }
1612
1613         ast_prod(chan);
1614         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1615                 res = -1;
1616         }
1617         
1618         if (!res) {
1619                 ast_settimeout(chan, 160, generator_force, chan);
1620                 chan->generator = gen;
1621         }
1622
1623         ast_channel_unlock(chan);
1624
1625         return res;
1626 }
1627
1628 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1629 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1630 {
1631         int winner = -1;
1632         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1633         return winner;
1634 }
1635
1636 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1637 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1638         int *exception, int *outfd, int *ms)
1639 {
1640         struct timeval start = { 0 , 0 };
1641         struct pollfd *pfds;
1642         int res;
1643         long rms;
1644         int x, y, max;
1645         int sz;
1646         time_t now = 0;
1647         long whentohangup = 0, diff;
1648         struct ast_channel *winner = NULL;
1649         struct fdmap {
1650                 int chan;
1651                 int fdno;
1652         } *fdmap;
1653
1654         sz = n * AST_MAX_FDS + nfds;
1655         pfds = alloca(sizeof(*pfds) * sz);
1656         fdmap = alloca(sizeof(*fdmap) * sz);
1657
1658         if (outfd)
1659                 *outfd = -99999;
1660         if (exception)
1661                 *exception = 0;
1662         
1663         /* Perform any pending masquerades */
1664         for (x=0; x < n; x++) {
1665                 ast_channel_lock(c[x]);
1666                 if (c[x]->masq) {
1667                         if (ast_do_masquerade(c[x])) {
1668                                 ast_log(LOG_WARNING, "Masquerade failed\n");
1669                                 *ms = -1;
1670                                 ast_channel_unlock(c[x]);
1671                                 return NULL;
1672                         }
1673                 }
1674                 if (c[x]->whentohangup) {
1675                         if (!whentohangup)
1676                                 time(&now);
1677                         diff = c[x]->whentohangup - now;
1678                         if (diff < 1) {
1679                                 /* Should already be hungup */
1680                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1681                                 ast_channel_unlock(c[x]);
1682                                 return c[x];
1683                         }
1684                         if (!whentohangup || (diff < whentohangup))
1685                                 whentohangup = diff;
1686                 }
1687                 ast_channel_unlock(c[x]);
1688         }
1689         /* Wait full interval */
1690         rms = *ms;
1691         if (whentohangup) {
1692                 rms = (whentohangup - now) * 1000;      /* timeout in milliseconds */
1693                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1694                         rms =  *ms;
1695         }
1696         /*
1697          * Build the pollfd array, putting the channels' fds first,
1698          * followed by individual fds. Order is important because
1699          * individual fd's must have priority over channel fds.
1700          */
1701         max = 0;
1702         for (x=0; x<n; x++) {
1703                 for (y=0; y<AST_MAX_FDS; y++) {
1704                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1705                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1706                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1707                 }
1708                 CHECK_BLOCKING(c[x]);
1709         }
1710         /* Add the individual fds */
1711         for (x=0; x<nfds; x++) {
1712                 fdmap[max].chan = -1;
1713                 max += ast_add_fd(&pfds[max], fds[x]);
1714         }
1715
1716         if (*ms > 0)
1717                 start = ast_tvnow();
1718         
1719         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1720                 do {
1721                         int kbrms = rms;
1722                         if (kbrms > 600000)
1723                                 kbrms = 600000;
1724                         res = poll(pfds, max, kbrms);
1725                         if (!res)
1726                                 rms -= kbrms;
1727                 } while (!res && (rms > 0));
1728         } else {
1729                 res = poll(pfds, max, rms);
1730         }
1731         for (x=0; x<n; x++)
1732                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1733         if (res < 0) { /* Simulate a timeout if we were interrupted */
1734                 if (errno != EINTR)
1735                         *ms = -1;
1736                 return NULL;
1737         }
1738         if (whentohangup) {   /* if we have a timeout, check who expired */
1739                 time(&now);
1740                 for (x=0; x<n; x++) {
1741                         if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1742                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1743                                 if (winner == NULL)
1744                                         winner = c[x];
1745                         }
1746                 }
1747         }
1748         if (res == 0) { /* no fd ready, reset timeout and done */
1749                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1750                 return winner;
1751         }
1752         /*
1753          * Then check if any channel or fd has a pending event.
1754          * Remember to check channels first and fds last, as they
1755          * must have priority on setting 'winner'
1756          */
1757         for (x = 0; x < max; x++) {
1758                 res = pfds[x].revents;
1759                 if (res == 0)
1760                         continue;
1761                 if (fdmap[x].chan >= 0) {       /* this is a channel */
1762                         winner = c[fdmap[x].chan];      /* override previous winners */
1763                         if (res & POLLPRI)
1764                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1765                         else
1766                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1767                         winner->fdno = fdmap[x].fdno;
1768                 } else {                        /* this is an fd */
1769                         if (outfd)
1770                                 *outfd = pfds[x].fd;
1771                         if (exception)
1772                                 *exception = (res & POLLPRI) ? -1 : 0;
1773                         winner = NULL;
1774                 }
1775         }
1776         if (*ms > 0) {
1777                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1778                 if (*ms < 0)
1779                         *ms = 0;
1780         }
1781         return winner;
1782 }
1783
1784 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1785 {
1786         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1787 }
1788
1789 int ast_waitfor(struct ast_channel *c, int ms)
1790 {
1791         int oldms = ms; /* -1 if no timeout */
1792
1793         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1794         if ((ms < 0) && (oldms < 0))
1795                 ms = 0;
1796         return ms;
1797 }
1798
1799 /* XXX never to be called with ms = -1 */
1800 int ast_waitfordigit(struct ast_channel *c, int ms)
1801 {
1802         return ast_waitfordigit_full(c, ms, -1, -1);
1803 }
1804
1805 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1806 {
1807         int res = -1;
1808 #ifdef HAVE_ZAPTEL
1809         if (c->timingfd > -1) {
1810                 if (!func) {
1811                         samples = 0;
1812                         data = 0;
1813                 }
1814                 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1815                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1816                 c->timingfunc = func;
1817                 c->timingdata = data;
1818         }
1819 #endif  
1820         return res;
1821 }
1822
1823 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1824 {
1825
1826         /* Stop if we're a zombie or need a soft hangup */
1827         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1828                 return -1;
1829         /* Wait for a digit, no more than ms milliseconds total. */
1830         while (ms) {
1831                 struct ast_channel *rchan;
1832                 int outfd;
1833
1834                 errno = 0;
1835                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1836                 if (!rchan && outfd < 0 && ms) {
1837                         if (errno == 0 || errno == EINTR)
1838                                 continue;
1839                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1840                         return -1;
1841                 } else if (outfd > -1) {
1842                         /* The FD we were watching has something waiting */
1843                         return 1;
1844                 } else if (rchan) {
1845                         int res;
1846                         struct ast_frame *f = ast_read(c);
1847                         if (!f)
1848                                 return -1;
1849
1850                         switch(f->frametype) {
1851                         case AST_FRAME_DTMF:
1852                                 res = f->subclass;
1853                                 ast_frfree(f);
1854                                 return res;
1855                         case AST_FRAME_CONTROL:
1856                                 switch(f->subclass) {
1857                                 case AST_CONTROL_HANGUP:
1858                                         ast_frfree(f);
1859                                         return -1;
1860                                 case AST_CONTROL_RINGING:
1861                                 case AST_CONTROL_ANSWER:
1862                                         /* Unimportant */
1863                                         break;
1864                                 default:
1865                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1866                                         break;
1867                                 }
1868                                 break;
1869                         case AST_FRAME_VOICE:
1870                                 /* Write audio if appropriate */
1871                                 if (audiofd > -1)
1872                                         write(audiofd, f->data, f->datalen);
1873                         default:
1874                                 /* Ignore */
1875                                 break;
1876                         }
1877                         ast_frfree(f);
1878                 }
1879         }
1880         return 0; /* Time is up */
1881 }
1882
1883 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1884 {
1885         struct ast_frame *f = NULL;     /* the return value */
1886         int blah;
1887         int prestate;
1888
1889         /* this function is very long so make sure there is only one return
1890          * point at the end (there is only one exception to this).
1891          */
1892         ast_channel_lock(chan);
1893         if (chan->masq) {
1894                 if (ast_do_masquerade(chan))
1895                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1896                 else
1897                         f =  &ast_null_frame;
1898                 goto done;
1899         }
1900
1901         /* Stop if we're a zombie or need a soft hangup */
1902         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1903                 if (chan->generator)
1904                         ast_deactivate_generator(chan);
1905                 goto done;
1906         }
1907         prestate = chan->_state;
1908
1909         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
1910             !ast_strlen_zero(chan->dtmfq)) {
1911                 /* We have DTMF that has been deferred.  Return it now */
1912                 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
1913                 chan->dtmff.subclass = chan->dtmfq[0];
1914                 /* Drop first digit from the buffer */
1915                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1916                 f = &chan->dtmff;
1917                 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
1918                 chan->emulate_dtmf_digit = f->subclass;
1919                 chan->emulate_dtmf_samples = AST_DEFAULT_EMULATE_DTMF_SAMPLES;
1920                 goto done;
1921         }
1922         
1923         /* Read and ignore anything on the alertpipe, but read only
1924            one sizeof(blah) per frame that we send from it */
1925         if (chan->alertpipe[0] > -1)
1926                 read(chan->alertpipe[0], &blah, sizeof(blah));
1927
1928 #ifdef HAVE_ZAPTEL
1929         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1930                 int res;
1931
1932                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1933                 blah = -1;
1934                 /* IF we can't get event, assume it's an expired as-per the old interface */
1935                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1936                 if (res)
1937                         blah = ZT_EVENT_TIMER_EXPIRED;
1938
1939                 if (blah == ZT_EVENT_TIMER_PING) {
1940                         if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
1941                                 /* Acknowledge PONG unless we need it again */
1942                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1943                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1944                                 }
1945                         }
1946                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1947                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1948                         if (chan->timingfunc) {
1949                                 /* save a copy of func/data before unlocking the channel */
1950                                 int (*func)(void *) = chan->timingfunc;
1951                                 void *data = chan->timingdata;
1952                                 ast_channel_unlock(chan);
1953                                 func(data);
1954                         } else {
1955                                 blah = 0;
1956                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1957                                 chan->timingdata = NULL;
1958                                 ast_channel_unlock(chan);
1959                         }
1960                         /* cannot 'goto done' because the channel is already unlocked */
1961                         return &ast_null_frame;
1962                 } else
1963                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1964         } else
1965 #endif
1966         if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
1967                 /* if the AST_GENERATOR_FD is set, call the generator with args
1968                  * set to -1 so it can do whatever it needs to.
1969                  */
1970                 void *tmp = chan->generatordata;
1971                 chan->generatordata = NULL;     /* reset to let ast_write get through */
1972                 chan->generator->generate(chan, tmp, -1, -1);
1973                 chan->generatordata = tmp;
1974                 f = &ast_null_frame;
1975                 goto done;
1976         }
1977
1978         /* Check for pending read queue */
1979         if (!AST_LIST_EMPTY(&chan->readq)) {
1980                 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
1981                 /* Interpret hangup and return NULL */
1982                 /* XXX why not the same for frames from the channel ? */
1983                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
1984                         ast_frfree(f);
1985                         f = NULL;
1986                 }
1987         } else {
1988                 chan->blocker = pthread_self();
1989                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1990                         if (chan->tech->exception)
1991                                 f = chan->tech->exception(chan);
1992                         else {
1993                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1994                                 f = &ast_null_frame;
1995                         }
1996                         /* Clear the exception flag */
1997                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1998                 } else if (chan->tech->read)
1999                         f = chan->tech->read(chan);
2000                 else
2001                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2002         }
2003
2004         if (f) {
2005                 /* if the channel driver returned more than one frame, stuff the excess
2006                    into the readq for the next ast_read call (note that we can safely assume
2007                    that the readq is empty, because otherwise we would not have called into
2008                    the channel driver and f would be only a single frame)
2009                 */
2010                 if (AST_LIST_NEXT(f, frame_list)) {
2011                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2012                         AST_LIST_NEXT(f, frame_list) = NULL;
2013                 }
2014
2015                 switch (f->frametype) {
2016                 case AST_FRAME_CONTROL:
2017                         if (f->subclass == AST_CONTROL_ANSWER) {
2018                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2019                                         ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
2020                                         ast_frfree(f);
2021                                         f = &ast_null_frame;
2022                                 } else if (prestate == AST_STATE_UP) {
2023                                         ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
2024                                         ast_frfree(f);
2025                                         f = &ast_null_frame;
2026                                 } else {
2027                                         /* Answer the CDR */
2028                                         ast_setstate(chan, AST_STATE_UP);
2029                                         ast_cdr_answer(chan->cdr);
2030                                 }
2031                         }
2032                         break;
2033                 case AST_FRAME_DTMF_END:
2034                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s\n", f->subclass, chan->name);
2035                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
2036                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2037                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2038                                 else
2039                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2040                                 ast_frfree(f);
2041                                 f = &ast_null_frame;
2042                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2043                                 f->frametype = AST_FRAME_DTMF_BEGIN;
2044                                 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2045                                 chan->emulate_dtmf_digit = f->subclass;
2046                                 if (f->samples)
2047                                         chan->emulate_dtmf_samples = f->samples;
2048                                 else
2049                                         chan->emulate_dtmf_samples = AST_DEFAULT_EMULATE_DTMF_SAMPLES;
2050                         } else 
2051                                 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2052                         break;
2053                 case AST_FRAME_DTMF_BEGIN:
2054                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2055                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF)) {
2056                                 ast_frfree(f);
2057                                 f = &ast_null_frame;
2058                         } else 
2059                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2060                         break;
2061                 case AST_FRAME_VOICE:
2062                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the samples
2063                          * first get to zero, because we want to make sure we pass at least one
2064                          * voice frame through before starting the next digit, to ensure a gap
2065                          * between DTMF digits. */
2066                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_samples) {
2067                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2068                                 chan->emulate_dtmf_digit = 0;
2069                         }
2070
2071                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2072                                 ast_frfree(f);
2073                                 f = &ast_null_frame;
2074                         } else if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2075                                 if (f->samples >= chan->emulate_dtmf_samples) {
2076                                         chan->emulate_dtmf_samples = 0;
2077                                         f->frametype = AST_FRAME_DTMF_END;
2078                                         f->subclass = chan->emulate_dtmf_digit;
2079                                 } else {
2080                                         chan->emulate_dtmf_samples -= f->samples;
2081                                         ast_frfree(f);
2082                                         f = &ast_null_frame;
2083                                 }
2084                         } else if (!(f->subclass & chan->nativeformats)) {
2085                                 /* This frame can't be from the current native formats -- drop it on the
2086                                    floor */
2087                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2088                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2089                                 ast_frfree(f);
2090                                 f = &ast_null_frame;
2091                         } else {
2092                                 if (chan->spies)
2093                                         queue_frame_to_spies(chan, f, SPY_READ);
2094                                 
2095                                 if (chan->monitor && chan->monitor->read_stream ) {
2096                                         /* XXX what does this do ? */
2097 #ifndef MONITOR_CONSTANT_DELAY
2098                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2099                                         if (jump >= 0) {
2100                                                 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2101                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2102                                                 chan->insmpl += jump + 4 * f->samples;
2103                                         } else
2104                                                 chan->insmpl+= f->samples;
2105 #else
2106                                         int jump = chan->outsmpl - chan->insmpl;
2107                                         if (jump - MONITOR_DELAY >= 0) {
2108                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2109                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2110                                                 chan->insmpl += jump;
2111                                         } else
2112                                                 chan->insmpl += f->samples;
2113 #endif
2114                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2115                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2116                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2117                                         }
2118                                 }
2119
2120                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2121                                         f = &ast_null_frame;
2122
2123                                 /* Run generator sitting on the line if timing device not available
2124                                 * and synchronous generation of outgoing frames is necessary       */
2125                                 if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2126                                         void *tmp = chan->generatordata;
2127                                         int res;
2128
2129                                         if (chan->timingfunc) {
2130                                                 if (option_debug > 1)
2131                                                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2132                                                 ast_settimeout(chan, 0, NULL, NULL);
2133                                         }
2134
2135                                         chan->generatordata = NULL;     /* reset, to let writes go through */
2136                                         res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2137                                         chan->generatordata = tmp;
2138                                         if (res) {
2139                                                 if (option_debug > 1)
2140                                                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2141                                                 ast_deactivate_generator(chan);
2142                                         }
2143
2144                                 } else if (f->frametype == AST_FRAME_CNG) {
2145                                         if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2146                                                 if (option_debug > 1)
2147                                                         ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2148                                                 ast_settimeout(chan, 160, generator_force, chan);
2149                                         }
2150                                 }
2151                         }
2152                 default:
2153                         /* Just pass it on! */
2154                         break;
2155                 }
2156         } else {
2157                 /* Make sure we always return NULL in the future */
2158                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2159                 if (chan->generator)
2160                         ast_deactivate_generator(chan);
2161                 /* End the CDR if appropriate */
2162                 if (chan->cdr)
2163                         ast_cdr_end(chan->cdr);
2164         }
2165
2166         /* High bit prints debugging */
2167         if (chan->fin & DEBUGCHAN_FLAG)
2168                 ast_frame_dump(chan->name, f, "<<");
2169         chan->fin = FRAMECOUNT_INC(chan->fin);
2170
2171 done:
2172         ast_channel_unlock(chan);
2173         return f;
2174 }
2175
2176 int ast_internal_timing_enabled(struct ast_channel *chan)
2177 {
2178         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2179         if (option_debug > 4)
2180                 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);
2181         return ret;
2182 }
2183
2184 struct ast_frame *ast_read(struct ast_channel *chan)
2185 {
2186         return __ast_read(chan, 0);
2187 }
2188
2189 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2190 {
2191         return __ast_read(chan, 1);
2192 }
2193
2194 int ast_indicate(struct ast_channel *chan, int condition)
2195 {
2196         return ast_indicate_data(chan, condition, NULL, 0);
2197 }
2198
2199 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2200 {
2201         int res = -1;
2202
2203         ast_channel_lock(chan);
2204         /* Stop if we're a zombie or need a soft hangup */
2205         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2206                 ast_channel_unlock(chan);
2207                 return -1;
2208         }
2209         if (chan->tech->indicate)
2210                 res = chan->tech->indicate(chan, condition, data, datalen);
2211         ast_channel_unlock(chan);
2212         if (!chan->tech->indicate || res) {
2213                 /*
2214                  * Device does not support (that) indication, lets fake
2215                  * it by doing our own tone generation. (PM2002)
2216                  */
2217                 if (condition < 0)
2218                         ast_playtones_stop(chan);
2219                 else {
2220                         const struct tone_zone_sound *ts = NULL;
2221                         switch (condition) {
2222                         case AST_CONTROL_RINGING:
2223                                 ts = ast_get_indication_tone(chan->zone, "ring");
2224                                 break;
2225                         case AST_CONTROL_BUSY:
2226                                 ts = ast_get_indication_tone(chan->zone, "busy");
2227                                 break;
2228                         case AST_CONTROL_CONGESTION:
2229                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2230                                 break;
2231                         }
2232                         if (ts && ts->data[0]) {
2233                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2234                                 ast_playtones_start(chan,0,ts->data, 1);
2235                                 res = 0;
2236                         } else if (condition == AST_CONTROL_PROGRESS) {
2237                                 /* ast_playtones_stop(chan); */
2238                         } else if (condition == AST_CONTROL_PROCEEDING) {
2239                                 /* Do nothing, really */
2240                         } else if (condition == AST_CONTROL_HOLD) {
2241                                 /* Do nothing.... */
2242                         } else if (condition == AST_CONTROL_UNHOLD) {
2243                                 /* Do nothing.... */
2244                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2245                                 /* Do nothing.... */
2246                         } else {
2247                                 /* not handled */
2248                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2249                                 res = -1;
2250                         }
2251                 }
2252         }
2253         return res;
2254 }
2255
2256 int ast_recvchar(struct ast_channel *chan, int timeout)
2257 {
2258         int c;
2259         char *buf = ast_recvtext(chan, timeout);
2260         if (buf == NULL)
2261                 return -1;      /* error or timeout */
2262         c = *(unsigned char *)buf;
2263         free(buf);
2264         return c;
2265 }
2266
2267 char *ast_recvtext(struct ast_channel *chan, int timeout)
2268 {
2269         int res, done = 0;
2270         char *buf = NULL;
2271         
2272         while (!done) {
2273                 struct ast_frame *f;
2274                 if (ast_check_hangup(chan))
2275                         break;
2276                 res = ast_waitfor(chan, timeout);
2277                 if (res <= 0) /* timeout or error */
2278                         break;
2279                 timeout = res;  /* update timeout */
2280                 f = ast_read(chan);
2281                 if (f == NULL)
2282                         break; /* no frame */
2283                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2284                         done = 1;       /* force a break */
2285                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2286                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2287                         done = 1;
2288                 }
2289                 ast_frfree(f);
2290         }
2291         return buf;
2292 }
2293
2294 int ast_sendtext(struct ast_channel *chan, const char *text)
2295 {
2296         int res = 0;
2297         /* Stop if we're a zombie or need a soft hangup */
2298         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2299                 return -1;
2300         CHECK_BLOCKING(chan);
2301         if (chan->tech->send_text)
2302                 res = chan->tech->send_text(chan, text);
2303         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2304         return res;
2305 }
2306
2307 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2308 {
2309         int res = -1;
2310
2311         if (chan->tech->send_digit_begin)
2312                 res = chan->tech->send_digit_begin(chan, digit);
2313
2314         if (res) {
2315                 /*
2316                  * Device does not support DTMF tones, lets fake
2317                  * it by doing our own generation. (PM2002)
2318                  */
2319                 static const char* dtmf_tones[] = {
2320                         "!941+1336/100,!0/100", /* 0 */
2321                         "!697+1209/100,!0/100", /* 1 */
2322                         "!697+1336/100,!0/100", /* 2 */
2323                         "!697+1477/100,!0/100", /* 3 */
2324                         "!770+1209/100,!0/100", /* 4 */
2325                         "!770+1336/100,!0/100", /* 5 */
2326                         "!770+1477/100,!0/100", /* 6 */
2327                         "!852+1209/100,!0/100", /* 7 */
2328                         "!852+1336/100,!0/100", /* 8 */
2329                         "!852+1477/100,!0/100", /* 9 */
2330                         "!697+1633/100,!0/100", /* A */
2331                         "!770+1633/100,!0/100", /* B */
2332                         "!852+1633/100,!0/100", /* C */
2333                         "!941+1633/100,!0/100", /* D */
2334                         "!941+1209/100,!0/100", /* * */
2335                         "!941+1477/100,!0/100" };       /* # */
2336                 if (digit >= '0' && digit <='9')
2337                         ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2338                 else if (digit >= 'A' && digit <= 'D')
2339                         ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2340                 else if (digit == '*')
2341                         ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2342                 else if (digit == '#')
2343                         ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2344                 else {
2345                         /* not handled */
2346                         ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2347                 }
2348         }
2349
2350         return 0;
2351 }
2352
2353 int ast_senddigit_end(struct ast_channel *chan, char digit)
2354 {
2355         int res = -1;
2356
2357         if (chan->tech->send_digit_end)
2358                 res = chan->tech->send_digit_end(chan, digit);
2359
2360         if (res && chan->generator)
2361                 ast_playtones_stop(chan);
2362         
2363         return 0;
2364 }
2365
2366 int ast_senddigit(struct ast_channel *chan, char digit)
2367 {
2368         ast_senddigit_begin(chan, digit);
2369         
2370         ast_safe_sleep(chan, 100); /* XXX 100ms ... probably should be configurable */
2371         
2372         return ast_senddigit_end(chan, digit);
2373 }
2374
2375 int ast_prod(struct ast_channel *chan)
2376 {
2377         struct ast_frame a = { AST_FRAME_VOICE };
2378         char nothing[128];
2379
2380         /* Send an empty audio frame to get things moving */
2381         if (chan->_state != AST_STATE_UP) {
2382                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2383                 a.subclass = chan->rawwriteformat;
2384                 a.data = nothing + AST_FRIENDLY_OFFSET;
2385                 a.src = "ast_prod";
2386                 if (ast_write(chan, &a))
2387                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2388         }
2389         return 0;
2390 }
2391
2392 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2393 {
2394         int res;
2395         if (!chan->tech->write_video)
2396                 return 0;
2397         res = ast_write(chan, fr);
2398         if (!res)
2399                 res = 1;
2400         return res;
2401 }
2402
2403 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2404 {
2405         int res = -1;
2406         struct ast_frame *f = NULL;
2407
2408         /* Stop if we're a zombie or need a soft hangup */
2409         ast_channel_lock(chan);
2410         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2411                 goto done;
2412
2413         /* Handle any pending masquerades */
2414         if (chan->masq && ast_do_masquerade(chan)) {
2415                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2416                 goto done;
2417         }
2418         if (chan->masqr) {
2419                 res = 0;        /* XXX explain, why 0 ? */
2420                 goto done;
2421         }
2422         if (chan->generatordata) {
2423                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2424                         ast_deactivate_generator(chan);
2425                 else {
2426                         res = 0;        /* XXX explain, why 0 ? */
2427                         goto done;
2428                 }
2429         }
2430         /* High bit prints debugging */
2431         if (chan->fout & DEBUGCHAN_FLAG)
2432                 ast_frame_dump(chan->name, fr, ">>");
2433         CHECK_BLOCKING(chan);
2434         switch(fr->frametype) {
2435         case AST_FRAME_CONTROL:
2436                 res = (chan->tech->indicate == NULL) ? 0 :
2437                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2438                 break;
2439         case AST_FRAME_DTMF_BEGIN:
2440                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2441                 ast_channel_unlock(chan);
2442                 res = ast_senddigit_begin(chan, fr->subclass);
2443                 ast_channel_lock(chan);
2444                 CHECK_BLOCKING(chan);
2445                 break;
2446         case AST_FRAME_DTMF_END:
2447                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2448                 ast_channel_unlock(chan);
2449                 res = ast_senddigit_end(chan, fr->subclass);
2450                 ast_channel_lock(chan);
2451                 CHECK_BLOCKING(chan);
2452                 break;
2453         case AST_FRAME_TEXT:
2454                 res = (chan->tech->send_text == NULL) ? 0 :
2455                         chan->tech->send_text(chan, (char *) fr->data);
2456                 break;
2457         case AST_FRAME_HTML:
2458                 res = (chan->tech->send_html == NULL) ? 0 :
2459                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2460                 break;
2461         case AST_FRAME_VIDEO:
2462                 /* XXX Handle translation of video codecs one day XXX */
2463                 res = (chan->tech->write_video == NULL) ? 0 :
2464                         chan->tech->write_video(chan, fr);
2465                 break;
2466         case AST_FRAME_MODEM:
2467                 res = (chan->tech->write == NULL) ? 0 :
2468                         chan->tech->write(chan, fr);
2469                 break;
2470         case AST_FRAME_VOICE:
2471                 if (chan->tech->write == NULL)
2472                         break;  /*! \todo XXX should return 0 maybe ? */
2473
2474                 /* Bypass translator if we're writing format in the raw write format.  This
2475                    allows mixing of native / non-native formats */
2476                 if (fr->subclass == chan->rawwriteformat)
2477                         f = fr;
2478                 else
2479                         f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2480                 if (f == NULL) {
2481                         res = 0;
2482                 } else {
2483                         if (chan->spies)
2484                                 queue_frame_to_spies(chan, f, SPY_WRITE);
2485
2486                         if (chan->monitor && chan->monitor->write_stream) {
2487                                 /* XXX must explain this code */
2488 #ifndef MONITOR_CONSTANT_DELAY
2489                                 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2490                                 if (jump >= 0) {
2491                                         if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2492                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2493                                         chan->outsmpl += jump + 4 * f->samples;
2494                                 } else
2495                                         chan->outsmpl += f->samples;
2496 #else
2497                                 int jump = chan->insmpl - chan->outsmpl;
2498                                 if (jump - MONITOR_DELAY >= 0) {
2499                                         if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2500                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2501                                         chan->outsmpl += jump;
2502                                 } else
2503                                         chan->outsmpl += f->samples;
2504 #endif
2505                                 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2506                                         if (ast_writestream(chan->monitor->write_stream, f) < 0)
2507                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2508                                 }
2509                         }
2510
2511                         if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2512                                 /* frame is assumed to be in SLINEAR, since that is
2513                                    required for whisper mode */
2514                                 ast_frame_adjust_volume(f, -2);
2515                                 if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2516                                         short buf[f->samples];
2517                                         struct ast_frame whisper = {
2518                                                 .frametype = AST_FRAME_VOICE,
2519                                                 .subclass = AST_FORMAT_SLINEAR,
2520                                                 .data = buf,
2521                                                 .datalen = sizeof(buf),
2522                                                 .samples = f->samples,
2523                                         };
2524
2525                                         ast_mutex_lock(&chan->whisper->lock);
2526                                         if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2527                                                 ast_frame_slinear_sum(f, &whisper);
2528                                         ast_mutex_unlock(&chan->whisper->lock);
2529                                 }
2530                         }
2531
2532                         res = chan->tech->write(chan, f);
2533                 }
2534                 break;
2535         case AST_FRAME_NULL:
2536         case AST_FRAME_IAX:
2537                 /* Ignore these */
2538                 res = 0;
2539                 break;
2540         default:
2541                 res = chan->tech->write(chan, f);
2542                 break;
2543         }
2544
2545         if (f && f != fr)
2546                 ast_frfree(f);
2547         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2548         /* Consider a write failure to force a soft hangup */
2549         if (res < 0)
2550                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2551         else {
2552                 chan->fout = FRAMECOUNT_INC(chan->fout);
2553         }
2554 done:
2555         ast_channel_unlock(chan);
2556         return res;
2557 }
2558
2559 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2560                       struct ast_trans_pvt **trans, const int direction)
2561 {
2562         int native;
2563         int res;
2564         
2565         /* Make sure we only consider audio */
2566         fmt &= AST_FORMAT_AUDIO_MASK;
2567         
2568         native = chan->nativeformats;
2569         /* Find a translation path from the native format to one of the desired formats */
2570         if (!direction)
2571                 /* reading */
2572                 res = ast_translator_best_choice(&fmt, &native);
2573         else
2574                 /* writing */
2575                 res = ast_translator_best_choice(&native, &fmt);
2576
2577         if (res < 0) {
2578                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2579                         ast_getformatname(native), ast_getformatname(fmt));
2580                 return -1;
2581         }
2582         
2583         /* Now we have a good choice for both. */
2584         ast_channel_lock(chan);
2585
2586         if ((*rawformat == native) && (*format == fmt)) {
2587                 /* the channel is already in these formats, so nothing to do */
2588                 ast_channel_unlock(chan);
2589                 return 0;
2590         }
2591
2592         *rawformat = native;
2593         /* User perspective is fmt */
2594         *format = fmt;
2595         /* Free any read translation we have right now */
2596         if (*trans)
2597                 ast_translator_free_path(*trans);
2598         /* Build a translation path from the raw format to the desired format */
2599         if (!direction)
2600                 /* reading */
2601                 *trans = ast_translator_build_path(*format, *rawformat);
2602         else
2603                 /* writing */
2604                 *trans = ast_translator_build_path(*rawformat, *format);
2605         ast_channel_unlock(chan);
2606         if (option_debug)
2607                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2608                         direction ? "write" : "read", ast_getformatname(fmt));
2609         return 0;
2610 }
2611
2612 int ast_set_read_format(struct ast_channel *chan, int fmt)
2613 {
2614         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2615                           &chan->readtrans, 0);
2616 }
2617
2618 int ast_set_write_format(struct ast_channel *chan, int fmt)
2619 {
2620         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2621                           &chan->writetrans, 1);
2622 }
2623
2624 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)
2625 {
2626         int dummy_outstate;
2627         int cause = 0;
2628         struct ast_channel *chan;
2629         int res = 0;
2630         
2631         if (outstate)
2632                 *outstate = 0;
2633         else
2634                 outstate = &dummy_outstate;     /* make outstate always a valid pointer */
2635
2636         chan = ast_request(type, format, data, &cause);
2637         if (!chan) {
2638                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2639                 /* compute error and return */
2640                 if (cause == AST_CAUSE_BUSY)
2641                         *outstate = AST_CONTROL_BUSY;
2642                 else if (cause == AST_CAUSE_CONGESTION)
2643                         *outstate = AST_CONTROL_CONGESTION;
2644                 return NULL;
2645         }
2646
2647         if (oh) {
2648                 if (oh->vars)   
2649                         ast_set_variables(chan, oh->vars);
2650                 /* XXX why is this necessary, for the parent_channel perhaps ? */
2651                 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2652                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2653                 if (oh->parent_channel)
2654                         ast_channel_inherit_variables(oh->parent_channel, chan);
2655                 if (oh->account)
2656                         ast_cdr_setaccount(chan, oh->account);  
2657         }
2658         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2659
2660         if (ast_call(chan, data, 0)) {  /* ast_call failed... */
2661                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2662         } else {
2663                 res = 1;        /* mark success in case chan->_state is already AST_STATE_UP */
2664                 while (timeout && chan->_state != AST_STATE_UP) {
2665                         struct ast_frame *f;
2666                         res = ast_waitfor(chan, timeout);
2667                         if (res <= 0) /* error, timeout, or done */
2668                                 break;
2669                         if (timeout > -1)
2670                                 timeout = res;
2671                         f = ast_read(chan);
2672                         if (!f) {
2673                                 *outstate = AST_CONTROL_HANGUP;
2674                                 res = 0;
2675                                 break;
2676                         }
2677                         if (f->frametype == AST_FRAME_CONTROL) {
2678                                 switch (f->subclass) {
2679                                 case AST_CONTROL_RINGING:       /* record but keep going */
2680                                         *outstate = f->subclass;
2681                                         break;
2682
2683                                 case AST_CONTROL_BUSY:
2684                                 case AST_CONTROL_CONGESTION:
2685                                 case AST_CONTROL_ANSWER:
2686                                         *outstate = f->subclass;
2687                                         timeout = 0;            /* trick to force exit from the while() */
2688                                         break;
2689
2690                                 /* Ignore these */
2691                                 case AST_CONTROL_PROGRESS:
2692                                 case AST_CONTROL_PROCEEDING:
2693                                 case AST_CONTROL_HOLD:
2694                                 case AST_CONTROL_UNHOLD:
2695                                 case AST_CONTROL_VIDUPDATE:
2696                                 case -1:                        /* Ignore -- just stopping indications */
2697                                         break;
2698
2699                                 default:
2700                                         ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2701                                 }
2702                         }
2703                         ast_frfree(f);
2704                 }
2705         }
2706
2707         /* Final fixups */
2708         if (oh) {
2709                 if (!ast_strlen_zero(oh->context))
2710                         ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2711                 if (!ast_strlen_zero(oh->exten))
2712                         ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2713                 if (oh->priority)       
2714                         chan->priority = oh->priority;
2715         }
2716         if (chan->_state == AST_STATE_UP)
2717                 *outstate = AST_CONTROL_ANSWER;
2718
2719         if (res <= 0) {
2720                 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2721                         ast_cdr_init(chan->cdr, chan);
2722                 if (chan->cdr) {
2723                         char tmp[256];
2724                         snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2725                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2726                         ast_cdr_update(chan);
2727                         ast_cdr_start(chan->cdr);
2728                         ast_cdr_end(chan->cdr);
2729                         /* If the cause wasn't handled properly */
2730                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2731                                 ast_cdr_failed(chan->cdr);
2732                 }
2733                 ast_hangup(chan);
2734                 chan = NULL;
2735         }
2736         return chan;
2737 }
2738
2739 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2740 {
2741         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2742 }
2743
2744 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2745 {
2746         struct chanlist *chan;
2747         struct ast_channel *c;
2748         int capabilities;
2749         int fmt;
2750         int res;
2751         int foo;
2752         int videoformat = format & AST_FORMAT_VIDEO_MASK;
2753
2754         if (!cause)
2755                 cause = &foo;
2756         *cause = AST_CAUSE_NOTDEFINED;
2757
2758         if (AST_LIST_LOCK(&channels)) {
2759                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2760                 return NULL;
2761         }
2762
2763         AST_LIST_TRAVERSE(&backends, chan, list) {
2764                 if (strcasecmp(type, chan->tech->type))
2765                         continue;
2766
2767                 capabilities = chan->tech->capabilities;
2768                 fmt = format & AST_FORMAT_AUDIO_MASK;
2769                 res = ast_translator_best_choice(&fmt, &capabilities);
2770                 if (res < 0) {
2771                         ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2772                         AST_LIST_UNLOCK(&channels);
2773                         return NULL;
2774                 }
2775                 AST_LIST_UNLOCK(&channels);
2776                 if (!chan->tech->requester)
2777                         return NULL;
2778                 
2779                 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
2780                         return NULL;
2781
2782                 if (c->_state == AST_STATE_DOWN) {
2783                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2784                                       "Channel: %s\r\n"
2785                                       "State: %s\r\n"
2786                                       "CallerID: %s\r\n"
2787                                       "CallerIDName: %s\r\n"
2788                                       "Uniqueid: %s\r\n",
2789                                       c->name, ast_state2str(c->_state),
2790                                       S_OR(c->cid.cid_num, "<unknown>"),
2791                                       S_OR(c->cid.cid_name, "<unknown>"),
2792                                       c->uniqueid);
2793                 }
2794                 return c;
2795         }
2796
2797         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2798         *cause = AST_CAUSE_NOSUCHDRIVER;
2799         AST_LIST_UNLOCK(&channels);
2800
2801         return NULL;
2802 }
2803
2804 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2805 {
2806         /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2807            If the remote end does not answer within the timeout, then do NOT hang up, but
2808            return anyway.  */
2809         int res = -1;
2810         /* Stop if we're a zombie or need a soft hangup */
2811         ast_channel_lock(chan);
2812         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2813                 if (chan->tech->call)
2814                         res = chan->tech->call(chan, addr, timeout);
2815                 ast_set_flag(chan, AST_FLAG_OUTGOING);
2816         }
2817         ast_channel_unlock(chan);
2818         return res;
2819 }
2820
2821 /*!
2822   \brief Transfer a call to dest, if the channel supports transfer
2823
2824   Called by:
2825     \arg app_transfer
2826     \arg the manager interface
2827 */
2828 int ast_transfer(struct ast_channel *chan, char *dest)
2829 {
2830         int res = -1;
2831
2832         /* Stop if we're a zombie or need a soft hangup */
2833         ast_channel_lock(chan);
2834         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2835                 if (chan->tech->transfer) {
2836                         res = chan->tech->transfer(chan, dest);
2837                         if (!res)
2838                                 res = 1;
2839                 } else
2840                         res = 0;
2841         }
2842         ast_channel_unlock(chan);
2843         return res;
2844 }
2845
2846 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2847 {
2848         return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
2849 }
2850
2851 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2852 {
2853         int pos = 0;    /* index in the buffer where we accumulate digits */
2854         int to = ftimeout;
2855
2856         /* Stop if we're a zombie or need a soft hangup */
2857         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2858                 return -1;
2859         if (!len)
2860                 return -1;
2861         for (;;) {
2862                 int d;
2863                 if (c->stream) {
2864                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2865                         ast_stopstream(c);
2866                         usleep(1000);
2867                         if (!d)
2868                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2869                 } else {
2870                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2871                 }
2872                 if (d < 0)
2873                         return -1;
2874                 if (d == 0) {
2875                         s[pos]='\0';
2876                         return 1;
2877                 }
2878                 if (d == 1) {
2879                         s[pos]='\0';
2880                         return 2;
2881                 }
2882                 if (!strchr(enders, d))
2883                         s[pos++] = d;
2884                 if (strchr(enders, d) || (pos >= len)) {
2885                         s[pos]='\0';
2886                         return 0;
2887                 }
2888                 to = timeout;
2889         }
2890         /* Never reached */
2891         return 0;
2892 }
2893
2894 int ast_channel_supports_html(struct ast_channel *chan)
2895 {
2896         return (chan->tech->send_html) ? 1 : 0;
2897 }
2898
2899 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2900 {
2901         if (chan->tech->send_html)
2902                 return chan->tech->send_html(chan, subclass, data, datalen);
2903         return -1;
2904 }
2905
2906 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2907 {
2908         return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
2909 }
2910
2911 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2912 {
2913         int src;
2914         int dst;
2915
2916         /* Set up translation from the chan to the peer */
2917         src = chan->nativeformats;
2918         dst = peer->nativeformats;
2919         if (ast_translator_best_choice(&dst, &src) < 0) {
2920                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2921                 return -1;
2922         }
2923
2924         /* if the best path is not 'pass through', then
2925            transcoding is needed; if desired, force transcode path
2926            to use SLINEAR between channels, but only if there is
2927            no direct conversion available */
2928         if ((src != dst) && ast_opt_transcode_via_slin &&
2929             (ast_translate_path_steps(dst, src) != 1))
2930                 dst = AST_FORMAT_SLINEAR;
2931         if (ast_set_read_format(chan, dst) < 0) {
2932                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2933                 return -1;
2934         }
2935         if (ast_set_write_format(peer, dst) < 0) {
2936                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2937                 return -1;
2938         }
2939
2940         /* Set up translation from the peer to the chan */
2941         src = peer->nativeformats;
2942         dst = chan->nativeformats;
2943         if (ast_translator_best_choice(&dst, &src) < 0) {
2944                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2945                 return -1;
2946         }
2947
2948         /* if the best path is not 'pass through', then
2949            transcoding is needed; if desired, force transcode path
2950            to use SLINEAR between channels, but only if there is
2951            no direct conversion available */
2952         if ((src != dst) && ast_opt_transcode_via_slin &&
2953             (ast_translate_path_steps(dst, src) != 1))
2954                 dst = AST_FORMAT_SLINEAR;
2955         if (ast_set_read_format(peer, dst) < 0) {
2956                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2957                 return -1;
2958         }
2959         if (ast_set_write_format(chan, dst) < 0) {
2960                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2961                 return -1;
2962         }
2963         return 0;
2964 }
2965
2966 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2967 {
2968         int res = -1;
2969         struct ast_channel *final_orig = original, *final_clone = clone;
2970
2971         ast_channel_lock(original);
2972         while (ast_channel_trylock(clone)) {
2973                 ast_channel_unlock(original);
2974                 usleep(1);
2975                 ast_channel_lock(original);
2976         }
2977
2978         /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
2979            and if so, we don't really want to masquerade it, but its proxy */
2980         if (original->_bridge && (original->_bridge != ast_bridged_channel(original)))
2981                 final_orig = original->_bridge;
2982
2983         if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)))
2984                 final_clone = clone->_bridge;
2985
2986         if ((final_orig != original) || (final_clone != clone)) {
2987                 ast_channel_lock(final_orig);
2988                 while (ast_channel_trylock(final_clone)) {
2989                         ast_channel_unlock(final_orig);
2990                         usleep(1);
2991                         ast_channel_lock(final_orig);
2992                 }
2993                 ast_channel_unlock(clone);
2994                 ast_channel_unlock(original);
2995                 original = final_orig;
2996                 clone = final_clone;
2997         }
2998
2999         if (original == clone) {
3000                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3001                 ast_channel_unlock(clone);
3002                 ast_channel_unlock(original);
3003                 return -1;
3004         }
3005
3006         ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
3007                 clone->name, original->name);
3008         if (original->masq) {
3009                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3010                         original->masq->name, original->name);
3011         } else if (clone->masqr) {
3012                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3013                         clone->name, clone->masqr->name);
3014         } else {
3015                 original->masq = clone;
3016                 clone->masqr = original;
3017                 ast_queue_frame(original, &ast_null_frame);
3018                 ast_queue_frame(clone, &ast_null_frame);
3019                 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3020                 res = 0;
3021         }
3022
3023         ast_channel_unlock(clone);
3024         ast_channel_unlock(original);
3025
3026         return res;
3027 }
3028
3029 void ast_change_name(struct ast_channel *chan, char *newname)
3030 {
3031         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3032         ast_string_field_set(chan, name, newname);
3033 }
3034
3035 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3036 {
3037         struct ast_var_t *current, *newvar;
3038         const char *varname;
3039
3040         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3041                 int vartype = 0;
3042
3043                 varname = ast_var_full_name(current);
3044                 if (!varname)
3045                         continue;
3046
3047                 if (varname[0] == '_') {
3048                         vartype = 1;
3049                         if (varname[1] == '_')
3050                                 vartype = 2;
3051                 }
3052
3053                 switch (vartype) {
3054                 case 1:
3055                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
3056                         if (newvar) {
3057                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3058                                 if (option_debug)
3059                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3060                         }
3061                         break;
3062                 case 2:
3063                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
3064                         if (newvar) {
3065                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3066                                 if (option_debug)
3067                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3068                         }
3069                         break;
3070                 default:
3071                         if (option_debug)
3072                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
3073                         break;
3074                 }
3075         }
3076 }
3077
3078 /*!
3079   \brief Clone channel variables from 'clone' channel into 'original' channel
3080
3081   All variables except those related to app_groupcount are cloned.
3082   Variables are actually _removed_ from 'clone' channel, presumably
3083   because it will subsequently be destroyed.
3084
3085   \note Assumes locks will be in place on both channels when called.
3086 */
3087 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3088 {
3089         struct ast_var_t *varptr;
3090
3091         /* we need to remove all app_groupcount related variables from the original
3092            channel before merging in the clone's variables; any groups assigned to the
3093            original channel should be released, only those assigned to the clone
3094            should remain
3095         */
3096
3097         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
3098                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
3099                         AST_LIST_REMOVE_CURRENT(&original->varshead, entries);
3100                         ast_var_delete(varptr);
3101                 }
3102         }
3103         AST_LIST_TRAVERSE_SAFE_END;
3104
3105         /* Append variables from clone channel into original channel */
3106         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
3107         if (AST_LIST_FIRST(&clone->varshead))
3108                 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3109 }
3110
3111 /*!
3112   \brief Masquerade a channel
3113
3114   \note Assumes channel will be locked when called
3115 */
3116 int ast_do_masquerade(struct ast_channel *original)
3117 {
3118         int x,i;
3119         int res=0;
3120         int origstate;
3121         struct ast_frame *cur;
3122         const struct ast_channel_tech *t;
3123         void *t_pvt;
3124         struct ast_callerid tmpcid;
3125         struct ast_channel *clone = original->masq;
3126         int rformat = original->readformat;
3127         int wformat = original->writeformat;
3128         char newn[100];
3129         char orig[100];
3130         char masqn[100];
3131         char zombn[100];
3132
3133         if (option_debug > 3)
3134                 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3135                         clone->name, clone->_state, original->name, original->_state);
3136
3137         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
3138            the clone channel into the original channel.  Start by killing off the original
3139            channel's backend.   I'm not sure we're going to keep this function, because
3140            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3141
3142         /* We need the clone's lock, too */
3143         ast_channel_lock(clone);
3144
3145         if (option_debug > 1)
3146                 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3147
3148         /* Having remembered the original read/write formats, we turn off any translation on either
3149            one */
3150         free_translation(clone);
3151         free_translation(original);
3152
3153
3154         /* Unlink the masquerade */
3155         original->masq = NULL;
3156         clone->masqr = NULL;
3157         
3158         /* Save the original name */
3159         ast_copy_string(orig, original->name, sizeof(orig));
3160         /* Save the new name */
3161         ast_copy_string(newn, clone->name, sizeof(newn));
3162         /* Create the masq name */
3163         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3164                 
3165         /* Copy the name from the clone channel */
3166         ast_string_field_set(original, name, newn);
3167
3168         /* Mangle the name of the clone channel */
3169         ast_string_field_set(clone, name, masqn);
3170         
3171         /* Notify any managers of the change, first the masq then the other */
3172         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3173         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3174
3175         /* Swap the technologies */     
3176         t = original->tech;
3177         original->tech = clone->tech;
3178         clone->tech = t;
3179
3180         t_pvt = original->tech_pvt;
3181         original->tech_pvt = clone->tech_pvt;
3182         clone->tech_pvt = t_pvt;
3183
3184         /* Swap the readq's */
3185         cur = AST_LIST_FIRST(&original->readq);
3186         AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3187         AST_LIST_HEAD_SET_NOLOCK(&clone->readq, cur);
3188
3189         /* Swap the alertpipes */
3190         for (i = 0; i < 2; i++) {
3191                 x = original->alertpipe[i];
3192                 original->alertpipe[i] = clone->alertpipe[i];
3193                 clone->alertpipe[i] = x;
3194         }
3195
3196         /* Swap the raw formats */
3197         x = original->rawreadformat;
3198         original->rawreadformat = clone->rawreadformat;
3199         clone->rawreadformat = x;
3200         x = original->rawwriteformat;
3201         original->rawwriteformat = clone->rawwriteformat;
3202         clone->rawwriteformat = x;
3203
3204         /* Save any pending frames on both sides.  Start by counting
3205          * how many we're going to need... */
3206         x = 0;
3207         if (original->alertpipe[1] > -1) {
3208                 AST_LIST_TRAVERSE(&clone->readq, cur, frame_list)
3209                         x++;
3210         }
3211
3212         /* If we had any, prepend them to the ones already in the queue, and 
3213          * load up the alertpipe */
3214         if (AST_LIST_FIRST(&clone->readq)) {
3215                 AST_LIST_INSERT_TAIL(&clone->readq, AST_LIST_FIRST(&original->readq), frame_list);
3216                 AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3217                 AST_LIST_HEAD_SET_NOLOCK(&clone->readq, NULL);
3218                 for (i = 0; i < x; i++)
3219                         write(original->alertpipe[1], &x, sizeof(x));
3220         }
3221         
3222         clone->_softhangup = AST_SOFTHANGUP_DEV;
3223
3224
3225         /* And of course, so does our current state.  Note we need not
3226            call ast_setstate since the event manager doesn't really consider
3227            these separate.  We do this early so that the clone has the proper
3228            state of the original channel. */
3229         origstate = original->_state;
3230         original->_state = clone->_state;
3231         clone->_state = origstate;
3232
3233         if (clone->tech->fixup){
3234                 res = clone->tech->fixup(original, clone);
3235                 if (res)
3236                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3237         }
3238
3239         /* Start by disconnecting the original's physical side */
3240         if (clone->tech->hangup)
3241                 res = clone->tech->hangup(clone);
3242         if (res) {
3243                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
3244                 ast_channel_unlock(clone);
3245                 return -1;
3246         }
3247         
3248         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3249         /* Mangle the name of the clone channel */
3250         ast_string_field_set(clone, name, zombn);
3251         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3252
3253         /* Update the type. */
3254         t_pvt = original->monitor;
3255         original->monitor = clone->monitor;
3256         clone->monitor = t_pvt;
3257         
3258         /* Keep the same language.  */
3259         ast_string_field_set(original, language, clone->language);
3260         /* Copy the FD's other than the generator fd */
3261         for (x = 0; x < AST_MAX_FDS; x++) {
3262                 if (x != AST_GENERATOR_FD)
3263                         original->fds[x] = clone->fds[x];
3264         }
3265
3266         /* move any whisperer over */
3267         ast_channel_whisper_stop(original);
3268         if (ast_test_flag(clone, AST_FLAG_WHISPER)) {
3269                 original->whisper = clone->whisper;
3270                 ast_set_flag(original, AST_FLAG_WHISPER);
3271                 clone->whisper = NULL;
3272                 ast_clear_flag(clone, AST_FLAG_WHISPER);
3273         }
3274
3275         /* Move data stores over */
3276         if (AST_LIST_FIRST(&clone->datastores))
3277                 AST_LIST_INSERT_TAIL(&original->datastores, AST_LIST_FIRST(&clone->datastores), entry);
3278         AST_LIST_HEAD_INIT_NOLOCK(&clone->datastores);
3279
3280         clone_variables(original, clone);
3281         AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3282         /* Presense of ADSI capable CPE follows clone */
3283         original->adsicpe = clone->adsicpe;
3284         /* Bridge remains the same */
3285         /* CDR fields remain the same */
3286         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3287         /* Application and data remain the same */
3288         /* Clone exception  becomes real one, as with fdno */
3289         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3290         original->fdno = clone->fdno;
3291         /* Schedule context remains the same */
3292         /* Stream stuff stays the same */
3293         /* Keep the original state.  The fixup code will need to work with it most likely */
3294
3295         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3296            out. */
3297         tmpcid = original->cid;
3298         original->cid = clone->cid;
3299         clone->cid = tmpcid;
3300         
3301         /* Restore original timing file descriptor */
3302         original->fds[AST_TIMING_FD] = original->timingfd;
3303         
3304         /* Our native formats are different now */
3305         original->nativeformats = clone->nativeformats;
3306         
3307         /* Context, extension, priority, app data, jump table,  remain the same */
3308         /* pvt switches.  pbx stays the same, as does next */
3309         
3310         /* Set the write format */
3311         ast_set_write_format(original, wformat);
3312
3313         /* Set the read format */
3314         ast_set_read_format(original, rformat);
3315
3316         /* Copy the music class */
3317         ast_string_field_set(original, musicclass, clone->musicclass);
3318
3319         if (option_debug)
3320                 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3321
3322         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
3323            can fix up everything as best as possible */
3324         if (original->tech->fixup) {
3325                 res = original->tech->fixup(clone, original);
3326                 if (res) {
3327                         ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3328                                 original->tech->type, original->name);
3329                         ast_channel_unlock(clone);
3330                         return -1;
3331                 }
3332         } else
3333                 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
3334                         original->tech->type, original->name);
3335         
3336         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
3337            a zombie so nothing tries to touch it.  If it's already been marked as a
3338            zombie, then free it now (since it already is considered invalid). */
3339         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3340                 if (option_debug)
3341                         ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3342                 ast_channel_unlock(clone);
3343                 manager_event(EVENT_FLAG_CALL, "Hangup",
3344                         "Channel: %s\r\n"
3345                         "Uniqueid: %s\r\n"
3346                         "Cause: %d\r\n"
3347                         "Cause-txt: %s\r\n",
3348                         clone->name,
3349                         clone->uniqueid,
3350                         clone->hangupcause,
3351                         ast_cause2str(clone->hangupcause)
3352                         );
3353                 ast_channel_free(clone);
3354         } else {
3355                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3356                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3357                 ast_queue_frame(clone, &ast_null_frame);
3358                 ast_channel_unlock(clone);
3359         }
3360         
3361         /* Signal any blocker */
3362         if (ast_test_flag(original, AST_FLAG_BLOCKING))
3363                 pthread_kill(original->blocker, SIGURG);
3364         if (option_debug)
3365                 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3366         return 0;
3367 }
3368
3369 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3370 {
3371         if (callerid) {
3372                 if (chan->cid.cid_num)
3373                         free(chan->cid.cid_num);
3374                 chan->cid.cid_num = ast_strdup(callerid);
3375         }
3376         if (calleridname) {
3377                 if (chan->cid.cid_name)
3378                         free(chan->cid.cid_name);
3379                 chan->cid.cid_name = ast_strdup(calleridname);
3380         }
3381         if (ani) {
3382                 if (chan->cid.cid_ani)
3383                         free(chan->cid.cid_ani);
3384                 chan->cid.cid_ani = ast_strdup(ani);
3385         }
3386         if (chan->cdr)
3387                 ast_cdr_setcid(chan->cdr, chan);
3388         manager_event(EVENT_FLAG_CALL, "Newcallerid",
3389                                 "Channel: %s\r\n"
3390                                 "CallerID: %s\r\n"
3391                                 "CallerIDName: %s\r\n"
3392                                 "Uniqueid: %s\r\n"
3393                                 "CID-CallingPres: %d (%s)\r\n",
3394                                 chan->name,
3395                                 S_OR(chan->cid.cid_num, "<Unknown>"),
3396                                 S_OR(chan->cid.cid_name, "<Unknown>"),
3397                                 chan->uniqueid,
3398                                 chan->cid.cid_pres,
3399                                 ast_describe_caller_presentation(chan->cid.cid_pres)
3400                                 );
3401 }
3402
3403 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
3404 {
3405         int oldstate = chan->_state;
3406
3407         if (oldstate == state)
3408                 return 0;
3409
3410         chan->_state = state;
3411         ast_device_state_changed_literal(chan->name);
3412         manager_event(EVENT_FLAG_CALL,
3413                       (oldstate == AST_STATE_DOWN) ? "Newchannel" : "Newstate",
3414                       "Channel: %s\r\n"
3415                       "State: %s\r\n"
3416                       "CallerID: %s\r\n"
3417                       "CallerIDName: %s\r\n"
3418                       "Uniqueid: %s\r\n",
3419                       chan->name, ast_state2str(chan->_state),
3420                       S_OR(chan->cid.cid_num, "<unknown>"),
3421                       S_OR(chan->cid.cid_name, "<unknown>"),
3422                       chan->uniqueid);
3423
3424         return 0;
3425 }
3426
3427 /*! \brief Find bridged channel */
3428 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3429 {
3430         struct ast_channel *bridged;
3431         bridged = chan->_bridge;
3432         if (bridged && bridged->tech->bridged_channel)
3433                 bridged = bridged->tech->bridged_channel(chan, bridged);
3434         return bridged;
3435 }
3436
3437 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3438 {
3439         int min = 0, sec = 0, check;
3440
3441         check = ast_autoservice_start(peer);
3442         if (check)
3443                 return;
3444
3445         if (remain > 0) {
3446                 if (remain / 60 > 1) {
3447                         min = remain / 60;
3448                         sec = remain % 60;
3449                 } else {
3450                         sec = remain;
3451                 }
3452         }
3453         
3454         if (!strcmp(sound,"timeleft")) {        /* Queue support */
3455                 ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
3456                 if (min) {
3457                         ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
3458                         ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
3459                 }
3460                 if (sec) {
3461                         ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
3462                         ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
3463                 }
3464         } else {
3465                 ast_stream_and_wait(chan, sound, chan->language, "");
3466         }
3467
3468         ast_autoservice_stop(peer);
3469 }
3470
3471 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3472                                                  struct ast_bridge_config *config, struct ast_frame **fo,
3473                                                  struct ast_channel **rc, struct timeval bridge_end)
3474 {
3475         /* Copy voice back and forth between the two channels. */
3476         struct ast_channel *cs[3];
3477         struct ast_frame *f;
3478         enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3479         int o0nativeformats;
3480         int o1nativeformats;
3481         int watch_c0_dtmf;
3482         int watch_c1_dtmf;
3483         void *pvt0, *pvt1;
3484         /* Indicates whether a frame was queued into a jitterbuffer */
3485         int frame_put_in_jb = 0;
3486         int jb_in_use;
3487         int to;
3488         
3489         cs[0] = c0;
3490         cs[1] = c1;
3491         pvt0 = c0->tech_pvt;
3492         pvt1 = c1->tech_pvt;
3493         o0nativeformats = c0->nativeformats;
3494         o1nativeformats = c1->nativeformats;
3495         watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3496         watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3497
3498         /* Check the need of a jitterbuffer for each channel */
3499         jb_in_use = ast_jb_do_usecheck(c0, c1);
3500
3501         for (;;) {
3502                 struct ast_channel *who, *other;
3503
3504                 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3505                     (o0nativeformats != c0->nativeformats) ||
3506                     (o1nativeformats != c1->nativeformats)) {
3507                         /* Check for Masquerade, codec changes, etc */
3508                         res = AST_BRIDGE_RETRY;
3509                         break;
3510                 }
3511                 if (bridge_end.tv_sec) {
3512                         to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3513                         if (to <= 0) {
3514                                 res = AST_BRIDGE_RETRY;
3515                                 break;
3516                         }
3517                 } else
3518                         to = -1;
3519                 /* Calculate the appropriate max sleep interval - in general, this is the time,
3520                    left to the closest jb delivery moment */
3521                 if (jb_in_use)
3522                         to = ast_jb_get_when_to_wakeup(c0, c1, to);
3523                 who = ast_waitfor_n(cs, 2, &to);
3524                 if (!who) {
3525                         /* No frame received within the specified timeout - check if we have to deliver now */
3526                         if (jb_in_use)
3527                                 ast_jb_get_and_deliver(c0, c1);
3528                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3529                                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3530                                         c0->_softhangup = 0;
3531                                 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3532                                         c1->_softhangup = 0;
3533                                 c0->_bridge = c1;
3534                                 c1->_bridge = c0;
3535                         }
3536                         continue;
3537                 }
3538                 f = ast_read(who);
3539                 if (!f) {
3540                         *fo = NULL;
3541                         *rc = who;
3542                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3543                         break;
3544                 }
3545
3546                 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3547                 /* Try add the frame info the who's bridged channel jitterbuff */
3548                 if (jb_in_use)
3549                         frame_put_in_jb = !ast_jb_put(other, f);
3550
3551                 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3552                         int