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