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