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