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