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