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