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