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