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