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