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