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