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