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