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