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