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