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