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