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