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