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