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