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