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