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