d5fcb0a2d4a38d7dcd4ab4ce58965b2ebe7e4d7a
[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 <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <sys/time.h>
35 #include <signal.h>
36 #include <errno.h>
37 #include <unistd.h>
38 #include <math.h>
39
40 #include "asterisk/zapata.h"
41
42 #include "asterisk/pbx.h"
43 #include "asterisk/frame.h"
44 #include "asterisk/sched.h"
45 #include "asterisk/options.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/musiconhold.h"
48 #include "asterisk/logger.h"
49 #include "asterisk/say.h"
50 #include "asterisk/file.h"
51 #include "asterisk/cli.h"
52 #include "asterisk/translate.h"
53 #include "asterisk/manager.h"
54 #include "asterisk/chanvars.h"
55 #include "asterisk/linkedlists.h"
56 #include "asterisk/indications.h"
57 #include "asterisk/monitor.h"
58 #include "asterisk/causes.h"
59 #include "asterisk/callerid.h"
60 #include "asterisk/utils.h"
61 #include "asterisk/lock.h"
62 #include "asterisk/app.h"
63 #include "asterisk/transcap.h"
64 #include "asterisk/devicestate.h"
65 #include "asterisk/sha1.h"
66 #include "asterisk/threadstorage.h"
67 #include "asterisk/slinfactory.h"
68 #include "asterisk/audiohook.h"
69
70 #ifdef HAVE_EPOLL
71 #include <sys/epoll.h>
72 #endif
73
74 struct ast_epoll_data {
75         struct ast_channel *chan;
76         int which;
77 };
78
79 /* uncomment if you have problems with 'monitoring' synchronized files */
80 #if 0
81 #define MONITOR_CONSTANT_DELAY
82 #define MONITOR_DELAY   150 * 8         /*!< 150 ms of MONITORING DELAY */
83 #endif
84
85 /*! \brief Prevent new channel allocation if shutting down. */
86 static int shutting_down;
87
88 static int uniqueint;
89
90 unsigned long global_fin, global_fout;
91
92 AST_THREADSTORAGE(state2str_threadbuf);
93 #define STATE2STR_BUFSIZE   32
94
95 /*! Default amount of time to use when emulating a digit as a begin and end 
96  *  100ms */
97 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
98
99 /*! Minimum allowed digit length - 80ms */
100 #define AST_MIN_DTMF_DURATION 80
101
102 /*! Minimum amount of time between the end of the last digit and the beginning 
103  *  of a new one - 45ms */
104 #define AST_MIN_DTMF_GAP 45
105
106 /*! \brief List of channel drivers */
107 struct chanlist {
108         const struct ast_channel_tech *tech;
109         AST_LIST_ENTRY(chanlist) list;
110 };
111
112 /*! \brief the list of registered channel types */
113 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
114
115 /*! \brief the list of channels we have. Note that the lock for this list is used for
116     both the channels list and the backends list.  */
117 static AST_RWLIST_HEAD_STATIC(channels, ast_channel);
118
119 /*! \brief map AST_CAUSE's to readable string representations 
120  *
121  * \ref causes.h
122 */
123 const struct ast_cause {
124         int cause;
125         const char *name;
126         const char *desc;
127 } causes[] = {
128         { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
129         { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
130         { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
131         { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
132         { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
133         { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
134         { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
135         { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
136         { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
137         { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
138         { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
139         { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
140         { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
141         { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
142         { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
143         { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
144         { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
145         { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
146         { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
147         { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
148         { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
149         { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
150         { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
151         { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
152         { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
153         { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
154         { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
155         { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
156         { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
157         { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
158         { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
159         { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
160         { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
161         { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
162         { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
163         { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
164         { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
165         { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
166         { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
167         { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
168         { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
169         { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
170         { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
171         { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
172 };
173
174 struct ast_variable *ast_channeltype_list(void)
175 {
176         struct chanlist *cl;
177         struct ast_variable *var=NULL, *prev = NULL;
178         AST_LIST_TRAVERSE(&backends, cl, list) {
179                 if (prev)  {
180                         if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
181                                 prev = prev->next;
182                 } else {
183                         var = ast_variable_new(cl->tech->type, cl->tech->description, "");
184                         prev = var;
185                 }
186         }
187         return var;
188 }
189
190 /*! \brief Show channel types - CLI command */
191 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
192 {
193 #define FORMAT  "%-10.10s  %-40.40s %-12.12s %-12.12s %-12.12s\n"
194         struct chanlist *cl;
195         int count_chan = 0;
196
197         switch (cmd) {
198         case CLI_INIT:
199                 e->command = "core show channeltypes";
200                 e->usage =
201                         "Usage: core show channeltypes\n"
202                         "       Lists available channel types registered in your\n"
203                         "       Asterisk server.\n";
204                 return NULL;
205         case CLI_GENERATE:
206                 return NULL;
207         }
208
209         if (a->argc != 3)
210                 return CLI_SHOWUSAGE;
211
212         ast_cli(a->fd, FORMAT, "Type", "Description",       "Devicestate", "Indications", "Transfer");
213         ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
214         if (AST_RWLIST_RDLOCK(&channels)) {
215                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
216                 return CLI_FAILURE;
217         }
218         AST_LIST_TRAVERSE(&backends, cl, list) {
219                 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
220                         (cl->tech->devicestate) ? "yes" : "no",
221                         (cl->tech->indicate) ? "yes" : "no",
222                         (cl->tech->transfer) ? "yes" : "no");
223                 count_chan++;
224         }
225         AST_RWLIST_UNLOCK(&channels);
226         ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
227         return CLI_SUCCESS;
228
229 #undef FORMAT
230 }
231
232 static char *complete_channeltypes(struct ast_cli_args *a)
233 {
234         struct chanlist *cl;
235         int which = 0;
236         int wordlen;
237         char *ret = NULL;
238
239         if (a->pos != 3)
240                 return NULL;
241
242         wordlen = strlen(a->word);
243
244         AST_LIST_TRAVERSE(&backends, cl, list) {
245                 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
246                         ret = ast_strdup(cl->tech->type);
247                         break;
248                 }
249         }
250         
251         return ret;
252 }
253
254 /*! \brief Show details about a channel driver - CLI command */
255 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
256 {
257         struct chanlist *cl = NULL;
258
259         switch (cmd) {
260         case CLI_INIT:
261                 e->command = "core show channeltype";
262                 e->usage =
263                         "Usage: core show channeltype <name>\n"
264                         "       Show details about the specified channel type, <name>.\n";
265                 return NULL;
266         case CLI_GENERATE:
267                 return complete_channeltypes(a);
268         }
269
270         if (a->argc != 4)
271                 return CLI_SHOWUSAGE;
272         
273         if (AST_RWLIST_RDLOCK(&channels)) {
274                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
275                 return CLI_FAILURE;
276         }
277
278         AST_LIST_TRAVERSE(&backends, cl, list) {
279                 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
280                         break;
281         }
282
283
284         if (!cl) {
285                 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
286                 AST_RWLIST_UNLOCK(&channels);
287                 return CLI_FAILURE;
288         }
289
290         ast_cli(a->fd,
291                 "-- Info about channel driver: %s --\n"
292                 "  Device State: %s\n"
293                 "    Indication: %s\n"
294                 "     Transfer : %s\n"
295                 "  Capabilities: %d\n"
296                 "   Digit Begin: %s\n"
297                 "     Digit End: %s\n"
298                 "    Send HTML : %s\n"
299                 " Image Support: %s\n"
300                 "  Text Support: %s\n",
301                 cl->tech->type,
302                 (cl->tech->devicestate) ? "yes" : "no",
303                 (cl->tech->indicate) ? "yes" : "no",
304                 (cl->tech->transfer) ? "yes" : "no",
305                 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
306                 (cl->tech->send_digit_begin) ? "yes" : "no",
307                 (cl->tech->send_digit_end) ? "yes" : "no",
308                 (cl->tech->send_html) ? "yes" : "no",
309                 (cl->tech->send_image) ? "yes" : "no",
310                 (cl->tech->send_text) ? "yes" : "no"
311                 
312         );
313
314         AST_RWLIST_UNLOCK(&channels);
315         return CLI_SUCCESS;
316 }
317
318 static struct ast_cli_entry cli_channel[] = {
319         AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
320         AST_CLI_DEFINE(handle_cli_core_show_channeltype,  "Give more details on that channel type")
321 };
322
323 /*! \brief Checks to see if a channel is needing hang up */
324 int ast_check_hangup(struct ast_channel *chan)
325 {
326         if (chan->_softhangup)          /* yes if soft hangup flag set */
327                 return 1;
328         if (!chan->tech_pvt)            /* yes if no technology private data */
329                 return 1;
330         if (!chan->whentohangup)        /* no if no hangup scheduled */
331                 return 0;
332         if (chan->whentohangup > time(NULL))    /* no if hangup time has not come yet. */
333                 return 0;
334         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;    /* record event */
335         return 1;
336 }
337
338 static int ast_check_hangup_locked(struct ast_channel *chan)
339 {
340         int res;
341         ast_channel_lock(chan);
342         res = ast_check_hangup(chan);
343         ast_channel_unlock(chan);
344         return res;
345 }
346
347 /*! \brief Initiate system shutdown */
348 void ast_begin_shutdown(int hangup)
349 {
350         struct ast_channel *c;
351         shutting_down = 1;
352         if (hangup) {
353                 AST_RWLIST_RDLOCK(&channels);
354                 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
355                         ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
356                 AST_RWLIST_UNLOCK(&channels);
357         }
358 }
359
360 /*! \brief returns number of active/allocated channels */
361 int ast_active_channels(void)
362 {
363         struct ast_channel *c;
364         int cnt = 0;
365         AST_RWLIST_RDLOCK(&channels);
366         AST_RWLIST_TRAVERSE(&channels, c, chan_list)
367                 cnt++;
368         AST_RWLIST_UNLOCK(&channels);
369         return cnt;
370 }
371
372 /*! \brief Cancel a shutdown in progress */
373 void ast_cancel_shutdown(void)
374 {
375         shutting_down = 0;
376 }
377
378 /*! \brief Returns non-zero if Asterisk is being shut down */
379 int ast_shutting_down(void)
380 {
381         return shutting_down;
382 }
383
384 /*! \brief Set when to hangup channel */
385 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
386 {
387         chan->whentohangup = offset ? time(NULL) + offset : 0;
388         ast_queue_frame(chan, &ast_null_frame);
389         return;
390 }
391
392 /*! \brief Compare a offset with when to hangup channel */
393 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
394 {
395         time_t whentohangup;
396
397         if (!chan->whentohangup)
398                 return (offset == 0) ? 0 : -1;
399
400         if (!offset) /* XXX why is this special? */
401                 return 1;
402
403         whentohangup = offset + time(NULL);
404
405         if (chan->whentohangup < whentohangup)
406                 return 1;
407         else if (chan->whentohangup == whentohangup)
408                 return 0;
409         else
410                 return -1;
411 }
412
413 /*! \brief Register a new telephony channel in Asterisk */
414 int ast_channel_register(const struct ast_channel_tech *tech)
415 {
416         struct chanlist *chan;
417
418         AST_RWLIST_WRLOCK(&channels);
419
420         AST_LIST_TRAVERSE(&backends, chan, list) {
421                 if (!strcasecmp(tech->type, chan->tech->type)) {
422                         ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
423                         AST_RWLIST_UNLOCK(&channels);
424                         return -1;
425                 }
426         }
427         
428         if (!(chan = ast_calloc(1, sizeof(*chan)))) {
429                 AST_RWLIST_UNLOCK(&channels);
430                 return -1;
431         }
432         chan->tech = tech;
433         AST_LIST_INSERT_HEAD(&backends, chan, list);
434
435         ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
436
437         ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
438
439         AST_RWLIST_UNLOCK(&channels);
440         return 0;
441 }
442
443 /*! \brief Unregister channel driver */
444 void ast_channel_unregister(const struct ast_channel_tech *tech)
445 {
446         struct chanlist *chan;
447
448         ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
449
450         AST_RWLIST_WRLOCK(&channels);
451
452         AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
453                 if (chan->tech == tech) {
454                         AST_LIST_REMOVE_CURRENT(&backends, list);
455                         ast_free(chan);
456                         ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
457                         break;  
458                 }
459         }
460         AST_LIST_TRAVERSE_SAFE_END
461
462         AST_RWLIST_UNLOCK(&channels);
463 }
464
465 /*! \brief Get handle to channel driver based on name */
466 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
467 {
468         struct chanlist *chanls;
469         const struct ast_channel_tech *ret = NULL;
470
471         if (AST_RWLIST_RDLOCK(&channels)) {
472                 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
473                 return NULL;
474         }
475
476         AST_LIST_TRAVERSE(&backends, chanls, list) {
477                 if (!strcasecmp(name, chanls->tech->type)) {
478                         ret = chanls->tech;
479                         break;
480                 }
481         }
482
483         AST_RWLIST_UNLOCK(&channels);
484         
485         return ret;
486 }
487
488 /*! \brief Gives the string form of a given hangup cause */
489 const char *ast_cause2str(int cause)
490 {
491         int x;
492
493         for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
494                 if (causes[x].cause == cause)
495                         return causes[x].desc;
496         }
497
498         return "Unknown";
499 }
500
501 /*! \brief Convert a symbolic hangup cause to number */
502 int ast_str2cause(const char *name)
503 {
504         int x;
505
506         for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
507                 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
508                         return causes[x].cause;
509
510         return -1;
511 }
512
513 /*! \brief Gives the string form of a given channel state.
514         \note This function is not reentrant.
515  */
516 const char *ast_state2str(enum ast_channel_state state)
517 {
518         char *buf;
519
520         switch (state) {
521         case AST_STATE_DOWN:
522                 return "Down";
523         case AST_STATE_RESERVED:
524                 return "Rsrvd";
525         case AST_STATE_OFFHOOK:
526                 return "OffHook";
527         case AST_STATE_DIALING:
528                 return "Dialing";
529         case AST_STATE_RING:
530                 return "Ring";
531         case AST_STATE_RINGING:
532                 return "Ringing";
533         case AST_STATE_UP:
534                 return "Up";
535         case AST_STATE_BUSY:
536                 return "Busy";
537         case AST_STATE_DIALING_OFFHOOK:
538                 return "Dialing Offhook";
539         case AST_STATE_PRERING:
540                 return "Pre-ring";
541         default:
542                 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
543                         return "Unknown";
544                 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
545                 return buf;
546         }
547 }
548
549 /*! \brief Gives the string form of a given transfer capability */
550 char *ast_transfercapability2str(int transfercapability)
551 {
552         switch (transfercapability) {
553         case AST_TRANS_CAP_SPEECH:
554                 return "SPEECH";
555         case AST_TRANS_CAP_DIGITAL:
556                 return "DIGITAL";
557         case AST_TRANS_CAP_RESTRICTED_DIGITAL:
558                 return "RESTRICTED_DIGITAL";
559         case AST_TRANS_CAP_3_1K_AUDIO:
560                 return "3K1AUDIO";
561         case AST_TRANS_CAP_DIGITAL_W_TONES:
562                 return "DIGITAL_W_TONES";
563         case AST_TRANS_CAP_VIDEO:
564                 return "VIDEO";
565         default:
566                 return "UNKNOWN";
567         }
568 }
569
570 /*! \brief Pick the best audio codec */
571 int ast_best_codec(int fmts)
572 {
573         /* This just our opinion, expressed in code.  We are asked to choose
574            the best codec to use, given no information */
575         int x;
576         static const int prefs[] =
577         {
578                 /*! Okay, ulaw is used by all telephony equipment, so start with it */
579                 AST_FORMAT_ULAW,
580                 /*! Unless of course, you're a silly European, so then prefer ALAW */
581                 AST_FORMAT_ALAW,
582                 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
583                 AST_FORMAT_G722,
584                 /*! Okay, well, signed linear is easy to translate into other stuff */
585                 AST_FORMAT_SLINEAR,
586                 /*! G.726 is standard ADPCM, in RFC3551 packing order */
587                 AST_FORMAT_G726,
588                 /*! G.726 is standard ADPCM, in AAL2 packing order */
589                 AST_FORMAT_G726_AAL2,
590                 /*! ADPCM has great sound quality and is still pretty easy to translate */
591                 AST_FORMAT_ADPCM,
592                 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
593                     translate and sounds pretty good */
594                 AST_FORMAT_GSM,
595                 /*! iLBC is not too bad */
596                 AST_FORMAT_ILBC,
597                 /*! Speex is free, but computationally more expensive than GSM */
598                 AST_FORMAT_SPEEX,
599                 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
600                     to use it */
601                 AST_FORMAT_LPC10,
602                 /*! G.729a is faster than 723 and slightly less expensive */
603                 AST_FORMAT_G729A,
604                 /*! Down to G.723.1 which is proprietary but at least designed for voice */
605                 AST_FORMAT_G723_1,
606         };
607
608         /* Strip out video */
609         fmts &= AST_FORMAT_AUDIO_MASK;
610         
611         /* Find the first preferred codec in the format given */
612         for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
613                 if (fmts & prefs[x])
614                         return prefs[x];
615         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
616         return 0;
617 }
618
619 static const struct ast_channel_tech null_tech = {
620         .type = "NULL",
621         .description = "Null channel (should not see this)",
622 };
623
624 /*! \brief Create a new channel structure */
625 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, ...)
626 {
627         struct ast_channel *tmp;
628         int x;
629         int flags;
630         struct varshead *headp;
631         va_list ap1, ap2;
632
633         /* If shutting down, don't allocate any new channels */
634         if (shutting_down) {
635                 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
636                 return NULL;
637         }
638
639         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
640                 return NULL;
641
642         if (!(tmp->sched = sched_context_create())) {
643                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
644                 ast_free(tmp);
645                 return NULL;
646         }
647         
648         if ((ast_string_field_init(tmp, 128))) {
649                 sched_context_destroy(tmp->sched);
650                 ast_free(tmp);
651                 return NULL;
652         }
653
654 #ifdef HAVE_EPOLL
655         tmp->epfd = epoll_create(25);
656 #endif
657
658         for (x = 0; x < AST_MAX_FDS; x++) {
659                 tmp->fds[x] = -1;
660 #ifdef HAVE_EPOLL
661                 tmp->epfd_data[x] = NULL;
662 #endif
663         }
664
665 #ifdef HAVE_ZAPTEL
666         tmp->timingfd = open("/dev/zap/timer", O_RDWR);
667         if (tmp->timingfd > -1) {
668                 /* Check if timing interface supports new
669                    ping/pong scheme */
670                 flags = 1;
671                 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
672                         needqueue = 0;
673         }
674 #else
675         tmp->timingfd = -1;                                     
676 #endif                                  
677
678         if (needqueue) {
679                 if (pipe(tmp->alertpipe)) {
680                         ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
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);
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);
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         struct ast_datastore *datastore2 = NULL;
1254         int res = -1;
1255
1256         /* Find our position and remove ourselves */
1257         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1258                 if (datastore2 == datastore) {
1259                         AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1260                         res = 0;
1261                         break;
1262                 }
1263         }
1264         AST_LIST_TRAVERSE_SAFE_END
1265
1266         return res;
1267 }
1268
1269 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1270 {
1271         struct ast_datastore *datastore = NULL;
1272         
1273         if (info == NULL)
1274                 return NULL;
1275
1276         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1277                 if (datastore->info == info) {
1278                         if (uid != NULL && datastore->uid != NULL) {
1279                                 if (!strcasecmp(uid, datastore->uid)) {
1280                                         /* Matched by type AND uid */
1281                                         break;
1282                                 }
1283                         } else {
1284                                 /* Matched by type at least */
1285                                 break;
1286                         }
1287                 }
1288         }
1289         AST_LIST_TRAVERSE_SAFE_END
1290
1291         return datastore;
1292 }
1293
1294 /*! Set the file descriptor on the channel */
1295 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
1296 {
1297 #ifdef HAVE_EPOLL
1298         struct epoll_event ev;
1299         struct ast_epoll_data *aed = NULL;
1300
1301         if (chan->fds[which] > -1) {
1302                 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
1303                 aed = chan->epfd_data[which];
1304         }
1305
1306         /* If this new fd is valid, add it to the epoll */
1307         if (fd > -1) {
1308                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
1309                         return;
1310                 
1311                 chan->epfd_data[which] = aed;
1312                 aed->chan = chan;
1313                 aed->which = which;
1314                 
1315                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1316                 ev.data.ptr = aed;
1317                 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
1318         } else if (aed) {
1319                 /* We don't have to keep around this epoll data structure now */
1320                 free(aed);
1321                 chan->epfd_data[which] = NULL;
1322         }
1323 #endif
1324         chan->fds[which] = fd;
1325         return;
1326 }
1327
1328 /*! Add a channel to an optimized waitfor */
1329 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
1330 {
1331 #ifdef HAVE_EPOLL
1332         struct epoll_event ev;
1333         int i = 0;
1334
1335         if (chan0->epfd == -1)
1336                 return;
1337
1338         /* Iterate through the file descriptors on chan1, adding them to chan0 */
1339         for (i = 0; i < AST_MAX_FDS; i++) {
1340                 if (chan1->fds[i] == -1)
1341                         continue;
1342                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1343                 ev.data.ptr = chan1->epfd_data[i];
1344                 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
1345         }
1346
1347 #endif
1348         return;
1349 }
1350
1351 /*! Delete a channel from an optimized waitfor */
1352 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
1353 {
1354 #ifdef HAVE_EPOLL
1355         struct epoll_event ev;
1356         int i = 0;
1357
1358         if (chan0->epfd == -1)
1359                 return;
1360
1361         for (i = 0; i < AST_MAX_FDS; i++) {
1362                 if (chan1->fds[i] == -1)
1363                         continue;
1364                 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
1365         }
1366
1367 #endif
1368         return;
1369 }
1370
1371 /*! \brief Softly hangup a channel, don't lock */
1372 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1373 {
1374         ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1375         /* Inform channel driver that we need to be hung up, if it cares */
1376         chan->_softhangup |= cause;
1377         ast_queue_frame(chan, &ast_null_frame);
1378         /* Interrupt any poll call or such */
1379         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1380                 pthread_kill(chan->blocker, SIGURG);
1381         return 0;
1382 }
1383
1384 /*! \brief Softly hangup a channel, lock */
1385 int ast_softhangup(struct ast_channel *chan, int cause)
1386 {
1387         int res;
1388         ast_channel_lock(chan);
1389         res = ast_softhangup_nolock(chan, cause);
1390         ast_channel_unlock(chan);
1391         return res;
1392 }
1393
1394 static void free_translation(struct ast_channel *clone)
1395 {
1396         if (clone->writetrans)
1397                 ast_translator_free_path(clone->writetrans);
1398         if (clone->readtrans)
1399                 ast_translator_free_path(clone->readtrans);
1400         clone->writetrans = NULL;
1401         clone->readtrans = NULL;
1402         clone->rawwriteformat = clone->nativeformats;
1403         clone->rawreadformat = clone->nativeformats;
1404 }
1405
1406 /*! \brief Hangup a channel */
1407 int ast_hangup(struct ast_channel *chan)
1408 {
1409         int res = 0;
1410         struct ast_cdr *cdr = NULL;
1411
1412         /* Don't actually hang up a channel that will masquerade as someone else, or
1413            if someone is going to masquerade as us */
1414         ast_channel_lock(chan);
1415
1416         if (chan->audiohooks) {
1417                 ast_audiohook_detach_list(chan->audiohooks);
1418                 chan->audiohooks = NULL;
1419         }
1420
1421         if (chan->masq) {
1422                 if (ast_do_masquerade(chan))
1423                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1424         }
1425
1426         if (chan->masq) {
1427                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1428                 ast_channel_unlock(chan);
1429                 return 0;
1430         }
1431         /* If this channel is one which will be masqueraded into something,
1432            mark it as a zombie already, so we know to free it later */
1433         if (chan->masqr) {
1434                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1435                 ast_channel_unlock(chan);
1436                 return 0;
1437         }
1438         free_translation(chan);
1439         /* Close audio stream */
1440         if (chan->stream) {
1441                 ast_closestream(chan->stream);
1442                 chan->stream = NULL;
1443         }
1444         /* Close video stream */
1445         if (chan->vstream) {
1446                 ast_closestream(chan->vstream);
1447                 chan->vstream = NULL;
1448         }
1449         if (chan->sched) {
1450                 sched_context_destroy(chan->sched);
1451                 chan->sched = NULL;
1452         }
1453         
1454         if (chan->generatordata)        /* Clear any tone stuff remaining */
1455                 if (chan->generator && chan->generator->release)
1456                         chan->generator->release(chan, chan->generatordata);
1457         chan->generatordata = NULL;
1458         chan->generator = NULL;
1459         if (chan->cdr) {                /* End the CDR if it hasn't already */
1460                 ast_cdr_end(chan->cdr);
1461                 cdr = chan->cdr;
1462                 chan->cdr = NULL;
1463         }
1464         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1465                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1466                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1467                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1468                 CRASH;
1469         }
1470         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1471                 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1472                 if (chan->tech->hangup)
1473                         res = chan->tech->hangup(chan);
1474         } else {
1475                 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1476         }
1477                         
1478         ast_channel_unlock(chan);
1479         manager_event(EVENT_FLAG_CALL, "Hangup",
1480                         "Channel: %s\r\n"
1481                         "Uniqueid: %s\r\n"
1482                         "Cause: %d\r\n"
1483                         "Cause-txt: %s\r\n",
1484                         chan->name,
1485                         chan->uniqueid,
1486                         chan->hangupcause,
1487                         ast_cause2str(chan->hangupcause)
1488                         );
1489         ast_channel_free(chan);
1490
1491         if (cdr)
1492                 ast_cdr_detach(cdr);
1493
1494         return res;
1495 }
1496
1497 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1498 {
1499         int res = 0;
1500
1501         ast_channel_lock(chan);
1502
1503         /* You can't answer an outbound call */
1504         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1505                 ast_channel_unlock(chan);
1506                 return 0;
1507         }
1508
1509         /* Stop if we're a zombie or need a soft hangup */
1510         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1511                 ast_channel_unlock(chan);
1512                 return -1;
1513         }
1514
1515         switch (chan->_state) {
1516         case AST_STATE_RINGING:
1517         case AST_STATE_RING:
1518                 if (chan->tech->answer)
1519                         res = chan->tech->answer(chan);
1520                 ast_setstate(chan, AST_STATE_UP);
1521                 ast_cdr_answer(chan->cdr);
1522                 ast_channel_unlock(chan);
1523                 if (delay)
1524                         ast_safe_sleep(chan, delay);
1525                 return res;
1526                 break;
1527         case AST_STATE_UP:
1528                 ast_cdr_answer(chan->cdr);
1529                 break;
1530         default:
1531                 break;
1532         }
1533
1534         ast_channel_unlock(chan);
1535
1536         return res;
1537 }
1538
1539 int ast_answer(struct ast_channel *chan)
1540 {
1541         return __ast_answer(chan, 500);
1542 }
1543
1544 void ast_deactivate_generator(struct ast_channel *chan)
1545 {
1546         ast_channel_lock(chan);
1547         if (chan->generatordata) {
1548                 if (chan->generator && chan->generator->release)
1549                         chan->generator->release(chan, chan->generatordata);
1550                 chan->generatordata = NULL;
1551                 chan->generator = NULL;
1552                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
1553                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1554                 ast_settimeout(chan, 0, NULL, NULL);
1555         }
1556         ast_channel_unlock(chan);
1557 }
1558
1559 static int generator_force(const void *data)
1560 {
1561         /* Called if generator doesn't have data */
1562         void *tmp;
1563         int res;
1564         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1565         struct ast_channel *chan = (struct ast_channel *)data;
1566         tmp = chan->generatordata;
1567         chan->generatordata = NULL;
1568         generate = chan->generator->generate;
1569         res = generate(chan, tmp, 0, 160);
1570         chan->generatordata = tmp;
1571         if (res) {
1572                 ast_debug(1, "Auto-deactivating generator\n");
1573                 ast_deactivate_generator(chan);
1574         }
1575         return 0;
1576 }
1577
1578 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1579 {
1580         int res = 0;
1581
1582         ast_channel_lock(chan);
1583
1584         if (chan->generatordata) {
1585                 if (chan->generator && chan->generator->release)
1586                         chan->generator->release(chan, chan->generatordata);
1587                 chan->generatordata = NULL;
1588         }
1589
1590         ast_prod(chan);
1591         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1592                 res = -1;
1593         }
1594         
1595         if (!res) {
1596                 ast_settimeout(chan, 160, generator_force, chan);
1597                 chan->generator = gen;
1598         }
1599
1600         ast_channel_unlock(chan);
1601
1602         return res;
1603 }
1604
1605 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1606 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1607 {
1608         int winner = -1;
1609         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1610         return winner;
1611 }
1612
1613 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1614 #ifdef HAVE_EPOLL
1615 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
1616                                         int *exception, int *outfd, int *ms)
1617 #else
1618 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1619                                         int *exception, int *outfd, int *ms)
1620 #endif
1621 {
1622         struct timeval start = { 0 , 0 };
1623         struct pollfd *pfds;
1624         int res;
1625         long rms;
1626         int x, y, max;
1627         int sz;
1628         time_t now = 0;
1629         long whentohangup = 0, diff;
1630         struct ast_channel *winner = NULL;
1631         struct fdmap {
1632                 int chan;
1633                 int fdno;
1634         } *fdmap;
1635
1636         sz = n * AST_MAX_FDS + nfds;
1637         pfds = alloca(sizeof(*pfds) * sz);
1638         fdmap = alloca(sizeof(*fdmap) * sz);
1639
1640         if (outfd)
1641                 *outfd = -99999;
1642         if (exception)
1643                 *exception = 0;
1644         
1645         /* Perform any pending masquerades */
1646         for (x = 0; x < n; x++) {
1647                 ast_channel_lock(c[x]);
1648                 if (c[x]->masq && ast_do_masquerade(c[x])) {
1649                         ast_log(LOG_WARNING, "Masquerade failed\n");
1650                         *ms = -1;
1651                         ast_channel_unlock(c[x]);
1652                         return NULL;
1653                 }
1654                 if (c[x]->whentohangup) {
1655                         if (!whentohangup)
1656                                 time(&now);
1657                         diff = c[x]->whentohangup - now;
1658                         if (diff < 1) {
1659                                 /* Should already be hungup */
1660                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1661                                 ast_channel_unlock(c[x]);
1662                                 return c[x];
1663                         }
1664                         if (!whentohangup || (diff < whentohangup))
1665                                 whentohangup = diff;
1666                 }
1667                 ast_channel_unlock(c[x]);
1668         }
1669         /* Wait full interval */
1670         rms = *ms;
1671         if (whentohangup) {
1672                 rms = whentohangup * 1000;              /* timeout in milliseconds */
1673                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1674                         rms =  *ms;
1675         }
1676         /*
1677          * Build the pollfd array, putting the channels' fds first,
1678          * followed by individual fds. Order is important because
1679          * individual fd's must have priority over channel fds.
1680          */
1681         max = 0;
1682         for (x = 0; x < n; x++) {
1683                 for (y = 0; y < AST_MAX_FDS; y++) {
1684                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1685                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1686                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1687                 }
1688                 CHECK_BLOCKING(c[x]);
1689         }
1690         /* Add the individual fds */
1691         for (x = 0; x < nfds; x++) {
1692                 fdmap[max].chan = -1;
1693                 max += ast_add_fd(&pfds[max], fds[x]);
1694         }
1695
1696         if (*ms > 0)
1697                 start = ast_tvnow();
1698         
1699         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1700                 do {
1701                         int kbrms = rms;
1702                         if (kbrms > 600000)
1703                                 kbrms = 600000;
1704                         res = poll(pfds, max, kbrms);
1705                         if (!res)
1706                                 rms -= kbrms;
1707                 } while (!res && (rms > 0));
1708         } else {
1709                 res = poll(pfds, max, rms);
1710         }
1711         for (x = 0; x < n; x++)
1712                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1713         if (res < 0) { /* Simulate a timeout if we were interrupted */
1714                 if (errno != EINTR)
1715                         *ms = -1;
1716                 return NULL;
1717         }
1718         if (whentohangup) {   /* if we have a timeout, check who expired */
1719                 time(&now);
1720                 for (x = 0; x < n; x++) {
1721                         if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1722                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1723                                 if (winner == NULL)
1724                                         winner = c[x];
1725                         }
1726                 }
1727         }
1728         if (res == 0) { /* no fd ready, reset timeout and done */
1729                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1730                 return winner;
1731         }
1732         /*
1733          * Then check if any channel or fd has a pending event.
1734          * Remember to check channels first and fds last, as they
1735          * must have priority on setting 'winner'
1736          */
1737         for (x = 0; x < max; x++) {
1738                 res = pfds[x].revents;
1739                 if (res == 0)
1740                         continue;
1741                 if (fdmap[x].chan >= 0) {       /* this is a channel */
1742                         winner = c[fdmap[x].chan];      /* override previous winners */
1743                         if (res & POLLPRI)
1744                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1745                         else
1746                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1747                         winner->fdno = fdmap[x].fdno;
1748                 } else {                        /* this is an fd */
1749                         if (outfd)
1750                                 *outfd = pfds[x].fd;
1751                         if (exception)
1752                                 *exception = (res & POLLPRI) ? -1 : 0;
1753                         winner = NULL;
1754                 }
1755         }
1756         if (*ms > 0) {
1757                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1758                 if (*ms < 0)
1759                         *ms = 0;
1760         }
1761         return winner;
1762 }
1763
1764 #ifdef HAVE_EPOLL
1765 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
1766 {
1767         struct timeval start = { 0 , 0 };
1768         int res = 0;
1769         struct epoll_event ev[1];
1770         long whentohangup = 0, rms = *ms;
1771         time_t now;
1772         struct ast_channel *winner = NULL;
1773         struct ast_epoll_data *aed = NULL;
1774
1775         ast_channel_lock(chan);
1776
1777         /* See if this channel needs to be masqueraded */
1778         if (chan->masq && ast_do_masquerade(chan)) {
1779                 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
1780                 *ms = -1;
1781                 ast_channel_unlock(chan);
1782                 return NULL;
1783         }
1784
1785         /* Figure out their timeout */
1786         if (chan->whentohangup) {
1787                 time(&now);
1788                 if ((whentohangup = chan->whentohangup - now) < 1) {
1789                         /* They should already be hungup! */
1790                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1791                         ast_channel_unlock(chan);
1792                         return NULL;
1793                 }
1794                 /* If this value is smaller then the current one... make it priority */
1795                 whentohangup *= 1000;
1796                 if (rms > whentohangup)
1797                         rms = whentohangup;
1798         }
1799
1800         ast_channel_unlock(chan);
1801
1802         /* Time to make this channel block... */
1803         CHECK_BLOCKING(chan);
1804
1805         if (*ms > 0)
1806                 start = ast_tvnow();
1807
1808         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
1809         res = epoll_wait(chan->epfd, ev, 1, rms);
1810
1811         /* Stop blocking */
1812         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1813
1814         /* Simulate a timeout if we were interrupted */
1815         if (res < 0) {
1816                 if (errno != EINTR)
1817                         *ms = -1;
1818                 return NULL;
1819         }
1820
1821         /* If this channel has a timeout see if it expired */
1822         if (chan->whentohangup) {
1823                 time(&now);
1824                 if (now >= chan->whentohangup) {
1825                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1826                         winner = chan;
1827                 }
1828         }
1829
1830         /* No fd ready, reset timeout and be done for now */
1831         if (!res) {
1832                 *ms = 0;
1833                 return winner;
1834         }
1835
1836         /* See what events are pending */
1837         aed = ev[0].data.ptr;
1838         chan->fdno = aed->which;
1839         if (ev[0].events & EPOLLPRI)
1840                 ast_set_flag(chan, AST_FLAG_EXCEPTION);
1841         else
1842                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1843
1844         if (*ms > 0) {
1845                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1846                 if (*ms < 0)
1847                         *ms = 0;
1848         }
1849
1850         return chan;
1851 }
1852
1853 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
1854 {
1855         struct timeval start = { 0 , 0 };
1856         int res = 0, i;
1857         struct epoll_event ev[25] = { { 0, } };
1858         long whentohangup = 0, diff, rms = *ms;
1859         time_t now;
1860         struct ast_channel *winner = NULL;
1861
1862         for (i = 0; i < n; i++) {
1863                 ast_channel_lock(c[i]);
1864                 if (c[i]->masq && ast_do_masquerade(c[i])) {
1865                         ast_log(LOG_WARNING, "Masquerade failed\n");
1866                         *ms = -1;
1867                         ast_channel_unlock(c[i]);
1868                         return NULL;
1869                 }
1870                 if (c[i]->whentohangup) {
1871                         if (!whentohangup)
1872                                 time(&now);
1873                         if ((diff = c[i]->whentohangup - now) < 1) {
1874                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1875                                 ast_channel_unlock(c[i]);
1876                                 return c[i];
1877                         }
1878                         if (!whentohangup || (diff < whentohangup))
1879                                 whentohangup = diff;
1880                 }
1881                 ast_channel_unlock(c[i]);
1882                 CHECK_BLOCKING(c[i]);
1883         }
1884
1885         rms = *ms;
1886         if (whentohangup) {
1887                 rms = whentohangup * 1000;
1888                 if (*ms >= 0 && *ms < rms)
1889                         rms = *ms;
1890         }
1891
1892         if (*ms > 0)
1893                 start = ast_tvnow();
1894
1895         res = epoll_wait(c[0]->epfd, ev, 25, rms);
1896
1897         for (i = 0; i < n; i++)
1898                 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
1899
1900         if (res < 0) {
1901                 if (errno != EINTR)
1902                         *ms = -1;
1903                 return NULL;
1904         }
1905
1906         if (whentohangup) {
1907                 time(&now);
1908                 for (i = 0; i < n; i++) {
1909                         if (c[i]->whentohangup && now >= c[i]->whentohangup) {
1910                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1911                                 if (!winner)
1912                                         winner = c[i];
1913                         }
1914                 }
1915         }
1916
1917         if (!res) {
1918                 *ms = 0;
1919                 return winner;
1920         }
1921
1922         for (i = 0; i < 25; i++) {
1923                 struct ast_epoll_data *aed = ev[i].data.ptr;
1924
1925                 if (!ev[i].events || !aed)
1926                         continue;
1927
1928                 winner = aed->chan;
1929                 if (ev[i].events & EPOLLPRI)
1930                         ast_set_flag(winner, AST_FLAG_EXCEPTION);
1931                 else
1932                         ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1933                 winner->fdno = aed->which;
1934         }
1935
1936         if (*ms > 0) {
1937                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1938                 if (*ms < 0)
1939                         *ms = 0;
1940         }
1941
1942         return winner;
1943 }
1944
1945 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1946                                         int *exception, int *outfd, int *ms)
1947 {
1948         /* Clear all provided values in one place. */
1949         if (outfd)
1950                 *outfd = -99999;
1951         if (exception)
1952                 *exception = 0;
1953
1954         /* If no epoll file descriptor is available resort to classic nandfds */
1955         if (!n || nfds || c[0]->epfd == -1)
1956                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
1957         else if (!nfds && n == 1)
1958                 return ast_waitfor_nandfds_simple(c[0], ms);
1959         else
1960                 return ast_waitfor_nandfds_complex(c, n, ms);
1961 }
1962 #endif
1963
1964 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1965 {
1966         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1967 }
1968
1969 int ast_waitfor(struct ast_channel *c, int ms)
1970 {
1971         int oldms = ms; /* -1 if no timeout */
1972
1973         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1974         if ((ms < 0) && (oldms < 0))
1975                 ms = 0;
1976         return ms;
1977 }
1978
1979 /* XXX never to be called with ms = -1 */
1980 int ast_waitfordigit(struct ast_channel *c, int ms)
1981 {
1982         return ast_waitfordigit_full(c, ms, -1, -1);
1983 }
1984
1985 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
1986 {
1987         int res = -1;
1988 #ifdef HAVE_ZAPTEL
1989         if (c->timingfd > -1) {
1990                 if (!func) {
1991                         samples = 0;
1992                         data = 0;
1993                 }
1994                 ast_debug(1, "Scheduling timer at %d sample intervals\n", samples);
1995                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1996                 c->timingfunc = func;
1997                 c->timingdata = data;
1998         }
1999 #endif  
2000         return res;
2001 }
2002
2003 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2004 {
2005         /* Stop if we're a zombie or need a soft hangup */
2006         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2007                 return -1;
2008
2009         /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2010         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2011
2012         /* Wait for a digit, no more than ms milliseconds total. */
2013         
2014         while (ms) {
2015                 struct ast_channel *rchan;
2016                 int outfd=-1;
2017
2018                 errno = 0;
2019                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2020                 
2021                 if (!rchan && outfd < 0 && ms) {
2022                         if (errno == 0 || errno == EINTR)
2023                                 continue;
2024                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2025                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2026                         return -1;
2027                 } else if (outfd > -1) {
2028                         /* The FD we were watching has something waiting */
2029                         ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2030                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2031                         return 1;
2032                 } else if (rchan) {
2033                         int res;
2034                         struct ast_frame *f = ast_read(c);
2035                         if (!f)
2036                                 return -1;
2037
2038                         switch (f->frametype) {
2039                         case AST_FRAME_DTMF_BEGIN:
2040                                 break;
2041                         case AST_FRAME_DTMF_END:
2042                                 res = f->subclass;
2043                                 ast_frfree(f);
2044                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2045                                 return res;
2046                         case AST_FRAME_CONTROL:
2047                                 switch (f->subclass) {
2048                                 case AST_CONTROL_HANGUP:
2049                                         ast_frfree(f);
2050                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2051                                         return -1;
2052                                 case AST_CONTROL_RINGING:
2053                                 case AST_CONTROL_ANSWER:
2054                                         /* Unimportant */
2055                                         break;
2056                                 default:
2057                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2058                                         break;
2059                                 }
2060                                 break;
2061                         case AST_FRAME_VOICE:
2062                                 /* Write audio if appropriate */
2063                                 if (audiofd > -1)
2064                                         write(audiofd, f->data, f->datalen);
2065                         default:
2066                                 /* Ignore */
2067                                 break;
2068                         }
2069                         ast_frfree(f);
2070                 }
2071         }
2072
2073         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2074
2075         return 0; /* Time is up */
2076 }
2077
2078 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2079 {
2080         manager_event(EVENT_FLAG_DTMF,
2081                         "DTMF",
2082                         "Channel: %s\r\n"
2083                         "Uniqueid: %s\r\n"
2084                         "Digit: %c\r\n"
2085                         "Direction: %s\r\n"
2086                         "Begin: %s\r\n"
2087                         "End: %s\r\n",
2088                         chan->name, chan->uniqueid, digit, direction, begin, end);
2089 }
2090
2091 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2092 {
2093         if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2094                 void *tmp = chan->generatordata;
2095                 int res;
2096
2097                 if (chan->timingfunc) {
2098                         if (option_debug > 1)
2099                                 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2100                         ast_settimeout(chan, 0, NULL, NULL);
2101                 }
2102
2103                 chan->generatordata = NULL;     /* reset, to let writes go through */
2104                 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2105                 chan->generatordata = tmp;
2106                 if (res) {
2107                         if (option_debug > 1)
2108                                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2109                         ast_deactivate_generator(chan);
2110                 }
2111
2112         } else if (f->frametype == AST_FRAME_CNG) {
2113                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2114                         if (option_debug > 1)
2115                                 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2116                         ast_settimeout(chan, 160, generator_force, chan);
2117                 }
2118         }
2119 }
2120
2121 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2122 {
2123         struct ast_frame *f = NULL;     /* the return value */
2124         struct ast_channel *base = NULL;
2125         int blah;
2126         int prestate;
2127
2128         /* this function is very long so make sure there is only one return
2129          * point at the end (there is only one exception to this).
2130          */
2131         ast_channel_lock(chan);
2132         if (chan->masq) {
2133                 if (ast_do_masquerade(chan))
2134                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2135                 else
2136                         f =  &ast_null_frame;
2137                 goto done;
2138         }
2139
2140         /* Stop if we're a zombie or need a soft hangup */
2141         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2142                 if (chan->generator)
2143                         ast_deactivate_generator(chan);
2144                 goto done;
2145         }
2146         prestate = chan->_state;
2147
2148         /* Check if there's an underlying channel */
2149         if (chan->tech->get_base_channel && (base = chan->tech->get_base_channel(chan)) != chan) {
2150                 int count = 0;
2151                 while (!base || ast_mutex_trylock(&base->lock)) {
2152                         if (count++ > 10) {
2153                                 f = &ast_null_frame;
2154                                 goto done;
2155                         }
2156                         ast_mutex_unlock(&chan->lock);
2157                         usleep(1);
2158                         ast_mutex_lock(&chan->lock);
2159                         base = chan->tech->get_base_channel(chan);
2160                 }
2161                 ast_mutex_unlock(&chan->lock);
2162                 chan = base;
2163         }
2164
2165         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
2166             !ast_strlen_zero(chan->dtmfq) && 
2167                 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2168                 /* We have DTMF that has been deferred.  Return it now */
2169                 chan->dtmff.subclass = chan->dtmfq[0];
2170                 /* Drop first digit from the buffer */
2171                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2172                 f = &chan->dtmff;
2173                 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2174                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2175                         chan->dtmff.frametype = AST_FRAME_DTMF_END;
2176                 } else {
2177                         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);
2178                         chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2179                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2180                         chan->emulate_dtmf_digit = f->subclass;
2181                         chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2182                 }
2183                 chan->dtmf_tv = ast_tvnow();
2184                 goto done;
2185         }
2186         
2187         /* Read and ignore anything on the alertpipe, but read only
2188            one sizeof(blah) per frame that we send from it */
2189         if (chan->alertpipe[0] > -1)
2190                 read(chan->alertpipe[0], &blah, sizeof(blah));
2191
2192 #ifdef HAVE_ZAPTEL
2193         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2194                 int res;
2195
2196                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2197                 blah = -1;
2198                 /* IF we can't get event, assume it's an expired as-per the old interface */
2199                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2200                 if (res)
2201                         blah = ZT_EVENT_TIMER_EXPIRED;
2202
2203                 if (blah == ZT_EVENT_TIMER_PING) {
2204                         if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2205                                 /* Acknowledge PONG unless we need it again */
2206                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2207                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2208                                 }
2209                         }
2210                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2211                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2212                         if (chan->timingfunc) {
2213                                 chan->timingfunc(chan->timingdata);
2214                         } else {
2215                                 blah = 0;
2216                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2217                                 chan->timingdata = NULL;
2218                         }
2219                         ast_channel_unlock(chan);
2220                         /* cannot 'goto done' because the channel is already unlocked */
2221                         return &ast_null_frame;
2222                 } else
2223                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2224         } else
2225 #endif
2226         if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2227                 /* if the AST_GENERATOR_FD is set, call the generator with args
2228                  * set to -1 so it can do whatever it needs to.
2229                  */
2230                 void *tmp = chan->generatordata;
2231                 chan->generatordata = NULL;     /* reset to let ast_write get through */
2232                 chan->generator->generate(chan, tmp, -1, -1);
2233                 chan->generatordata = tmp;
2234                 f = &ast_null_frame;
2235                 goto done;
2236         }
2237
2238         /* Check for pending read queue */
2239         if (!AST_LIST_EMPTY(&chan->readq)) {
2240                 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2241                 /* Interpret hangup and return NULL */
2242                 /* XXX why not the same for frames from the channel ? */
2243                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2244                         ast_frfree(f);
2245                         f = NULL;
2246                 }
2247         } else {
2248                 chan->blocker = pthread_self();
2249                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2250                         if (chan->tech->exception)
2251                                 f = chan->tech->exception(chan);
2252                         else {
2253                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2254                                 f = &ast_null_frame;
2255                         }
2256                         /* Clear the exception flag */
2257                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2258                 } else if (chan->tech->read)
2259                         f = chan->tech->read(chan);
2260                 else
2261                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2262         }
2263
2264         if (f) {
2265                 /* if the channel driver returned more than one frame, stuff the excess
2266                    into the readq for the next ast_read call (note that we can safely assume
2267                    that the readq is empty, because otherwise we would not have called into
2268                    the channel driver and f would be only a single frame)
2269                 */
2270                 if (AST_LIST_NEXT(f, frame_list)) {
2271                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2272                         AST_LIST_NEXT(f, frame_list) = NULL;
2273                 }
2274
2275                 switch (f->frametype) {
2276                 case AST_FRAME_CONTROL:
2277                         if (f->subclass == AST_CONTROL_ANSWER) {
2278                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2279                                         ast_debug(1, "Ignoring answer on an inbound call!\n");
2280                                         ast_frfree(f);
2281                                         f = &ast_null_frame;
2282                                 } else if (prestate == AST_STATE_UP) {
2283                                         ast_debug(1, "Dropping duplicate answer!\n");
2284                                         ast_frfree(f);
2285                                         f = &ast_null_frame;
2286                                 } else {
2287                                         /* Answer the CDR */
2288                                         ast_setstate(chan, AST_STATE_UP);
2289                                         if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2290                                                                                  to keep from throwing off the basic order of the universe,
2291                                                                                  we will try to keep this cdr from getting posted. */
2292                                                 chan->cdr = ast_cdr_alloc();
2293                                                 ast_cdr_init(chan->cdr, chan);
2294                                                 ast_cdr_start(chan->cdr);
2295                                         }
2296                                         
2297                                         ast_cdr_answer(chan->cdr);
2298                                 }
2299                         }
2300                         break;
2301                 case AST_FRAME_DTMF_END:
2302                         send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2303                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2304                         /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2305                          * However, only let emulation be forced if the other end cares about BEGIN frames */
2306                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2307                                 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2308                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2309                                         ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2310                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2311                                 } else
2312                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2313                                 ast_frfree(f);
2314                                 f = &ast_null_frame;
2315                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2316                                 if (!ast_tvzero(chan->dtmf_tv) && 
2317                                     ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2318                                         /* If it hasn't been long enough, defer this digit */
2319                                         if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2320                                                 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2321                                                 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2322                                         } else
2323                                                 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2324                                         ast_frfree(f);
2325                                         f = &ast_null_frame;
2326                                 } else {
2327                                         /* There was no begin, turn this into a begin and send the end later */
2328                                         f->frametype = AST_FRAME_DTMF_BEGIN;
2329                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2330                                         chan->emulate_dtmf_digit = f->subclass;
2331                                         chan->dtmf_tv = ast_tvnow();
2332                                         if (f->len) {
2333                                                 if (f->len > AST_MIN_DTMF_DURATION)
2334                                                         chan->emulate_dtmf_duration = f->len;
2335                                                 else 
2336                                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2337                                         } else
2338                                                 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2339                                         ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2340                                 }
2341                                 if (chan->audiohooks) {
2342                                         struct ast_frame *old_frame = f;
2343                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2344                                         if (old_frame != f)
2345                                                 ast_frfree(old_frame);
2346                                 }
2347                         } else {
2348                                 struct timeval now = ast_tvnow();
2349                                 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2350                                         ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2351                                         ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2352                                         if (!f->len)
2353                                                 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2354                                 } else if (!f->len) {
2355                                         ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2356                                         f->len = AST_MIN_DTMF_DURATION;
2357                                 }
2358                                 if (f->len < AST_MIN_DTMF_DURATION) {
2359                                         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);
2360                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2361                                         chan->emulate_dtmf_digit = f->subclass;
2362                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2363                                         ast_frfree(f);
2364                                         f = &ast_null_frame;
2365                                 } else {
2366                                         ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2367                                         chan->dtmf_tv = now;
2368                                 }
2369                                 if (chan->audiohooks) {
2370                                         struct ast_frame *old_frame = f;
2371                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2372                                         if (old_frame != f)
2373                                                 ast_frfree(old_frame);
2374                                 }
2375                         }
2376                         break;
2377                 case AST_FRAME_DTMF_BEGIN:
2378                         send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2379                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2380                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY) || 
2381                             (!ast_tvzero(chan->dtmf_tv) && 
2382                               ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2383                                 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2384                                 ast_frfree(f);
2385                                 f = &ast_null_frame;
2386                         } else {
2387                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2388                                 chan->dtmf_tv = ast_tvnow();
2389                                 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2390                         }
2391                         break;
2392                 case AST_FRAME_NULL:
2393                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2394                                 struct timeval now = ast_tvnow();
2395                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2396                                         chan->emulate_dtmf_duration = 0;
2397                                         ast_frfree(f);
2398                                         f = &chan->dtmff;
2399                                         f->frametype = AST_FRAME_DTMF_END;
2400                                         f->subclass = chan->emulate_dtmf_digit;
2401                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2402                                         chan->dtmf_tv = now;
2403                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2404                                         chan->emulate_dtmf_digit = 0;
2405                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2406                                 }
2407                         }
2408                         break;
2409                 case AST_FRAME_VOICE:
2410                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2411                          * is reached , because we want to make sure we pass at least one
2412                          * voice frame through before starting the next digit, to ensure a gap
2413                          * between DTMF digits. */
2414                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2415                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2416                                 chan->emulate_dtmf_digit = 0;
2417                         }
2418
2419                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2420                                 if (dropaudio)
2421                                         ast_read_generator_actions(chan, f);
2422                                 ast_frfree(f);
2423                                 f = &ast_null_frame;
2424                         }
2425
2426                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2427                                 struct timeval now = ast_tvnow();
2428                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2429                                         chan->emulate_dtmf_duration = 0;
2430                                         ast_frfree(f);
2431                                         f = &chan->dtmff;
2432                                         f->frametype = AST_FRAME_DTMF_END;
2433                                         f->subclass = chan->emulate_dtmf_digit;
2434                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2435                                         chan->dtmf_tv = now;
2436                                         if (chan->audiohooks) {
2437                                                 struct ast_frame *old_frame = f;
2438                                                 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2439                                                 if (old_frame != f)
2440                                                         ast_frfree(old_frame);
2441                                         }
2442                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2443                                 } else {
2444                                         /* Drop voice frames while we're still in the middle of the digit */
2445                                         ast_frfree(f);
2446                                         f = &ast_null_frame;
2447                                 }
2448                         } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2449                                 /* This frame can't be from the current native formats -- drop it on the
2450                                    floor */
2451                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2452                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2453                                 ast_frfree(f);
2454                                 f = &ast_null_frame;
2455                         } else if ((f->frametype == AST_FRAME_VOICE)) {
2456                                 /* Send frame to audiohooks if present */
2457                                 if (chan->audiohooks) {
2458                                         struct ast_frame *old_frame = f;
2459                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2460                                         if (old_frame != f)
2461                                                 ast_frfree(old_frame);
2462                                 }
2463                                 if (chan->monitor && chan->monitor->read_stream ) {
2464                                         /* XXX what does this do ? */
2465 #ifndef MONITOR_CONSTANT_DELAY
2466                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2467                                         if (jump >= 0) {
2468                                                 jump = chan->outsmpl - chan->insmpl;
2469                                                 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2470                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2471                                                 chan->insmpl += jump + f->samples;
2472                                         } else
2473                                                 chan->insmpl+= f->samples;
2474 #else
2475                                         int jump = chan->outsmpl - chan->insmpl;
2476                                         if (jump - MONITOR_DELAY >= 0) {
2477                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2478                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2479                                                 chan->insmpl += jump;
2480                                         } else
2481                                                 chan->insmpl += f->samples;
2482 #endif
2483                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2484                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2485                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2486                                         }
2487                                 }
2488
2489                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2490                                         f = &ast_null_frame;
2491                                 else
2492                                         /* Run generator sitting on the line if timing device not available
2493                                          * and synchronous generation of outgoing frames is necessary       */
2494                                         ast_read_generator_actions(chan, f);
2495                         }
2496                 default:
2497                         /* Just pass it on! */
2498                         break;
2499                 }
2500         } else {
2501                 /* Make sure we always return NULL in the future */
2502                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2503                 if (chan->generator)
2504                         ast_deactivate_generator(chan);
2505                 /* End the CDR if appropriate */
2506                 if (chan->cdr)
2507                         ast_cdr_end(chan->cdr);
2508         }
2509
2510         /* High bit prints debugging */
2511         if (chan->fin & DEBUGCHAN_FLAG)
2512                 ast_frame_dump(chan->name, f, "<<");
2513         chan->fin = FRAMECOUNT_INC(chan->fin);
2514
2515 done:
2516         if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2517                 chan->generator->digit(chan, f->subclass);
2518
2519         ast_channel_unlock(chan);
2520         return f;
2521 }
2522
2523 int ast_internal_timing_enabled(struct ast_channel *chan)
2524 {
2525         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2526         ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2527         return ret;
2528 }
2529
2530 struct ast_frame *ast_read(struct ast_channel *chan)
2531 {
2532         return __ast_read(chan, 0);
2533 }
2534
2535 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2536 {
2537         return __ast_read(chan, 1);
2538 }
2539
2540 int ast_indicate(struct ast_channel *chan, int condition)
2541 {
2542         return ast_indicate_data(chan, condition, NULL, 0);
2543 }
2544
2545 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2546 {
2547         int res = -1;
2548
2549         ast_channel_lock(chan);
2550         /* Stop if we're a zombie or need a soft hangup */
2551         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2552                 ast_channel_unlock(chan);
2553                 return -1;
2554         }
2555         if (chan->tech->indicate)
2556                 res = chan->tech->indicate(chan, condition, data, datalen);
2557         ast_channel_unlock(chan);
2558         if (!chan->tech->indicate || res) {
2559                 /*
2560                  * Device does not support (that) indication, lets fake
2561                  * it by doing our own tone generation. (PM2002)
2562                  */
2563                 if (condition < 0)
2564                         ast_playtones_stop(chan);
2565                 else {
2566                         const struct ind_tone_zone_sound *ts = NULL;
2567                         switch (condition) {
2568                         case AST_CONTROL_RINGING:
2569                                 ts = ast_get_indication_tone(chan->zone, "ring");
2570                                 break;
2571                         case AST_CONTROL_BUSY:
2572                                 ts = ast_get_indication_tone(chan->zone, "busy");
2573                                 break;
2574                         case AST_CONTROL_CONGESTION:
2575                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2576                                 break;
2577                         }
2578                         if (ts && ts->data[0]) {
2579                                 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2580                                 ast_playtones_start(chan,0,ts->data, 1);
2581                                 res = 0;
2582                         } else if (condition == AST_CONTROL_PROGRESS) {
2583                                 /* ast_playtones_stop(chan); */
2584                         } else if (condition == AST_CONTROL_PROCEEDING) {
2585                                 /* Do nothing, really */
2586                         } else if (condition == AST_CONTROL_HOLD) {
2587                                 /* Do nothing.... */
2588                         } else if (condition == AST_CONTROL_UNHOLD) {
2589                                 /* Do nothing.... */
2590                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2591                                 /* Do nothing.... */
2592                         } else {
2593                                 /* not handled */
2594                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2595                                 res = -1;
2596                         }
2597                 }
2598         }
2599         return res;
2600 }
2601
2602 int ast_recvchar(struct ast_channel *chan, int timeout)
2603 {
2604         int c;
2605         char *buf = ast_recvtext(chan, timeout);
2606         if (buf == NULL)
2607                 return -1;      /* error or timeout */
2608         c = *(unsigned char *)buf;
2609         ast_free(buf);
2610         return c;
2611 }
2612
2613 char *ast_recvtext(struct ast_channel *chan, int timeout)
2614 {
2615         int res, done = 0;
2616         char *buf = NULL;
2617         
2618         while (!done) {
2619                 struct ast_frame *f;
2620                 if (ast_check_hangup(chan))
2621                         break;
2622                 res = ast_waitfor(chan, timeout);
2623                 if (res <= 0) /* timeout or error */
2624                         break;
2625                 timeout = res;  /* update timeout */
2626                 f = ast_read(chan);
2627                 if (f == NULL)
2628                         break; /* no frame */
2629                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2630                         done = 1;       /* force a break */
2631                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2632                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2633                         done = 1;
2634                 }
2635                 ast_frfree(f);
2636         }
2637         return buf;
2638 }
2639
2640 int ast_sendtext(struct ast_channel *chan, const char *text)
2641 {
2642         int res = 0;
2643         /* Stop if we're a zombie or need a soft hangup */
2644         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2645                 return -1;
2646         CHECK_BLOCKING(chan);
2647         if (chan->tech->send_text)
2648                 res = chan->tech->send_text(chan, text);
2649         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2650         return res;
2651 }
2652
2653 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2654 {
2655         /* Device does not support DTMF tones, lets fake
2656          * it by doing our own generation. */
2657         static const char* dtmf_tones[] = {
2658                 "941+1336", /* 0 */
2659                 "697+1209", /* 1 */
2660                 "697+1336", /* 2 */
2661                 "697+1477", /* 3 */
2662                 "770+1209", /* 4 */
2663                 "770+1336", /* 5 */
2664                 "770+1477", /* 6 */
2665                 "852+1209", /* 7 */
2666                 "852+1336", /* 8 */
2667                 "852+1477", /* 9 */
2668                 "697+1633", /* A */
2669                 "770+1633", /* B */
2670                 "852+1633", /* C */
2671                 "941+1633", /* D */
2672                 "941+1209", /* * */
2673                 "941+1477"  /* # */
2674         };
2675
2676         if (!chan->tech->send_digit_begin)
2677                 return 0;
2678
2679         if (!chan->tech->send_digit_begin(chan, digit))
2680                 return 0;
2681
2682         if (digit >= '0' && digit <='9')
2683                 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2684         else if (digit >= 'A' && digit <= 'D')
2685                 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2686         else if (digit == '*')
2687                 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2688         else if (digit == '#')
2689                 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2690         else {
2691                 /* not handled */
2692                 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2693         }
2694
2695         return 0;
2696 }
2697
2698 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2699 {
2700         int res = -1;
2701
2702         if (chan->tech->send_digit_end)
2703                 res = chan->tech->send_digit_end(chan, digit, duration);
2704
2705         if (res && chan->generator)
2706                 ast_playtones_stop(chan);
2707         
2708         return 0;
2709 }
2710
2711 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
2712 {
2713         if (chan->tech->send_digit_begin) {
2714                 ast_senddigit_begin(chan, digit);
2715                 ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2716         }
2717         
2718         return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2719 }
2720
2721 int ast_prod(struct ast_channel *chan)
2722 {
2723         struct ast_frame a = { AST_FRAME_VOICE };
2724         char nothing[128];
2725
2726         /* Send an empty audio frame to get things moving */
2727         if (chan->_state != AST_STATE_UP) {
2728                 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2729                 a.subclass = chan->rawwriteformat;
2730                 a.data = nothing + AST_FRIENDLY_OFFSET;
2731                 a.src = "ast_prod";
2732                 if (ast_write(chan, &a))
2733                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2734         }
2735         return 0;
2736 }
2737
2738 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2739 {
2740         int res;
2741         if (!chan->tech->write_video)
2742                 return 0;
2743         res = ast_write(chan, fr);
2744         if (!res)
2745                 res = 1;
2746         return res;
2747 }
2748
2749 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2750 {
2751         int res = -1;
2752         struct ast_frame *f = NULL, *f2 = NULL;
2753
2754         /* Stop if we're a zombie or need a soft hangup */
2755         ast_channel_lock(chan);
2756         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2757                 goto done;
2758
2759         /* Handle any pending masquerades */
2760         if (chan->masq && ast_do_masquerade(chan)) {
2761                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2762                 goto done;
2763         }
2764         if (chan->masqr) {
2765                 res = 0;        /* XXX explain, why 0 ? */
2766                 goto done;
2767         }
2768         if (chan->generatordata) {
2769                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2770                         ast_deactivate_generator(chan);
2771                 else {
2772                         if (fr->frametype == AST_FRAME_DTMF_END) {
2773                                 /* There is a generator running while we're in the middle of a digit.
2774                                  * It's probably inband DTMF, so go ahead and pass it so it can
2775                                  * stop the generator */
2776                                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2777                                 ast_channel_unlock(chan);
2778                                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2779                                 ast_channel_lock(chan);
2780                                 CHECK_BLOCKING(chan);
2781                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2782                                 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2783                                 res = (chan->tech->indicate == NULL) ? 0 :
2784                                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2785                         }
2786                         res = 0;        /* XXX explain, why 0 ? */
2787                         goto done;
2788                 }
2789         }
2790         /* High bit prints debugging */
2791         if (chan->fout & DEBUGCHAN_FLAG)
2792                 ast_frame_dump(chan->name, fr, ">>");
2793         CHECK_BLOCKING(chan);
2794         switch (fr->frametype) {
2795         case AST_FRAME_CONTROL:
2796                 res = (chan->tech->indicate == NULL) ? 0 :
2797                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2798                 break;
2799         case AST_FRAME_DTMF_BEGIN:
2800                 if (chan->audiohooks) {
2801                         struct ast_frame *old_frame = fr;
2802                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2803                         if (old_frame != fr)
2804                                 f = fr;
2805                 }
2806                 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
2807                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2808                 ast_channel_unlock(chan);
2809                 res = ast_senddigit_begin(chan, fr->subclass);
2810                 ast_channel_lock(chan);
2811                 CHECK_BLOCKING(chan);
2812                 break;
2813         case AST_FRAME_DTMF_END:
2814                 if (chan->audiohooks) {
2815                         struct ast_frame *old_frame = fr;
2816                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2817                         if (old_frame != fr)
2818                                 f = fr;
2819                 }
2820                 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
2821                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2822                 ast_channel_unlock(chan);
2823                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2824                 ast_channel_lock(chan);
2825                 CHECK_BLOCKING(chan);
2826                 break;
2827         case AST_FRAME_TEXT:
2828                 if (fr->subclass == AST_FORMAT_T140) {
2829                         res = (chan->tech->write_text == NULL) ? 0 :
2830                                 chan->tech->write_text(chan, fr);
2831                 } else {
2832                         res = (chan->tech->send_text == NULL) ? 0 :
2833                                 chan->tech->send_text(chan, (char *) fr->data);
2834                 }
2835                 break;
2836         case AST_FRAME_HTML:
2837                 res = (chan->tech->send_html == NULL) ? 0 :
2838                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2839                 break;
2840         case AST_FRAME_VIDEO:
2841                 /* XXX Handle translation of video codecs one day XXX */
2842                 res = (chan->tech->write_video == NULL) ? 0 :
2843                         chan->tech->write_video(chan, fr);
2844                 break;
2845         case AST_FRAME_MODEM:
2846                 res = (chan->tech->write == NULL) ? 0 :
2847                         chan->tech->write(chan, fr);
2848                 break;
2849         case AST_FRAME_VOICE:
2850                 if (chan->tech->write == NULL)
2851                         break;  /*! \todo XXX should return 0 maybe ? */
2852
2853                 /* If audiohooks are present, write the frame out */
2854                 if (chan->audiohooks) {
2855                         struct ast_frame *old_frame = fr;
2856                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2857                         if (old_frame != fr)
2858                                 f2 = fr;
2859                 }
2860
2861                 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2862                 if (fr->subclass == chan->rawwriteformat)
2863                         f = fr;
2864                 else
2865                         f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2866
2867                 if (!f) {
2868                         res = 0;
2869                         break;
2870                 }
2871
2872                 /* If Monitor is running on this channel, then we have to write frames out there too */
2873                 if (chan->monitor && chan->monitor->write_stream) {
2874                         /* XXX must explain this code */
2875 #ifndef MONITOR_CONSTANT_DELAY
2876                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2877                         if (jump >= 0) {
2878                                 jump = chan->insmpl - chan->outsmpl;
2879                                 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2880                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2881                                 chan->outsmpl += jump + f->samples;
2882                         } else
2883                                 chan->outsmpl += f->samples;
2884 #else
2885                         int jump = chan->insmpl - chan->outsmpl;
2886                         if (jump - MONITOR_DELAY >= 0) {
2887                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2888                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2889                                 chan->outsmpl += jump;
2890                         } else
2891                                 chan->outsmpl += f->samples;
2892 #endif
2893                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2894                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2895                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2896                         }
2897                 }
2898
2899                 if (f) {
2900                         struct ast_channel *base = NULL;
2901                         if (!chan->tech->get_base_channel || chan == chan->tech->get_base_channel(chan))
2902                                 res = chan->tech->write(chan, f);
2903                         else {
2904                                 while (chan->tech->get_base_channel && (((base = chan->tech->get_base_channel(chan)) && ast_mutex_trylock(&base->lock)) || base == NULL)) {
2905                                         ast_mutex_unlock(&chan->lock);
2906                                         usleep(1);
2907                                         ast_mutex_lock(&chan->lock);
2908                                 }
2909                                 res = base->tech->write(base, f);
2910                                 ast_mutex_unlock(&base->lock);
2911                         }
2912                 } else
2913                         res = 0;
2914                 break;
2915         case AST_FRAME_NULL:
2916         case AST_FRAME_IAX:
2917                 /* Ignore these */
2918                 res = 0;
2919                 break;
2920         default:
2921                 /* At this point, fr is the incoming frame and f is NULL.  Channels do
2922                  * not expect to get NULL as a frame pointer and will segfault.  Hence,
2923                  * we output the original frame passed in. */
2924                 res = chan->tech->write(chan, fr);
2925                 break;
2926         }
2927
2928         if (f && f != fr)
2929                 ast_frfree(f);
2930         if (f2)
2931                 ast_frfree(f2);
2932         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2933         /* Consider a write failure to force a soft hangup */
2934         if (res < 0)
2935                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2936         else {
2937                 chan->fout = FRAMECOUNT_INC(chan->fout);
2938         }
2939 done:
2940         ast_channel_unlock(chan);
2941         return res;
2942 }
2943
2944 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2945                       struct ast_trans_pvt **trans, const int direction)
2946 {
2947         int native;
2948         int res;
2949         
2950         /* Make sure we only consider audio */
2951         fmt &= AST_FORMAT_AUDIO_MASK;
2952         
2953         native = chan->nativeformats;
2954         /* Find a translation path from the native format to one of the desired formats */
2955         if (!direction)
2956                 /* reading */
2957                 res = ast_translator_best_choice(&fmt, &native);
2958         else
2959                 /* writing */
2960                 res = ast_translator_best_choice(&native, &fmt);
2961
2962         if (res < 0) {
2963                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2964                         ast_getformatname(native), ast_getformatname(fmt));
2965                 return -1;
2966         }
2967         
2968         /* Now we have a good choice for both. */
2969         ast_channel_lock(chan);
2970
2971         if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2972                 /* the channel is already in these formats, so nothing to do */
2973                 ast_channel_unlock(chan);
2974                 return 0;
2975         }
2976
2977         *rawformat = native;
2978         /* User perspective is fmt */
2979         *format = fmt;
2980         /* Free any read translation we have right now */
2981         if (*trans)
2982                 ast_translator_free_path(*trans);
2983         /* Build a translation path from the raw format to the desired format */
2984         if (!direction)
2985                 /* reading */
2986                 *trans = ast_translator_build_path(*format, *rawformat);
2987         else
2988                 /* writing */
2989                 *trans = ast_translator_build_path(*rawformat, *format);
2990         ast_channel_unlock(chan);
2991         ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
2992                 direction ? "write" : "read", ast_getformatname(fmt));
2993         return 0;
2994 }
2995
2996 int ast_set_read_format(struct ast_channel *chan, int fmt)
2997 {
2998         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2999                           &chan->readtrans, 0);
3000 }
3001
3002 int ast_set_write_format(struct ast_channel *chan, int fmt)
3003 {
3004         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
3005                           &chan->writetrans, 1);
3006 }
3007
3008 const char *ast_channel_reason2str(int reason)
3009 {
3010         switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
3011         {
3012         case 0:
3013                 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
3014         case AST_CONTROL_HANGUP:
3015                 return "Hangup";
3016         case AST_CONTROL_RING:
3017                 return "Local Ring";
3018         case AST_CONTROL_RINGING:
3019                 return "Remote end Ringing";
3020         case AST_CONTROL_ANSWER:
3021                 return "Remote end has Answered";
3022         case AST_CONTROL_BUSY:
3023                 return "Remote end is Busy";
3024         case AST_CONTROL_CONGESTION:
3025                 return "Congestion (circuits busy)";
3026         default:
3027                 return "Unknown Reason!!";
3028         }
3029 }
3030
3031 struct ast_channel *__ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, struct outgoing_helper *oh)
3032 {
3033         int dummy_outstate;
3034         int cause = 0;
3035         struct ast_channel *chan;
3036         int res = 0;
3037         
3038         if (outstate)
3039                 *outstate = 0;
3040         else
3041                 outstate = &dummy_outstate;     /* make outstate always a valid pointer */
3042
3043         chan = ast_request(type, format, data, &cause);
3044         if (!chan) {
3045                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
3046                 /* compute error and return */
3047                 if (cause == AST_CAUSE_BUSY)
3048                         *outstate = AST_CONTROL_BUSY;
3049                 else if (cause == AST_CAUSE_CONGESTION)
3050                         *outstate = AST_CONTROL_CONGESTION;
3051                 return NULL;
3052         }
3053
3054         if (oh) {
3055                 if (oh->vars)   
3056                         ast_set_variables(chan, oh->vars);
3057                 /* XXX why is this necessary, for the parent_channel perhaps ? */
3058                 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
3059                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
3060                 if (oh->parent_channel) {
3061                         ast_channel_inherit_variables(oh->parent_channel, chan);
3062                         ast_channel_datastore_inherit(oh->parent_channel, chan);
3063                 }
3064                 if (oh->account)
3065                         ast_cdr_setaccount(chan, oh->account);  
3066         }
3067         ast_set_callerid(chan, cid_num, cid_name, cid_num);
3068
3069         
3070
3071         if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
3072                                 to keep from throwing off the basic order of the universe,
3073                                 we will try to keep this cdr from getting posted. */
3074                 chan->cdr = ast_cdr_alloc();
3075                 ast_cdr_init(chan->cdr, chan);
3076                 ast_cdr_start(chan->cdr);
3077         }
3078         if (ast_call(chan, data, 0)) {  /* ast_call failed... */
3079                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
3080