Formatting fixes
[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, chan_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, chan_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, chan_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, chan_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, chan_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, 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         ast_string_field_free_all(chan);
1010         free(chan);
1011         AST_LIST_UNLOCK(&channels);
1012
1013         ast_device_state_changed_literal(name);
1014 }
1015
1016 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1017 {
1018         if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1019                 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1020                         spy->type, chan->name);
1021                 return -1;
1022         }
1023
1024         if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1025                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1026                         ast_getformatname(spy->read_queue.format));
1027                 return -1;
1028         }
1029
1030         if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1031                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1032                         ast_getformatname(spy->write_queue.format));
1033                 return -1;
1034         }
1035
1036         if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1037             ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1038              (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1039                 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1040                         ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1041                 return -1;
1042         }
1043
1044         if (!chan->spies) {
1045                 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1046                         return -1;
1047                 }
1048
1049                 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1050                 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1051         } else {
1052                 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1053         }
1054
1055         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1056                 ast_cond_init(&spy->trigger, NULL);
1057                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1058                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1059         }
1060
1061         ast_log(LOG_DEBUG, "Spy %s added to channel %s\n",
1062                 spy->type, chan->name);
1063
1064         return 0;
1065 }
1066
1067 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1068 {
1069         struct ast_channel_spy *spy;
1070         
1071         if (!chan->spies)
1072                 return;
1073
1074         AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1075                 ast_mutex_lock(&spy->lock);
1076                 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1077                         spy->status = CHANSPY_STOP;
1078                         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1079                                 ast_cond_signal(&spy->trigger);
1080                 }
1081                 ast_mutex_unlock(&spy->lock);
1082         }
1083 }
1084
1085 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1086 {
1087         ast_cond_wait(&spy->trigger, &spy->lock);
1088 }
1089
1090 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1091 {
1092         struct ast_frame *f;
1093
1094         if (!chan->spies)
1095                 return;
1096
1097         AST_LIST_REMOVE(&chan->spies->list, spy, list);
1098
1099         ast_mutex_lock(&spy->lock);
1100
1101         for (f = spy->read_queue.head; f; f = spy->read_queue.head) {
1102                 spy->read_queue.head = f->next;
1103                 ast_frfree(f);
1104         }
1105         for (f = spy->write_queue.head; f; f = spy->write_queue.head) {
1106                 spy->write_queue.head = f->next;
1107                 ast_frfree(f);
1108         }
1109
1110         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1111                 ast_cond_destroy(&spy->trigger);
1112
1113         ast_mutex_unlock(&spy->lock);
1114
1115         ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n",
1116                 spy->type, chan->name);
1117
1118         if (AST_LIST_EMPTY(&chan->spies->list)) {
1119                 if (chan->spies->read_translator.path)
1120                         ast_translator_free_path(chan->spies->read_translator.path);
1121                 if (chan->spies->write_translator.path)
1122                         ast_translator_free_path(chan->spies->write_translator.path);
1123                 free(chan->spies);
1124                 chan->spies = NULL;
1125         }
1126 }
1127
1128 static void detach_spies(struct ast_channel *chan) 
1129 {
1130         struct ast_channel_spy *spy;
1131
1132         if (!chan->spies)
1133                 return;
1134
1135         /* Marking the spies as done is sufficient.  Chanspy or spy users will get the picture. */
1136         AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1137                 ast_mutex_lock(&spy->lock);
1138                 if (spy->status == CHANSPY_RUNNING)
1139                         spy->status = CHANSPY_DONE;
1140                 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1141                         ast_cond_signal(&spy->trigger);
1142                 ast_mutex_unlock(&spy->lock);
1143         }
1144
1145         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list)
1146                 ast_channel_spy_remove(chan, spy);
1147         AST_LIST_TRAVERSE_SAFE_END;
1148 }
1149
1150 /*! \brief Softly hangup a channel, don't lock */
1151 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1152 {
1153         int res = 0;
1154         struct ast_frame f = { AST_FRAME_NULL };
1155         if (option_debug)
1156                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1157         /* Inform channel driver that we need to be hung up, if it cares */
1158         chan->_softhangup |= cause;
1159         ast_queue_frame(chan, &f);
1160         /* Interrupt any poll call or such */
1161         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1162                 pthread_kill(chan->blocker, SIGURG);
1163         return res;
1164 }
1165
1166 /*! \brief Softly hangup a channel, lock */
1167 int ast_softhangup(struct ast_channel *chan, int cause)
1168 {
1169         int res;
1170         ast_mutex_lock(&chan->lock);
1171         res = ast_softhangup_nolock(chan, cause);
1172         ast_mutex_unlock(&chan->lock);
1173         return res;
1174 }
1175
1176 enum spy_direction {
1177         SPY_READ,
1178         SPY_WRITE,
1179 };
1180
1181 #define SPY_QUEUE_SAMPLE_LIMIT 4000                     /* half of one second */
1182
1183 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1184 {
1185         struct ast_frame *translated_frame = NULL;
1186         struct ast_channel_spy *spy;
1187         struct ast_channel_spy_queue *queue;
1188         struct ast_channel_spy_queue *other_queue;
1189         struct channel_spy_trans *trans;
1190         struct ast_frame *last;
1191
1192         trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1193
1194         AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1195                 ast_mutex_lock(&spy->lock);
1196
1197                 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1198
1199                 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1200                         if (!translated_frame) {
1201                                 if (trans->path && (trans->last_format != f->subclass)) {
1202                                         ast_translator_free_path(trans->path);
1203                                         trans->path = NULL;
1204                                 }
1205                                 if (!trans->path) {
1206                                         ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1207                                                 ast_getformatname(f->subclass), chan->name);
1208                                         if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1209                                                 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1210                                                         ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1211                                                 ast_mutex_unlock(&spy->lock);
1212                                                 continue;
1213                                         } else {
1214                                                 trans->last_format = f->subclass;
1215                                         }
1216                                 }
1217                                 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1218                                         ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1219                                                 ast_getformatname(AST_FORMAT_SLINEAR));
1220                                         ast_mutex_unlock(&spy->lock);
1221                                         break;
1222                                 }
1223                         }
1224
1225                         for (last = queue->head; last && last->next; last = last->next);
1226                         if (last)
1227                                 last->next = ast_frdup(translated_frame);
1228                         else
1229                                 queue->head = ast_frdup(translated_frame);
1230                 } else {
1231                         if (f->subclass != queue->format) {
1232                                 ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1233                                         spy->type, chan->name,
1234                                         ast_getformatname(queue->format), ast_getformatname(f->subclass));
1235                                 ast_mutex_unlock(&spy->lock);
1236                                 continue;
1237                         }
1238
1239                         for (last = queue->head; last && last->next; last = last->next);
1240                         if (last)
1241                                 last->next = ast_frdup(f);
1242                         else
1243                                 queue->head = ast_frdup(f);
1244                 }
1245
1246                 queue->samples += f->samples;
1247
1248                 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1249                         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1250                                 other_queue = (dir == SPY_WRITE) ? &spy->read_queue : &spy->write_queue;
1251
1252                                 if (other_queue->samples == 0) {
1253                                         switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1254                                         case CHANSPY_TRIGGER_READ:
1255                                                 if (dir == SPY_WRITE) {
1256                                                         ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1257                                                         ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1258                                                         if (option_debug)
1259                                                                 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1260                                                                         spy->type, chan->name);
1261                                                 }
1262                                                 break;
1263                                         case CHANSPY_TRIGGER_WRITE:
1264                                                 if (dir == SPY_READ) {
1265                                                         ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1266                                                         ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1267                                                         if (option_debug)
1268                                                                 ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1269                                                                         spy->type, chan->name);
1270                                                 }
1271                                                 break;
1272                                         }
1273                                         if (option_debug)
1274                                                 ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1275                                                         spy->type, chan->name);
1276                                         ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1277                                         ast_cond_signal(&spy->trigger);
1278                                         ast_mutex_unlock(&spy->lock);
1279                                         continue;
1280                                 }
1281                         }
1282
1283                         if (option_debug)
1284                                 ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1285                                         spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1286                         while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1287                                 struct ast_frame *drop = queue->head;
1288
1289                                 queue->samples -= drop->samples;
1290                                 queue->head = drop->next;
1291                                 ast_frfree(drop);
1292                         }
1293                 } else {
1294                         switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1295                         case CHANSPY_TRIGGER_READ:
1296                                 if (dir == SPY_READ)
1297                                         ast_cond_signal(&spy->trigger);
1298                                 break;
1299                         case CHANSPY_TRIGGER_WRITE:
1300                                 if (dir == SPY_WRITE)
1301                                         ast_cond_signal(&spy->trigger);
1302                                 break;
1303                         }
1304                 }
1305
1306                 ast_mutex_unlock(&spy->lock);
1307         }
1308
1309         if (translated_frame)
1310                 ast_frfree(translated_frame);
1311 }
1312
1313 static void free_translation(struct ast_channel *clone)
1314 {
1315         if (clone->writetrans)
1316                 ast_translator_free_path(clone->writetrans);
1317         if (clone->readtrans)
1318                 ast_translator_free_path(clone->readtrans);
1319         clone->writetrans = NULL;
1320         clone->readtrans = NULL;
1321         clone->rawwriteformat = clone->nativeformats;
1322         clone->rawreadformat = clone->nativeformats;
1323 }
1324
1325 /*! \brief Hangup a channel */
1326 int ast_hangup(struct ast_channel *chan)
1327 {
1328         int res = 0;
1329
1330         /* Don't actually hang up a channel that will masquerade as someone else, or
1331            if someone is going to masquerade as us */
1332         ast_mutex_lock(&chan->lock);
1333
1334         detach_spies(chan);             /* get rid of spies */
1335
1336         if (chan->masq) {
1337                 if (ast_do_masquerade(chan)) 
1338                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1339         }
1340
1341         if (chan->masq) {
1342                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1343                 ast_mutex_unlock(&chan->lock);
1344                 return 0;
1345         }
1346         /* If this channel is one which will be masqueraded into something, 
1347            mark it as a zombie already, so we know to free it later */
1348         if (chan->masqr) {
1349                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1350                 ast_mutex_unlock(&chan->lock);
1351                 return 0;
1352         }
1353         free_translation(chan);
1354         if (chan->stream)               /* Close audio stream */
1355                 ast_closestream(chan->stream);
1356         if (chan->vstream)              /* Close video stream */
1357                 ast_closestream(chan->vstream);
1358         if (chan->sched) {
1359                 sched_context_destroy(chan->sched);
1360                 chan->sched = NULL;
1361         }
1362         
1363         if (chan->generatordata)        /* Clear any tone stuff remaining */ 
1364                 chan->generator->release(chan, chan->generatordata);
1365         chan->generatordata = NULL;
1366         chan->generator = NULL;
1367         if (chan->cdr) {                /* End the CDR if it hasn't already */ 
1368                 ast_cdr_end(chan->cdr);
1369                 ast_cdr_detach(chan->cdr);      /* Post and Free the CDR */ 
1370                 chan->cdr = NULL;
1371         }
1372         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1373                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1374                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1375                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1376                 CRASH;
1377         }
1378         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1379                 if (option_debug)
1380                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1381                 if (chan->tech->hangup)
1382                         res = chan->tech->hangup(chan);
1383         } else {
1384                 if (option_debug)
1385                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1386         }
1387                         
1388         ast_mutex_unlock(&chan->lock);
1389         manager_event(EVENT_FLAG_CALL, "Hangup", 
1390                         "Channel: %s\r\n"
1391                         "Uniqueid: %s\r\n"
1392                         "Cause: %d\r\n"
1393                         "Cause-txt: %s\r\n",
1394                         chan->name, 
1395                         chan->uniqueid, 
1396                         chan->hangupcause,
1397                         ast_cause2str(chan->hangupcause)
1398                         );
1399         ast_channel_free(chan);
1400         return res;
1401 }
1402
1403 int ast_answer(struct ast_channel *chan)
1404 {
1405         int res = 0;
1406         ast_mutex_lock(&chan->lock);
1407         /* Stop if we're a zombie or need a soft hangup */
1408         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1409                 ast_mutex_unlock(&chan->lock);
1410                 return -1;
1411         }
1412         switch(chan->_state) {
1413         case AST_STATE_RINGING:
1414         case AST_STATE_RING:
1415                 if (chan->tech->answer)
1416                         res = chan->tech->answer(chan);
1417                 ast_setstate(chan, AST_STATE_UP);
1418                 if (chan->cdr)
1419                         ast_cdr_answer(chan->cdr);
1420                 ast_mutex_unlock(&chan->lock);
1421                 return res;
1422                 break;
1423         case AST_STATE_UP:
1424                 if (chan->cdr)
1425                         ast_cdr_answer(chan->cdr);
1426                 break;
1427         }
1428         ast_mutex_unlock(&chan->lock);
1429         return 0;
1430 }
1431
1432 void ast_deactivate_generator(struct ast_channel *chan)
1433 {
1434         ast_mutex_lock(&chan->lock);
1435         if (chan->generatordata) {
1436                 if (chan->generator && chan->generator->release) 
1437                         chan->generator->release(chan, chan->generatordata);
1438                 chan->generatordata = NULL;
1439                 chan->generator = NULL;
1440                 chan->fds[AST_GENERATOR_FD] = -1;
1441                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1442                 ast_settimeout(chan, 0, NULL, NULL);
1443         }
1444         ast_mutex_unlock(&chan->lock);
1445 }
1446
1447 static int generator_force(void *data)
1448 {
1449         /* Called if generator doesn't have data */
1450         void *tmp;
1451         int res;
1452         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1453         struct ast_channel *chan = data;
1454         tmp = chan->generatordata;
1455         chan->generatordata = NULL;
1456         generate = chan->generator->generate;
1457         res = generate(chan, tmp, 0, 160);
1458         chan->generatordata = tmp;
1459         if (res) {
1460                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1461                 ast_deactivate_generator(chan);
1462         }
1463         return 0;
1464 }
1465
1466 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1467 {
1468         int res = 0;
1469
1470         ast_mutex_lock(&chan->lock);
1471
1472         if (chan->generatordata) {
1473                 if (chan->generator && chan->generator->release)
1474                         chan->generator->release(chan, chan->generatordata);
1475                 chan->generatordata = NULL;
1476         }
1477
1478         ast_prod(chan);
1479         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1480                 res = -1;
1481         }
1482         
1483         if (!res) {
1484                 ast_settimeout(chan, 160, generator_force, chan);
1485                 chan->generator = gen;
1486         }
1487
1488         ast_mutex_unlock(&chan->lock);
1489
1490         return res;
1491 }
1492
1493 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1494 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1495 {
1496         int winner = -1;
1497         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1498         return winner;
1499 }
1500
1501 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1502 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds, 
1503         int *exception, int *outfd, int *ms)
1504 {
1505         struct timeval start = { 0 , 0 };
1506         struct pollfd *pfds;
1507         int res;
1508         long rms;
1509         int x, y, max;
1510         int sz;
1511         time_t now = 0;
1512         long whentohangup = 0, diff;
1513         struct ast_channel *winner = NULL;
1514         struct fdmap {
1515                 int chan;
1516                 int fdno;
1517         } *fdmap;
1518
1519         sz = n * AST_MAX_FDS + nfds;
1520         if (!(pfds = alloca(sizeof(*pfds) * sz)) || !(fdmap = alloca(sizeof(*fdmap) * sz))) {
1521                 ast_log(LOG_ERROR, "Out of memory\n");
1522                 *outfd = -1;
1523                 return NULL;
1524         }
1525
1526         if (outfd)
1527                 *outfd = -99999;
1528         if (exception)
1529                 *exception = 0;
1530         
1531         /* Perform any pending masquerades */
1532         for (x=0; x < n; x++) {
1533                 ast_mutex_lock(&c[x]->lock);
1534                 if (c[x]->masq) {
1535                         if (ast_do_masquerade(c[x])) {
1536                                 ast_log(LOG_WARNING, "Masquerade failed\n");
1537                                 *ms = -1;
1538                                 ast_mutex_unlock(&c[x]->lock);
1539                                 return NULL;
1540                         }
1541                 }
1542                 if (c[x]->whentohangup) {
1543                         if (!whentohangup)
1544                                 time(&now);
1545                         diff = c[x]->whentohangup - now;
1546                         if (diff < 1) {
1547                                 /* Should already be hungup */
1548                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1549                                 ast_mutex_unlock(&c[x]->lock);
1550                                 return c[x];
1551                         }
1552                         if (!whentohangup || (diff < whentohangup))
1553                                 whentohangup = diff;
1554                 }
1555                 ast_mutex_unlock(&c[x]->lock);
1556         }
1557         /* Wait full interval */
1558         rms = *ms;
1559         if (whentohangup) {
1560                 rms = (whentohangup - now) * 1000;      /* timeout in milliseconds */
1561                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1562                         rms =  *ms;
1563         }
1564         /*
1565          * Build the pollfd array, putting the channels' fds first,
1566          * followed by individual fds. Order is important because
1567          * individual fd's must have priority over channel fds.
1568          */
1569         max = 0;
1570         for (x=0; x<n; x++) {
1571                 for (y=0; y<AST_MAX_FDS; y++) {
1572                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1573                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1574                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1575                 }
1576                 CHECK_BLOCKING(c[x]);
1577         }
1578         /* Add the individual fds */
1579         for (x=0; x<nfds; x++) {
1580                 fdmap[max].chan = -1;
1581                 max += ast_add_fd(&pfds[max], fds[x]);
1582         }
1583
1584         if (*ms > 0) 
1585                 start = ast_tvnow();
1586         
1587         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1588                 do {
1589                         int kbrms = rms;
1590                         if (kbrms > 600000)
1591                                 kbrms = 600000;
1592                         res = poll(pfds, max, kbrms);
1593                         if (!res)
1594                                 rms -= kbrms;
1595                 } while (!res && (rms > 0));
1596         } else {
1597                 res = poll(pfds, max, rms);
1598         }
1599         for (x=0; x<n; x++)
1600                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1601         if (res < 0) { /* Simulate a timeout if we were interrupted */
1602                 if (errno != EINTR)
1603                         *ms = -1;
1604                 return NULL;
1605         }
1606         if (whentohangup) {   /* if we have a timeout, check who expired */
1607                 time(&now);
1608                 for (x=0; x<n; x++) {
1609                         if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1610                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1611                                 if (winner == NULL)
1612                                         winner = c[x];
1613                         }
1614                 }
1615         }
1616         if (res == 0) { /* no fd ready, reset timeout and done */
1617                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1618                 return winner;
1619         }
1620         /*
1621          * Then check if any channel or fd has a pending event.
1622          * Remember to check channels first and fds last, as they
1623          * must have priority on setting 'winner'
1624          */
1625         for (x = 0; x < max; x++) {
1626                 res = pfds[x].revents;
1627                 if (res == 0)
1628                         continue;
1629                 if (fdmap[x].chan >= 0) {       /* this is a channel */
1630                         winner = c[fdmap[x].chan];      /* override previous winners */
1631                         if (res & POLLPRI)
1632                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1633                         else
1634                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1635                         winner->fdno = fdmap[x].fdno;
1636                 } else {                        /* this is an fd */
1637                         if (outfd)
1638                                 *outfd = pfds[x].fd;
1639                         if (exception)
1640                                 *exception = (res & POLLPRI) ? -1 : 0;
1641                         winner = NULL;
1642                 }
1643         }
1644         if (*ms > 0) {
1645                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1646                 if (*ms < 0)
1647                         *ms = 0;
1648         }
1649         return winner;
1650 }
1651
1652 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1653 {
1654         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1655 }
1656
1657 int ast_waitfor(struct ast_channel *c, int ms)
1658 {
1659         int oldms = ms;
1660
1661         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1662         if ((ms < 0) && (oldms < 0))
1663                 ms = 0;
1664         return ms;
1665 }
1666
1667 int ast_waitfordigit(struct ast_channel *c, int ms)
1668 {
1669         /* XXX Should I be merged with waitfordigit_full XXX */
1670         struct ast_frame *f;
1671         int result = 0;
1672
1673         /* Stop if we're a zombie or need a soft hangup */
1674         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
1675                 return -1;
1676
1677         /* Wait for a digit, no more than ms milliseconds total. */
1678         while(ms && !result) {
1679                 ms = ast_waitfor(c, ms);
1680                 if (ms < 0) /* Error */
1681                         result = -1; 
1682                 else if (ms > 0) {
1683                         /* Read something */
1684                         f = ast_read(c);
1685                         if (f) {
1686                                 if (f->frametype == AST_FRAME_DTMF) 
1687                                         result = f->subclass;
1688                                 ast_frfree(f);
1689                         } else
1690                                 result = -1;
1691                 }
1692         }
1693         return result;
1694 }
1695
1696 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1697 {
1698         int res = -1;
1699 #ifdef ZAPTEL_OPTIMIZATIONS
1700         if (c->timingfd > -1) {
1701                 if (!func) {
1702                         samples = 0;
1703                         data = 0;
1704                 }
1705                 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1706                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1707                 c->timingfunc = func;
1708                 c->timingdata = data;
1709         }
1710 #endif  
1711         return res;
1712 }
1713
1714 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1715 {
1716         struct ast_frame *f;
1717         struct ast_channel *rchan;
1718         int outfd;
1719         int res;
1720
1721         /* Stop if we're a zombie or need a soft hangup */
1722         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
1723                 return -1;
1724         /* Wait for a digit, no more than ms milliseconds total. */
1725         while(ms) {
1726                 errno = 0;
1727                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1728                 if ((!rchan) && (outfd < 0) && (ms)) { 
1729                         if (errno == 0 || errno == EINTR)
1730                                 continue;
1731                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1732                         return -1;
1733                 } else if (outfd > -1) {
1734                         /* The FD we were watching has something waiting */
1735                         return 1;
1736                 } else if (rchan) {
1737                         f = ast_read(c);
1738                         if(!f) {
1739                                 return -1;
1740                         }
1741
1742                         switch(f->frametype) {
1743                         case AST_FRAME_DTMF:
1744                                 res = f->subclass;
1745                                 ast_frfree(f);
1746                                 return res;
1747                         case AST_FRAME_CONTROL:
1748                                 switch(f->subclass) {
1749                                 case AST_CONTROL_HANGUP:
1750                                         ast_frfree(f);
1751                                         return -1;
1752                                 case AST_CONTROL_RINGING:
1753                                 case AST_CONTROL_ANSWER:
1754                                         /* Unimportant */
1755                                         break;
1756                                 default:
1757                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1758                                 }
1759                         case AST_FRAME_VOICE:
1760                                 /* Write audio if appropriate */
1761                                 if (audiofd > -1)
1762                                         write(audiofd, f->data, f->datalen);
1763                         }
1764                         /* Ignore */
1765                         ast_frfree(f);
1766                 }
1767         }
1768         return 0; /* Time is up */
1769 }
1770
1771 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1772 {
1773         struct ast_frame *f = NULL;
1774         int blah;
1775         int prestate;
1776 #ifdef ZAPTEL_OPTIMIZATIONS
1777         int (*func)(void *);
1778         void *data;
1779         int res;
1780 #endif
1781         ast_mutex_lock(&chan->lock);
1782         if (chan->masq) {
1783                 if (ast_do_masquerade(chan)) {
1784                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1785                         f = NULL;
1786                 } else
1787                         f =  &ast_null_frame;
1788                 ast_mutex_unlock(&chan->lock);
1789                 return f;
1790         }
1791
1792         /* Stop if we're a zombie or need a soft hangup */
1793         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1794                 if (chan->generator)
1795                         ast_deactivate_generator(chan);
1796                 ast_mutex_unlock(&chan->lock);
1797                 return NULL;
1798         }
1799         prestate = chan->_state;
1800
1801         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1802                 /* We have DTMF that has been deferred.  Return it now */
1803                 chan->dtmff.frametype = AST_FRAME_DTMF;
1804                 chan->dtmff.subclass = chan->dtmfq[0];
1805                 /* Drop first digit */
1806                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1807                 ast_mutex_unlock(&chan->lock);
1808                 return &chan->dtmff;
1809         }
1810         
1811         /* Read and ignore anything on the alertpipe, but read only
1812            one sizeof(blah) per frame that we send from it */
1813         if (chan->alertpipe[0] > -1) {
1814                 read(chan->alertpipe[0], &blah, sizeof(blah));
1815         }
1816 #ifdef ZAPTEL_OPTIMIZATIONS
1817         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1818                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1819                 blah = -1;
1820                 /* IF we can't get event, assume it's an expired as-per the old interface */
1821                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1822                 if (res) 
1823                         blah = ZT_EVENT_TIMER_EXPIRED;
1824
1825                 if (blah == ZT_EVENT_TIMER_PING) {
1826 #if 0
1827                         ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1828 #endif                  
1829                         if (!chan->readq || !chan->readq->next) {
1830                                 /* Acknowledge PONG unless we need it again */
1831 #if 0
1832                                 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1833 #endif                          
1834                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1835                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1836                                 }
1837                         }
1838                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1839                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1840                         func = chan->timingfunc;
1841                         data = chan->timingdata;
1842                         ast_mutex_unlock(&chan->lock);
1843                         if (func) {
1844 #if 0
1845                                 ast_log(LOG_DEBUG, "Calling private function\n");
1846 #endif                  
1847                                 func(data);
1848                         } else {
1849                                 blah = 0;
1850                                 ast_mutex_lock(&chan->lock);
1851                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1852                                 chan->timingdata = NULL;
1853                                 ast_mutex_unlock(&chan->lock);
1854                         }
1855                         return &ast_null_frame;
1856                 } else
1857                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1858         } else
1859 #endif
1860         /* Check for AST_GENERATOR_FD if not null.  If so, call generator with -1
1861            arguments now so it can do whatever it needs to. */
1862         if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
1863                 void *tmp = chan->generatordata;
1864                 chan->generatordata = NULL;     /* reset to let ast_write get through */
1865                 chan->generator->generate(chan, tmp, -1, -1);
1866                 chan->generatordata = tmp;
1867                 return &ast_null_frame;
1868         }
1869
1870         /* Check for pending read queue */
1871         if (chan->readq) {
1872                 f = chan->readq;
1873                 chan->readq = f->next;
1874                 f->next = NULL;
1875                 /* Interpret hangup and return NULL */
1876                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1877                         ast_frfree(f);
1878                         f = NULL;
1879                 }
1880         } else {
1881                 chan->blocker = pthread_self();
1882                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1883                         if (chan->tech->exception) 
1884                                 f = chan->tech->exception(chan);
1885                         else {
1886                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1887                                 f = &ast_null_frame;
1888                         }
1889                         /* Clear the exception flag */
1890                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1891                 } else {
1892                         if (chan->tech->read)
1893                                 f = chan->tech->read(chan);
1894                         else
1895                                 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1896                 }
1897         }
1898
1899         if (f) {
1900                 /* if the channel driver returned more than one frame, stuff the excess
1901                    into the readq for the next ast_read call
1902                 */
1903                 if (f->next) {
1904                         chan->readq = f->next;
1905                         f->next = NULL;
1906                 }
1907
1908                 switch (f->frametype) {
1909                 case AST_FRAME_CONTROL:
1910                         if (f->subclass == AST_CONTROL_ANSWER) {
1911                                 if (prestate == AST_STATE_UP) {
1912                                         ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1913                                         f = &ast_null_frame;
1914                                 }
1915                                 /* Answer the CDR */
1916                                 ast_setstate(chan, AST_STATE_UP);
1917                                 ast_cdr_answer(chan->cdr);
1918                         }
1919                         break;
1920                 case AST_FRAME_DTMF:
1921                         ast_log(LOG_DTMF, "DTMF '%c' received on %s\n", f->subclass, chan->name);
1922                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF)) {
1923                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1924                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1925                                 else
1926                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1927                                 f = &ast_null_frame;
1928                         }
1929                         break;
1930                 case AST_FRAME_DTMF_BEGIN:
1931                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
1932                         break;
1933                 case AST_FRAME_DTMF_END:
1934                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s\n", f->subclass, chan->name);
1935                         break;
1936                 case AST_FRAME_VOICE:
1937                         if (dropaudio) {
1938                                 ast_frfree(f);
1939                                 f = &ast_null_frame;
1940                         } else if (!(f->subclass & chan->nativeformats)) {
1941                                 /* This frame can't be from the current native formats -- drop it on the
1942                                    floor */
1943                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
1944                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
1945                                 ast_frfree(f);
1946                                 f = &ast_null_frame;
1947                         } else {
1948                                 if (chan->spies)
1949                                         queue_frame_to_spies(chan, f, SPY_READ);
1950                                 
1951                                 if (chan->monitor && chan->monitor->read_stream ) {
1952 #ifndef MONITOR_CONSTANT_DELAY
1953                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
1954                                         if (jump >= 0) {
1955                                                 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1956                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1957                                                 chan->insmpl += jump + 4 * f->samples;
1958                                         } else
1959                                                 chan->insmpl+= f->samples;
1960 #else
1961                                         int jump = chan->outsmpl - chan->insmpl;
1962                                         if (jump - MONITOR_DELAY >= 0) {
1963                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1964                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1965                                                 chan->insmpl += jump;
1966                                         } else
1967                                                 chan->insmpl += f->samples;
1968 #endif
1969                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
1970                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1971                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1972                                         }
1973                                 }
1974
1975                                 if (chan->readtrans) {
1976                                         if (!(f = ast_translate(chan->readtrans, f, 1)))
1977                                                 f = &ast_null_frame;
1978                                 }
1979
1980                                 /* Run generator sitting on the line if timing device not available
1981                                 * and synchronous generation of outgoing frames is necessary       */
1982                                 if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
1983                                         void *tmp;
1984                                         int res;
1985                                         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1986
1987                                         if (chan->timingfunc) {
1988                                                 if (option_debug > 1)
1989                                                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1990                                                 ast_settimeout(chan, 0, NULL, NULL);
1991                                         }
1992
1993                                         tmp = chan->generatordata;
1994                                         chan->generatordata = NULL;
1995                                         generate = chan->generator->generate;
1996                                         res = generate(chan, tmp, f->datalen, f->samples);
1997                                         chan->generatordata = tmp;
1998                                         if (res) {
1999                                                 if (option_debug > 1)
2000                                                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2001                                                 ast_deactivate_generator(chan);
2002                                         }
2003
2004                                 } else if (f->frametype == AST_FRAME_CNG) {
2005                                         if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2006                                                 if (option_debug > 1)
2007                                                         ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2008                                                 ast_settimeout(chan, 160, generator_force, chan);
2009                                         }
2010                                 }
2011                         }
2012                 }
2013         } else {
2014                 /* Make sure we always return NULL in the future */
2015                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2016                 if (chan->generator)
2017                         ast_deactivate_generator(chan);
2018                 /* End the CDR if appropriate */
2019                 if (chan->cdr)
2020                         ast_cdr_end(chan->cdr);
2021         }
2022
2023         /* High bit prints debugging */
2024         if (chan->fin & 0x80000000)
2025                 ast_frame_dump(chan->name, f, "<<");
2026         if ((chan->fin & 0x7fffffff) == 0x7fffffff)
2027                 chan->fin &= 0x80000000;
2028         else
2029                 chan->fin++;
2030         ast_mutex_unlock(&chan->lock);
2031
2032         return f;
2033 }
2034
2035 int ast_internal_timing_enabled(struct ast_channel *chan)
2036 {
2037         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2038         if (option_debug > 3) 
2039                 ast_log(LOG_DEBUG, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2040         return ret;
2041 }
2042
2043 struct ast_frame *ast_read(struct ast_channel *chan)
2044 {
2045         return __ast_read(chan, 0);
2046 }
2047
2048 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2049 {
2050         return __ast_read(chan, 1);
2051 }
2052
2053 int ast_indicate(struct ast_channel *chan, int condition)
2054 {
2055         int res = -1;
2056
2057         ast_mutex_lock(&chan->lock);
2058         /* Stop if we're a zombie or need a soft hangup */
2059         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2060                 ast_mutex_unlock(&chan->lock);
2061                 return -1;
2062         }
2063         if (chan->tech->indicate)
2064                 res = chan->tech->indicate(chan, condition);
2065         ast_mutex_unlock(&chan->lock);
2066         if (!chan->tech->indicate || res) {
2067                 /*
2068                  * Device does not support (that) indication, lets fake
2069                  * it by doing our own tone generation. (PM2002)
2070                  */
2071                 if (condition >= 0) {
2072                         const struct tone_zone_sound *ts = NULL;
2073                         switch (condition) {
2074                         case AST_CONTROL_RINGING:
2075                                 ts = ast_get_indication_tone(chan->zone, "ring");
2076                                 break;
2077                         case AST_CONTROL_BUSY:
2078                                 ts = ast_get_indication_tone(chan->zone, "busy");
2079                                 break;
2080                         case AST_CONTROL_CONGESTION:
2081                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2082                                 break;
2083                         }
2084                         if (ts && ts->data[0]) {
2085                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2086                                 ast_playtones_start(chan,0,ts->data, 1);
2087                                 res = 0;
2088                         } else if (condition == AST_CONTROL_PROGRESS) {
2089                                 /* ast_playtones_stop(chan); */
2090                         } else if (condition == AST_CONTROL_PROCEEDING) {
2091                                 /* Do nothing, really */
2092                         } else if (condition == AST_CONTROL_HOLD) {
2093                                 /* Do nothing.... */
2094                         } else if (condition == AST_CONTROL_UNHOLD) {
2095                                 /* Do nothing.... */
2096                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2097                                 /* Do nothing.... */
2098                         } else {
2099                                 /* not handled */
2100                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2101                                 res = -1;
2102                         }
2103                 }
2104                 else ast_playtones_stop(chan);
2105         }
2106         return res;
2107 }
2108
2109 int ast_recvchar(struct ast_channel *chan, int timeout)
2110 {
2111         int c;
2112         char *buf = ast_recvtext(chan, timeout);
2113         if (buf == NULL)
2114                 return -1;      /* error or timeout */
2115         c = *(unsigned char *)buf;
2116         free(buf);
2117         return c;
2118 }
2119
2120 char *ast_recvtext(struct ast_channel *chan, int timeout)
2121 {
2122         int res, done = 0;
2123         char *buf = NULL;
2124         
2125         while (!done) {
2126                 struct ast_frame *f;
2127                 if (ast_check_hangup(chan))
2128                         break;
2129                 res = ast_waitfor(chan, timeout);
2130                 if (res <= 0) /* timeout or error */
2131                         break;
2132                 timeout = res;  /* update timeout */
2133                 f = ast_read(chan);
2134                 if (f == NULL)
2135                         break; /* no frame */
2136                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2137                         done = 1;       /* force a break */
2138                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2139                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2140                         done = 1;
2141                 }
2142                 ast_frfree(f);
2143         }
2144         return buf;
2145 }
2146
2147 int ast_sendtext(struct ast_channel *chan, const char *text)
2148 {
2149         int res = 0;
2150         /* Stop if we're a zombie or need a soft hangup */
2151         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
2152                 return -1;
2153         CHECK_BLOCKING(chan);
2154         if (chan->tech->send_text)
2155                 res = chan->tech->send_text(chan, text);
2156         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2157         return res;
2158 }
2159
2160 static int do_senddigit(struct ast_channel *chan, char digit)
2161 {
2162         int res = -1;
2163
2164         if (chan->tech->send_digit)
2165                 res = chan->tech->send_digit(chan, digit);
2166         if (!(chan->tech->send_digit && chan->tech->send_digit_begin) ||
2167             res) {
2168                 /*
2169                  * Device does not support DTMF tones, lets fake
2170                  * it by doing our own generation. (PM2002)
2171                  */
2172                 static const char* dtmf_tones[] = {
2173                         "!941+1336/100,!0/100", /* 0 */
2174                         "!697+1209/100,!0/100", /* 1 */
2175                         "!697+1336/100,!0/100", /* 2 */
2176                         "!697+1477/100,!0/100", /* 3 */
2177                         "!770+1209/100,!0/100", /* 4 */
2178                         "!770+1336/100,!0/100", /* 5 */
2179                         "!770+1477/100,!0/100", /* 6 */
2180                         "!852+1209/100,!0/100", /* 7 */
2181                         "!852+1336/100,!0/100", /* 8 */
2182                         "!852+1477/100,!0/100", /* 9 */
2183                         "!697+1633/100,!0/100", /* A */
2184                         "!770+1633/100,!0/100", /* B */
2185                         "!852+1633/100,!0/100", /* C */
2186                         "!941+1633/100,!0/100", /* D */
2187                         "!941+1209/100,!0/100", /* * */
2188                         "!941+1477/100,!0/100" };       /* # */
2189                 if (digit >= '0' && digit <='9')
2190                         ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2191                 else if (digit >= 'A' && digit <= 'D')
2192                         ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2193                 else if (digit == '*')
2194                         ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2195                 else if (digit == '#')
2196                         ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2197                 else {
2198                         /* not handled */
2199                         ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2200                 }
2201         }
2202         return 0;
2203 }
2204
2205 int ast_senddigit(struct ast_channel *chan, char digit)
2206 {
2207         return do_senddigit(chan, digit);
2208 }
2209
2210 int ast_prod(struct ast_channel *chan)
2211 {
2212         struct ast_frame a = { AST_FRAME_VOICE };
2213         char nothing[128];
2214
2215         /* Send an empty audio frame to get things moving */
2216         if (chan->_state != AST_STATE_UP) {
2217                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2218                 a.subclass = chan->rawwriteformat;
2219                 a.data = nothing + AST_FRIENDLY_OFFSET;
2220                 a.src = "ast_prod";
2221                 if (ast_write(chan, &a))
2222                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2223         }
2224         return 0;
2225 }
2226
2227 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2228 {
2229         int res;
2230         if (!chan->tech->write_video)
2231                 return 0;
2232         res = ast_write(chan, fr);
2233         if (!res)
2234                 res = 1;
2235         return res;
2236 }
2237
2238 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2239 {
2240         int res = -1;
2241         struct ast_frame *f = NULL;
2242         /* Stop if we're a zombie or need a soft hangup */
2243         ast_mutex_lock(&chan->lock);
2244         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))  {
2245                 ast_mutex_unlock(&chan->lock);
2246                 return -1;
2247         }
2248         /* Handle any pending masquerades */
2249         if (chan->masq) {
2250                 if (ast_do_masquerade(chan)) {
2251                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2252                         ast_mutex_unlock(&chan->lock);
2253                         return -1;
2254                 }
2255         }
2256         if (chan->masqr) {
2257                 ast_mutex_unlock(&chan->lock);
2258                 return 0;
2259         }
2260         if (chan->generatordata) {
2261                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2262                         ast_deactivate_generator(chan);
2263                 else {
2264                         ast_mutex_unlock(&chan->lock);
2265                         return 0;
2266                 }
2267         }
2268         /* High bit prints debugging */
2269         if (chan->fout & 0x80000000)
2270                 ast_frame_dump(chan->name, fr, ">>");
2271         CHECK_BLOCKING(chan);
2272         switch(fr->frametype) {
2273         case AST_FRAME_CONTROL:
2274                 /* XXX Interpret control frames XXX */
2275                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
2276                 break;
2277         case AST_FRAME_DTMF_BEGIN:
2278                 if (chan->tech->send_digit_begin)
2279                         res = chan->tech->send_digit_begin(chan, fr->subclass);
2280                 else
2281                         res = 0;
2282                 break;
2283         case AST_FRAME_DTMF_END:
2284                 if (chan->tech->send_digit_end)
2285                         res = chan->tech->send_digit_end(chan);
2286                 else
2287                         res = 0;
2288                 break;
2289         case AST_FRAME_DTMF:
2290                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2291                 ast_mutex_unlock(&chan->lock);
2292                 res = do_senddigit(chan,fr->subclass);
2293                 ast_mutex_lock(&chan->lock);
2294                 CHECK_BLOCKING(chan);
2295                 break;
2296         case AST_FRAME_TEXT:
2297                 if (chan->tech->send_text)
2298                         res = chan->tech->send_text(chan, (char *) fr->data);
2299                 else
2300                         res = 0;
2301                 break;
2302         case AST_FRAME_HTML:
2303                 if (chan->tech->send_html)
2304                         res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2305                 else
2306                         res = 0;
2307                 break;
2308         case AST_FRAME_VIDEO:
2309                 /* XXX Handle translation of video codecs one day XXX */
2310                 if (chan->tech->write_video)
2311                         res = chan->tech->write_video(chan, fr);
2312                 else
2313                         res = 0;
2314                 break;
2315         case AST_FRAME_VOICE:
2316                 if (chan->tech->write) {
2317                         /* Bypass translator if we're writing format in the raw write format.  This
2318                            allows mixing of native / non-native formats */
2319                         if (fr->subclass == chan->rawwriteformat)
2320                                 f = fr;
2321                         else
2322                                 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2323                         if (f) {
2324                                 if (chan->spies)
2325                                         queue_frame_to_spies(chan, f, SPY_WRITE);
2326
2327                                 if (chan->monitor && chan->monitor->write_stream) {
2328 #ifndef MONITOR_CONSTANT_DELAY
2329                                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2330                                         if (jump >= 0) {
2331                                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2332                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2333                                                 chan->outsmpl += jump + 4 * f->samples;
2334                                         } else
2335                                                 chan->outsmpl += f->samples;
2336 #else
2337                                         int jump = chan->insmpl - chan->outsmpl;
2338                                         if (jump - MONITOR_DELAY >= 0) {
2339                                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2340                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2341                                                 chan->outsmpl += jump;
2342                                         } else
2343                                                 chan->outsmpl += f->samples;
2344 #endif
2345                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2346                                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2347                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2348                                         }
2349                                 }
2350
2351                                 res = chan->tech->write(chan, f);
2352                         } else
2353                                 res = 0;
2354                 }
2355         }
2356
2357         if (f && (f != fr))
2358                 ast_frfree(f);
2359         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2360         /* Consider a write failure to force a soft hangup */
2361         if (res < 0)
2362                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2363         else {
2364                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
2365                         chan->fout &= 0x80000000;
2366                 else
2367                         chan->fout++;
2368         }
2369         ast_mutex_unlock(&chan->lock);
2370         return res;
2371 }
2372
2373 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2374                       struct ast_trans_pvt **trans, const int direction)
2375 {
2376         int native;
2377         int res;
2378         
2379         /* Make sure we only consider audio */
2380         fmt &= AST_FORMAT_AUDIO_MASK;
2381         
2382         native = chan->nativeformats;
2383         /* Find a translation path from the native format to one of the desired formats */
2384         if (!direction)
2385                 /* reading */
2386                 res = ast_translator_best_choice(&fmt, &native);
2387         else
2388                 /* writing */
2389                 res = ast_translator_best_choice(&native, &fmt);
2390
2391         if (res < 0) {
2392                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2393                         ast_getformatname(native), ast_getformatname(fmt));
2394                 return -1;
2395         }
2396         
2397         /* Now we have a good choice for both. */
2398         ast_mutex_lock(&chan->lock);
2399         *rawformat = native;
2400         /* User perspective is fmt */
2401         *format = fmt;
2402         /* Free any read translation we have right now */
2403         if (*trans)
2404                 ast_translator_free_path(*trans);
2405         /* Build a translation path from the raw format to the desired format */
2406         if (!direction)
2407                 /* reading */
2408                 *trans = ast_translator_build_path(*format, *rawformat);
2409         else
2410                 /* writing */
2411                 *trans = ast_translator_build_path(*rawformat, *format);
2412         ast_mutex_unlock(&chan->lock);
2413         if (option_debug)
2414                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2415                         direction ? "write" : "read", ast_getformatname(fmt));
2416         return 0;
2417 }
2418
2419 int ast_set_read_format(struct ast_channel *chan, int fmt)
2420 {
2421         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2422                           &chan->readtrans, 0);
2423 }
2424
2425 int ast_set_write_format(struct ast_channel *chan, int fmt)
2426 {
2427         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2428                           &chan->writetrans, 1);
2429 }
2430
2431 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)
2432 {
2433         int state = 0;
2434         int cause = 0;
2435         struct ast_channel *chan;
2436         struct ast_frame *f;
2437         int res = 0;
2438         
2439         chan = ast_request(type, format, data, &cause);
2440         if (chan) {
2441                 if (oh) {
2442                         if (oh->vars)   
2443                                 ast_set_variables(chan, oh->vars);
2444                         if (oh->cid_num && *oh->cid_num && oh->cid_name && *oh->cid_name)
2445                                 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2446                         if (oh->parent_channel)
2447                                 ast_channel_inherit_variables(oh->parent_channel, chan);
2448                         if (oh->account)
2449                                 ast_cdr_setaccount(chan, oh->account);  
2450                 }
2451                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2452
2453                 if (!ast_call(chan, data, 0)) {
2454                         res = 1;        /* in case chan->_state is already AST_STATE_UP */
2455                         while (timeout && (chan->_state != AST_STATE_UP)) {
2456                                 res = ast_waitfor(chan, timeout);
2457                                 if (res < 0) {
2458                                         /* Something not cool, or timed out */
2459                                         break;
2460                                 }
2461                                 /* If done, break out */
2462                                 if (!res)
2463                                         break;
2464                                 if (timeout > -1)
2465                                         timeout = res;
2466                                 f = ast_read(chan);
2467                                 if (!f) {
2468                                         state = AST_CONTROL_HANGUP;
2469                                         res = 0;
2470                                         break;
2471                                 }
2472                                 if (f->frametype == AST_FRAME_CONTROL) {
2473                                         if (f->subclass == AST_CONTROL_RINGING)
2474                                                 state = AST_CONTROL_RINGING;
2475                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
2476                                                 state = f->subclass;
2477                                                 ast_frfree(f);
2478                                                 break;
2479                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
2480                                                 state = f->subclass;
2481                                                 ast_frfree(f);
2482                                                 break;
2483                                         } else if (f->subclass == AST_CONTROL_PROGRESS) {
2484                                                 /* Ignore */
2485                                         } else if (f->subclass == -1) {
2486                                                 /* Ignore -- just stopping indications */
2487                                         } else {
2488                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2489                                         }
2490                                 }
2491                                 ast_frfree(f);
2492                         }
2493                 } else
2494                         ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2495         } else {
2496                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2497                 switch(cause) {
2498                 case AST_CAUSE_BUSY:
2499                         state = AST_CONTROL_BUSY;
2500                         break;
2501                 case AST_CAUSE_CONGESTION:
2502                         state = AST_CONTROL_CONGESTION;
2503                         break;
2504                 }
2505         }
2506         if (chan) {
2507                 /* Final fixups */
2508                 if (oh) {
2509                         if (oh->context && *oh->context)
2510                                 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2511                         if (oh->exten && *oh->exten)
2512                                 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2513                         if (oh->priority)       
2514                                 chan->priority = oh->priority;
2515                 }
2516                 if (chan->_state == AST_STATE_UP) 
2517                         state = AST_CONTROL_ANSWER;
2518         }
2519         if (outstate)
2520                 *outstate = state;
2521         if (chan && res <= 0) {
2522                 if (!chan->cdr && (chan->cdr = ast_cdr_alloc())) {
2523                         ast_cdr_init(chan->cdr, chan);
2524                 }
2525                 if (chan->cdr) {
2526                         char tmp[256];
2527                         snprintf(tmp, 256, "%s/%s", type, (char *)data);
2528                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2529                         ast_cdr_update(chan);
2530                         ast_cdr_start(chan->cdr);
2531                         ast_cdr_end(chan->cdr);
2532                         /* If the cause wasn't handled properly */
2533                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2534                                 ast_cdr_failed(chan->cdr);
2535                 }
2536                 ast_hangup(chan);
2537                 chan = NULL;
2538         }
2539         return chan;
2540 }
2541
2542 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2543 {
2544         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2545 }
2546
2547 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2548 {
2549         struct chanlist *chan;
2550         struct ast_channel *c;
2551         int capabilities;
2552         int fmt;
2553         int res;
2554         int foo;
2555
2556         if (!cause)
2557                 cause = &foo;
2558         *cause = AST_CAUSE_NOTDEFINED;
2559
2560         if (AST_LIST_LOCK(&channels)) {
2561                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2562                 return NULL;
2563         }
2564
2565         AST_LIST_TRAVERSE(&backends, chan, list) {
2566                 if (strcasecmp(type, chan->tech->type))
2567                         continue;
2568
2569                 capabilities = chan->tech->capabilities;
2570                 fmt = format;
2571                 res = ast_translator_best_choice(&fmt, &capabilities);
2572                 if (res < 0) {
2573                         ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2574                         AST_LIST_UNLOCK(&channels);
2575                         return NULL;
2576                 }
2577                 AST_LIST_UNLOCK(&channels);
2578                 if (!chan->tech->requester)
2579                         return NULL;
2580                 
2581                 if (!(c = chan->tech->requester(type, capabilities, data, cause)))
2582                         return NULL;
2583
2584                 if (c->_state == AST_STATE_DOWN) {
2585                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2586                                       "Channel: %s\r\n"
2587                                       "State: %s\r\n"
2588                                       "CallerID: %s\r\n"
2589                                       "CallerIDName: %s\r\n"
2590                                       "Uniqueid: %s\r\n",
2591                                       c->name, ast_state2str(c->_state),
2592                                       c->cid.cid_num ? c->cid.cid_num : "<unknown>",
2593                                       c->cid.cid_name ? c->cid.cid_name : "<unknown>",
2594                                       c->uniqueid);
2595                 }
2596                 return c;
2597         }
2598
2599         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2600         *cause = AST_CAUSE_NOSUCHDRIVER;
2601         AST_LIST_UNLOCK(&channels);
2602
2603         return NULL;
2604 }
2605
2606 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
2607 {
2608         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2609            If the remote end does not answer within the timeout, then do NOT hang up, but 
2610            return anyway.  */
2611         int res = -1;
2612         /* Stop if we're a zombie or need a soft hangup */
2613         ast_mutex_lock(&chan->lock);
2614         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) 
2615                 if (chan->tech->call)
2616                         res = chan->tech->call(chan, addr, timeout);
2617         ast_mutex_unlock(&chan->lock);
2618         return res;
2619 }
2620
2621 /*! 
2622   \brief Transfer a call to dest, if the channel supports transfer
2623
2624   Called by: 
2625     \arg app_transfer
2626     \arg the manager interface
2627 */
2628 int ast_transfer(struct ast_channel *chan, char *dest) 
2629 {
2630         int res = -1;
2631
2632         /* Stop if we're a zombie or need a soft hangup */
2633         ast_mutex_lock(&chan->lock);
2634         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2635                 if (chan->tech->transfer) {
2636                         res = chan->tech->transfer(chan, dest);
2637                         if (!res)
2638                                 res = 1;
2639                 } else
2640                         res = 0;
2641         }
2642         ast_mutex_unlock(&chan->lock);
2643         return res;
2644 }
2645
2646 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2647 {
2648         int pos=0;
2649         int to = ftimeout;
2650         int d;
2651
2652         /* XXX Merge with full version? XXX */
2653         /* Stop if we're a zombie or need a soft hangup */
2654         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2655                 return -1;
2656         if (!len)
2657                 return -1;
2658         do {
2659                 if (c->stream) {
2660                         d = ast_waitstream(c, AST_DIGIT_ANY);
2661                         ast_stopstream(c);
2662                         usleep(1000);
2663                         if (!d)
2664                                 d = ast_waitfordigit(c, to);
2665                 } else {
2666                         d = ast_waitfordigit(c, to);
2667                 }
2668                 if (d < 0)
2669                         return -1;
2670                 if (d == 0) {
2671                         s[pos]='\0';
2672                         return 1;
2673                 }
2674                 if (!strchr(enders, d))
2675                         s[pos++] = d;
2676                 if (strchr(enders, d) || (pos >= len)) {
2677                         s[pos]='\0';
2678                         return 0;
2679                 }
2680                 to = timeout;
2681         } while(1);
2682         /* Never reached */
2683         return 0;
2684 }
2685
2686 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2687 {
2688         int pos=0;
2689         int to = ftimeout;
2690         int d;
2691
2692         /* Stop if we're a zombie or need a soft hangup */
2693         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2694                 return -1;
2695         if (!len)
2696                 return -1;
2697         do {
2698                 if (c->stream) {
2699                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2700                         ast_stopstream(c);
2701                         usleep(1000);
2702                         if (!d)
2703                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2704                 } else {
2705                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2706                 }
2707                 if (d < 0)
2708                         return -1;
2709                 if (d == 0) {
2710                         s[pos]='\0';
2711                         return 1;
2712                 }
2713                 if (d == 1) {
2714                         s[pos]='\0';
2715                         return 2;
2716                 }
2717                 if (!strchr(enders, d))
2718                         s[pos++] = d;
2719                 if (strchr(enders, d) || (pos >= len)) {
2720                         s[pos]='\0';
2721                         return 0;
2722                 }
2723                 to = timeout;
2724         } while(1);
2725         /* Never reached */
2726         return 0;
2727 }
2728
2729 int ast_channel_supports_html(struct ast_channel *chan)
2730 {
2731         if (chan->tech->send_html)
2732                 return 1;
2733         return 0;
2734 }
2735
2736 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2737 {
2738         if (chan->tech->send_html)
2739                 return chan->tech->send_html(chan, subclass, data, datalen);
2740         return -1;
2741 }
2742
2743 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2744 {
2745         if (chan->tech->send_html)
2746                 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2747         return -1;
2748 }
2749
2750 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2751 {
2752         int src;
2753         int dst;
2754
2755         /* Set up translation from the chan to the peer */
2756         src = chan->nativeformats;
2757         dst = peer->nativeformats;
2758         if (ast_translator_best_choice(&dst, &src) < 0) {
2759                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2760                 return -1;
2761         }
2762
2763         /* if the best path is not 'pass through', then
2764            transcoding is needed; if desired, force transcode path
2765            to use SLINEAR between channels */
2766         if ((src != dst) && ast_opt_transcode_via_slin)
2767                 dst = AST_FORMAT_SLINEAR;
2768         if (ast_set_read_format(chan, dst) < 0) {
2769                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2770                 return -1;
2771         }
2772         if (ast_set_write_format(peer, dst) < 0) {
2773                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2774                 return -1;
2775         }
2776
2777         /* Set up translation from the peer to the chan */
2778         src = peer->nativeformats;
2779         dst = chan->nativeformats;
2780         if (ast_translator_best_choice(&dst, &src) < 0) {
2781                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2782                 return -1;
2783         }
2784         /* if the best path is not 'pass through', then
2785            transcoding is needed; if desired, force transcode path
2786            to use SLINEAR between channels */
2787         if ((src != dst) && ast_opt_transcode_via_slin)
2788                 dst = AST_FORMAT_SLINEAR;
2789         if (ast_set_read_format(peer, dst) < 0) {
2790                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2791                 return -1;
2792         }
2793         if (ast_set_write_format(chan, dst) < 0) {
2794                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2795                 return -1;
2796         }
2797         return 0;
2798 }
2799
2800 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2801 {
2802         struct ast_frame null = { AST_FRAME_NULL, };
2803         int res = -1;
2804
2805         if (original == clone) {
2806                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2807                 return -1;
2808         }
2809         ast_mutex_lock(&original->lock);
2810         while(ast_mutex_trylock(&clone->lock)) {
2811                 ast_mutex_unlock(&original->lock);
2812                 usleep(1);
2813                 ast_mutex_lock(&original->lock);
2814         }
2815         ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
2816                 clone->name, original->name);
2817         if (original->masq) {
2818                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2819                         original->masq->name, original->name);
2820         } else if (clone->masqr) {
2821                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2822                         clone->name, clone->masqr->name);
2823         } else {
2824                 original->masq = clone;
2825                 clone->masqr = original;
2826                 ast_queue_frame(original, &null);
2827                 ast_queue_frame(clone, &null);
2828                 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
2829                 res = 0;
2830         }
2831         ast_mutex_unlock(&clone->lock);
2832         ast_mutex_unlock(&original->lock);
2833         return res;
2834 }
2835
2836 void ast_change_name(struct ast_channel *chan, char *newname)
2837 {
2838         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
2839         ast_string_field_set(chan, name, newname);
2840 }
2841
2842 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2843 {
2844         struct ast_var_t *current, *newvar;
2845         const char *varname;
2846
2847         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2848                 int vartype = 0;
2849
2850                 varname = ast_var_full_name(current);
2851                 if (!varname)
2852                         continue;
2853
2854                 if (varname[0] == '_') {
2855                         vartype = 1;
2856                         if (varname[1] == '_')
2857                                 vartype = 2;
2858                 }
2859
2860                 switch (vartype) {
2861                 case 1:
2862                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
2863                         if (newvar) {
2864                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2865                                 if (option_debug)
2866                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2867                         }
2868                         break;
2869                 case 2:
2870                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2871                         if (newvar) {
2872                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2873                                 if (option_debug)
2874                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2875                         }
2876                         break;
2877                 default:
2878                         if (option_debug)
2879                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2880                         break;
2881                 }
2882         }
2883 }
2884
2885 /*!
2886   \brief Clone channel variables from 'clone' channel into 'original' channel
2887    
2888   All variables except those related to app_groupcount are cloned.
2889   Variables are actually _removed_ from 'clone' channel, presumably
2890   because it will subsequently be destroyed.
2891   
2892   \note Assumes locks will be in place on both channels when called.
2893 */
2894 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2895 {
2896         struct ast_var_t *varptr;
2897
2898         /* we need to remove all app_groupcount related variables from the original
2899            channel before merging in the clone's variables; any groups assigned to the
2900            original channel should be released, only those assigned to the clone
2901            should remain
2902         */
2903
2904         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2905                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2906                         AST_LIST_REMOVE(&original->varshead, varptr, entries);
2907                         ast_var_delete(varptr);
2908                 }
2909         }
2910         AST_LIST_TRAVERSE_SAFE_END;
2911
2912         /* Append variables from clone channel into original channel */
2913         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
2914         if (AST_LIST_FIRST(&clone->varshead))
2915                 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2916 }
2917
2918 /*!
2919   \brief Masquerade a channel
2920
2921   \note Assumes channel will be locked when called 
2922 */
2923 int ast_do_masquerade(struct ast_channel *original)
2924 {
2925         int x,i;
2926         int res=0;
2927         int origstate;
2928         struct ast_frame *cur, *prev;
2929         const struct ast_channel_tech *t;
2930         void *t_pvt;
2931         struct ast_callerid tmpcid;
2932         struct ast_channel *clone = original->masq;
2933         int rformat = original->readformat;
2934         int wformat = original->writeformat;
2935         char newn[100];
2936         char orig[100];
2937         char masqn[100];
2938         char zombn[100];
2939
2940         if (option_debug > 3)
2941                 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2942                         clone->name, clone->_state, original->name, original->_state);
2943
2944         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
2945            the clone channel into the original channel.  Start by killing off the original
2946            channel's backend.   I'm not sure we're going to keep this function, because 
2947            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2948
2949         /* We need the clone's lock, too */
2950         ast_mutex_lock(&clone->lock);
2951
2952         ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
2953
2954         /* Having remembered the original read/write formats, we turn off any translation on either
2955            one */
2956         free_translation(clone);
2957         free_translation(original);
2958
2959
2960         /* Unlink the masquerade */
2961         original->masq = NULL;
2962         clone->masqr = NULL;
2963         
2964         /* Save the original name */
2965         ast_copy_string(orig, original->name, sizeof(orig));
2966         /* Save the new name */
2967         ast_copy_string(newn, clone->name, sizeof(newn));
2968         /* Create the masq name */
2969         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2970                 
2971         /* Copy the name from the clone channel */
2972         ast_string_field_set(original, name, newn);
2973
2974         /* Mangle the name of the clone channel */
2975         ast_string_field_set(clone, name, masqn);
2976         
2977         /* Notify any managers of the change, first the masq then the other */
2978         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2979         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2980
2981         /* Swap the technologies */     
2982         t = original->tech;
2983         original->tech = clone->tech;
2984         clone->tech = t;
2985
2986         t_pvt = original->tech_pvt;
2987         original->tech_pvt = clone->tech_pvt;
2988         clone->tech_pvt = t_pvt;
2989
2990         /* Swap the readq's */
2991         cur = original->readq;
2992         original->readq = clone->readq;
2993         clone->readq = cur;
2994
2995         /* Swap the alertpipes */
2996         for (i = 0; i < 2; i++) {
2997                 x = original->alertpipe[i];
2998                 original->alertpipe[i] = clone->alertpipe[i];
2999                 clone->alertpipe[i] = x;
3000         }
3001
3002         /* Swap the raw formats */
3003         x = original->rawreadformat;
3004         original->rawreadformat = clone->rawreadformat;
3005         clone->rawreadformat = x;
3006         x = original->rawwriteformat;
3007         original->rawwriteformat = clone->rawwriteformat;
3008         clone->rawwriteformat = x;
3009
3010         /* Save any pending frames on both sides.  Start by counting
3011          * how many we're going to need... */
3012         prev = NULL;
3013         x = 0;
3014         for (cur = clone->readq; cur; cur = cur->next) {
3015                 x++;
3016                 prev = cur;
3017         }
3018         /* If we had any, prepend them to the ones already in the queue, and 
3019          * load up the alertpipe */
3020         if (prev) {
3021                 prev->next = original->readq;
3022                 original->readq = clone->readq;
3023                 clone->readq = NULL;
3024                 if (original->alertpipe[1] > -1) {
3025                         for (i = 0; i < x; i++)
3026                                 write(original->alertpipe[1], &x, sizeof(x));
3027                 }
3028         }
3029         clone->_softhangup = AST_SOFTHANGUP_DEV;
3030
3031
3032         /* And of course, so does our current state.  Note we need not
3033            call ast_setstate since the event manager doesn't really consider
3034            these separate.  We do this early so that the clone has the proper
3035            state of the original channel. */
3036         origstate = original->_state;
3037         original->_state = clone->_state;
3038         clone->_state = origstate;
3039
3040         if (clone->tech->fixup){
3041                 res = clone->tech->fixup(original, clone);
3042                 if (res) 
3043                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3044         }
3045
3046         /* Start by disconnecting the original's physical side */
3047         if (clone->tech->hangup)
3048                 res = clone->tech->hangup(clone);
3049         if (res) {
3050                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
3051                 ast_mutex_unlock(&clone->lock);
3052                 return -1;
3053         }
3054         
3055         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3056         /* Mangle the name of the clone channel */
3057         ast_string_field_set(clone, name, zombn);
3058         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3059
3060         /* Update the type. */
3061         t_pvt = original->monitor;
3062         original->monitor = clone->monitor;
3063         clone->monitor = t_pvt;
3064         
3065         /* Keep the same language.  */
3066         ast_string_field_set(original, language, clone->language);
3067         /* Copy the FD's other than the generator fd */
3068         for (x = 0; x < AST_MAX_FDS; x++) {
3069                 if (x != AST_GENERATOR_FD)
3070                         original->fds[x] = clone->fds[x];
3071         }
3072         clone_variables(original, clone);
3073         AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3074         /* Presense of ADSI capable CPE follows clone */
3075         original->adsicpe = clone->adsicpe;
3076         /* Bridge remains the same */
3077         /* CDR fields remain the same */
3078         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3079         /* Application and data remain the same */
3080         /* Clone exception  becomes real one, as with fdno */
3081         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3082         original->fdno = clone->fdno;
3083         /* Schedule context remains the same */
3084         /* Stream stuff stays the same */
3085         /* Keep the original state.  The fixup code will need to work with it most likely */
3086
3087         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3088            out. */
3089         tmpcid = original->cid;
3090         original->cid = clone->cid;
3091         clone->cid = tmpcid;
3092         
3093         /* Restore original timing file descriptor */
3094         original->fds[AST_TIMING_FD] = original->timingfd;
3095         
3096         /* Our native formats are different now */
3097         original->nativeformats = clone->nativeformats;
3098         
3099         /* Context, extension, priority, app data, jump table,  remain the same */
3100         /* pvt switches.  pbx stays the same, as does next */
3101         
3102         /* Set the write format */
3103         ast_set_write_format(original, wformat);
3104
3105         /* Set the read format */
3106         ast_set_read_format(original, rformat);
3107
3108         /* Copy the music class */
3109         ast_string_field_set(original, musicclass, clone->musicclass);
3110
3111         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3112
3113         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
3114            can fix up everything as best as possible */
3115         if (original->tech->fixup) {
3116                 res = original->tech->fixup(clone, original);
3117                 if (res) {
3118                         ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3119                                 original->tech->type, original->name);
3120                         ast_mutex_unlock(&clone->lock);
3121                         return -1;
3122                 }
3123         } else
3124                 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
3125                         original->tech->type, original->name);
3126         
3127         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as