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