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