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