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