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