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