Kill off red blobs in most of main/*
[asterisk/asterisk.git] / main / file.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 Generic File Format Support.
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <dirent.h>
31 #include <sys/stat.h>
32 #include <sys/wait.h>
33 #include <math.h>
34
35 #include "asterisk/_private.h"  /* declare ast_file_init() */
36 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
37 #include "asterisk/mod_format.h"
38 #include "asterisk/cli.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/sched.h"
41 #include "asterisk/translate.h"
42 #include "asterisk/utils.h"
43 #include "asterisk/lock.h"
44 #include "asterisk/app.h"
45 #include "asterisk/pbx.h"
46 #include "asterisk/linkedlists.h"
47 #include "asterisk/module.h"
48 #include "asterisk/astobj2.h"
49 #include "asterisk/test.h"
50
51 /*! \brief
52  * The following variable controls the layout of localized sound files.
53  * If 0, use the historical layout with prefix just before the filename
54  * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
55  * if 1 put the prefix at the beginning of the filename
56  * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
57  * The latter permits a language to be entirely in one directory.
58  *
59  * This is settable in asterisk.conf.
60  */
61 int ast_language_is_prefix = 1;
62
63 static AST_RWLIST_HEAD_STATIC(formats, ast_format_def);
64
65 int __ast_format_def_register(const struct ast_format_def *f, struct ast_module *mod)
66 {
67         struct ast_format_def *tmp;
68
69         AST_RWLIST_WRLOCK(&formats);
70         AST_RWLIST_TRAVERSE(&formats, tmp, list) {
71                 if (!strcasecmp(f->name, tmp->name)) {
72                         AST_RWLIST_UNLOCK(&formats);
73                         ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
74                         return -1;
75                 }
76         }
77         if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
78                 AST_RWLIST_UNLOCK(&formats);
79                 return -1;
80         }
81         *tmp = *f;
82         tmp->module = mod;
83         if (tmp->buf_size) {
84                 /*
85                  * Align buf_size properly, rounding up to the machine-specific
86                  * alignment for pointers.
87                  */
88                 struct _test_align { void *a, *b; } p;
89                 int align = (char *)&p.b - (char *)&p.a;
90                 tmp->buf_size = ((f->buf_size + align - 1) / align) * align;
91         }
92
93         memset(&tmp->list, 0, sizeof(tmp->list));
94
95         AST_RWLIST_INSERT_HEAD(&formats, tmp, list);
96         AST_RWLIST_UNLOCK(&formats);
97         ast_verb(2, "Registered file format %s, extension(s) %s\n", f->name, f->exts);
98
99         return 0;
100 }
101
102 int ast_format_def_unregister(const char *name)
103 {
104         struct ast_format_def *tmp;
105         int res = -1;
106
107         AST_RWLIST_WRLOCK(&formats);
108         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
109                 if (!strcasecmp(name, tmp->name)) {
110                         AST_RWLIST_REMOVE_CURRENT(list);
111                         ast_free(tmp);
112                         res = 0;
113                 }
114         }
115         AST_RWLIST_TRAVERSE_SAFE_END;
116         AST_RWLIST_UNLOCK(&formats);
117
118         if (!res)
119                 ast_verb(2, "Unregistered format %s\n", name);
120         else
121                 ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
122
123         return res;
124 }
125
126 int ast_stopstream(struct ast_channel *tmp)
127 {
128         ast_channel_lock(tmp);
129
130         /* Stop a running stream if there is one */
131         if (ast_channel_stream(tmp)) {
132                 ast_closestream(ast_channel_stream(tmp));
133                 ast_channel_stream_set(tmp, NULL);
134                 if (ast_channel_oldwriteformat(tmp)->id && ast_set_write_format(tmp, ast_channel_oldwriteformat(tmp)))
135                         ast_log(LOG_WARNING, "Unable to restore format back to %s\n", ast_getformatname(ast_channel_oldwriteformat(tmp)));
136         }
137         /* Stop the video stream too */
138         if (ast_channel_vstream(tmp) != NULL) {
139                 ast_closestream(ast_channel_vstream(tmp));
140                 ast_channel_vstream_set(tmp, NULL);
141         }
142
143         ast_channel_unlock(tmp);
144
145         return 0;
146 }
147
148 int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
149 {
150         int res = -1;
151         if (f->frametype == AST_FRAME_VIDEO) {
152                 if (AST_FORMAT_GET_TYPE(fs->fmt->format.id) == AST_FORMAT_TYPE_AUDIO) {
153                         /* This is the audio portion.  Call the video one... */
154                         if (!fs->vfs && fs->filename) {
155                                 const char *type = ast_getformatname(&f->subclass.format);
156                                 fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
157                                 ast_debug(1, "Opened video output file\n");
158                         }
159                         if (fs->vfs)
160                                 return ast_writestream(fs->vfs, f);
161                         /* else ignore */
162                         return 0;
163                 }
164         } else if (f->frametype != AST_FRAME_VOICE) {
165                 ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
166                 return -1;
167         }
168         if (ast_format_cmp(&f->subclass.format, &fs->fmt->format) != AST_FORMAT_CMP_NOT_EQUAL) {
169                 res =  fs->fmt->write(fs, f);
170                 if (res < 0)
171                         ast_log(LOG_WARNING, "Natural write failed\n");
172                 else if (res > 0)
173                         ast_log(LOG_WARNING, "Huh??\n");
174         } else {
175                 /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
176                        the one we've setup a translator for, we do the "wrong thing" XXX */
177                 if (fs->trans && (ast_format_cmp(&f->subclass.format, &fs->lastwriteformat) != AST_FORMAT_CMP_EQUAL)) {
178                         ast_translator_free_path(fs->trans);
179                         fs->trans = NULL;
180                 }
181                 if (!fs->trans)
182                         fs->trans = ast_translator_build_path(&fs->fmt->format, &f->subclass.format);
183                 if (!fs->trans)
184                         ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
185                                 fs->fmt->name, ast_getformatname(&f->subclass.format));
186                 else {
187                         struct ast_frame *trf;
188                         ast_format_copy(&fs->lastwriteformat, &f->subclass.format);
189                         /* Get the translated frame but don't consume the original in case they're using it on another stream */
190                         if ((trf = ast_translate(fs->trans, f, 0))) {
191                                 struct ast_frame *cur;
192
193                                 /* the translator may have returned multiple frames, so process them */
194                                 for (cur = trf; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
195                                         if ((res = fs->fmt->write(fs, trf))) {
196                                                 ast_log(LOG_WARNING, "Translated frame write failed\n");
197                                                 break;
198                                         }
199                                 }
200                                 ast_frfree(trf);
201                         } else {
202                                 res = 0;
203                         }
204                 }
205         }
206         return res;
207 }
208
209 static int copy(const char *infile, const char *outfile)
210 {
211         int ifd, ofd, len;
212         char buf[4096]; /* XXX make it lerger. */
213
214         if ((ifd = open(infile, O_RDONLY)) < 0) {
215                 ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
216                 return -1;
217         }
218         if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, AST_FILE_MODE)) < 0) {
219                 ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
220                 close(ifd);
221                 return -1;
222         }
223         while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
224                 int res;
225                 if (len < 0) {
226                         ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
227                         break;
228                 }
229                 /* XXX handle partial writes */
230                 res = write(ofd, buf, len);
231                 if (res != len) {
232                         ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
233                         len = -1; /* error marker */
234                         break;
235                 }
236         }
237         close(ifd);
238         close(ofd);
239         if (len < 0) {
240                 unlink(outfile);
241                 return -1; /* error */
242         }
243         return 0;       /* success */
244 }
245
246 /*!
247  * \brief construct a filename. Absolute pathnames are preserved,
248  * relative names are prefixed by the sounds/ directory.
249  * The wav49 suffix is replaced by 'WAV'.
250  * Returns a malloc'ed string to be freed by the caller.
251  */
252 static char *build_filename(const char *filename, const char *ext)
253 {
254         char *fn = NULL;
255
256         if (!strcmp(ext, "wav49"))
257                 ext = "WAV";
258
259         if (filename[0] == '/') {
260                 if (asprintf(&fn, "%s.%s", filename, ext) < 0) {
261                         ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
262                         fn = NULL;
263                 }
264         } else {
265                 if (asprintf(&fn, "%s/sounds/%s.%s",
266                              ast_config_AST_DATA_DIR, filename, ext) < 0) {
267                         ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
268                         fn = NULL;
269                 }
270         }
271         return fn;
272 }
273
274 /* compare type against the list 'exts' */
275 /* XXX need a better algorithm */
276 static int exts_compare(const char *exts, const char *type)
277 {
278         char tmp[256];
279         char *stringp = tmp, *ext;
280
281         ast_copy_string(tmp, exts, sizeof(tmp));
282         while ((ext = strsep(&stringp, "|"))) {
283                 if (!strcmp(ext, type))
284                         return 1;
285         }
286
287         return 0;
288 }
289
290 /*! \internal \brief Close the file stream by canceling any pending read / write callbacks */
291 static void filestream_close(struct ast_filestream *f)
292 {
293         enum ast_format_type format_type = AST_FORMAT_GET_TYPE(f->fmt->format.id);
294
295         if (!f->owner) {
296                 return;
297         }
298
299         /* Stop a running stream if there is one */
300         switch (format_type)
301         {
302         case AST_FORMAT_TYPE_AUDIO:
303                 ast_channel_stream_set(f->owner, NULL);
304                 AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_streamid, ast_channel_streamid_set);
305                 ast_settimeout(f->owner, 0, NULL, NULL);
306                 break;
307         case AST_FORMAT_TYPE_VIDEO:
308                 ast_channel_vstream_set(f->owner, NULL);
309                 AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_vstreamid, ast_channel_vstreamid_set);
310                 break;
311         default:
312                 ast_log(AST_LOG_WARNING, "Unable to schedule deletion of filestream with unsupported type %s\n", f->fmt->name);
313                 break;
314         }
315 }
316
317 static void filestream_destructor(void *arg)
318 {
319         struct ast_filestream *f = arg;
320         int status;
321         int pid = -1;
322
323         /* Stop a running stream if there is one */
324         filestream_close(f);
325
326         /* destroy the translator on exit */
327         if (f->trans)
328                 ast_translator_free_path(f->trans);
329
330         if (f->realfilename && f->filename) {
331                 pid = ast_safe_fork(0);
332                 if (!pid) {
333                         execl("/bin/mv", "mv", "-f", f->filename, f->realfilename, SENTINEL);
334                         _exit(1);
335                 }
336                 else if (pid > 0) {
337                         /* Block the parent until the move is complete.*/
338                         waitpid(pid, &status, 0);
339                 }
340         }
341
342         if (f->filename)
343                 free(f->filename);
344         if (f->realfilename)
345                 free(f->realfilename);
346         if (f->fmt->close) {
347                 void (*closefn)(struct ast_filestream *) = f->fmt->close;
348                 closefn(f);
349         }
350         if (f->f)
351                 fclose(f->f);
352         if (f->vfs)
353                 ast_closestream(f->vfs);
354         if (f->write_buffer) {
355                 ast_free(f->write_buffer);
356         }
357         if (f->orig_chan_name)
358                 free((void *) f->orig_chan_name);
359         ast_module_unref(f->fmt->module);
360 }
361
362 static struct ast_filestream *get_filestream(struct ast_format_def *fmt, FILE *bfile)
363 {
364         struct ast_filestream *s;
365
366         int l = sizeof(*s) + fmt->buf_size + fmt->desc_size;    /* total allocation size */
367         if ( (s = ao2_alloc(l, filestream_destructor)) == NULL)
368                 return NULL;
369         s->fmt = fmt;
370         s->f = bfile;
371
372         if (fmt->desc_size)
373                 s->_private = ((char *)(s + 1)) + fmt->buf_size;
374         if (fmt->buf_size)
375                 s->buf = (char *)(s + 1);
376         s->fr.src = fmt->name;
377         return s;
378 }
379
380 /*
381  * Default implementations of open and rewrite.
382  * Only use them if you don't have expensive stuff to do.
383  */
384 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
385
386 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
387 {
388         struct ast_format_def *f = s->fmt;
389         int ret = -1;
390         int (*openfn)(struct ast_filestream *s);
391
392         if (mode == WRAP_OPEN && (openfn = f->open) && openfn(s))
393                 ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
394         else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
395                 ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
396         else {
397                 /* preliminary checks succeed. update usecount */
398                 ast_module_ref(f->module);
399                 ret = 0;
400         }
401         return ret;
402 }
403
404 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
405 {
406         return fn_wrapper(s, comment, WRAP_REWRITE);
407 }
408
409 static int open_wrapper(struct ast_filestream *s)
410 {
411         return fn_wrapper(s, NULL, WRAP_OPEN);
412 }
413
414 enum file_action {
415         ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
416         ACTION_DELETE,  /* delete file, return 0 on success, -1 on error */
417         ACTION_RENAME,  /* rename file. return 0 on success, -1 on error */
418         ACTION_OPEN,
419         ACTION_COPY     /* copy file. return 0 on success, -1 on error */
420 };
421
422 /*!
423  * \internal
424  * \brief perform various actions on a file. Second argument
425  * \note arg2 depends on the command:
426  *      unused for DELETE
427  *  optional ast_format_cap holding all the formats found for a file, for EXISTS.
428  *      destination file name (const char *) for COPY and RENAME
429  *      struct ast_channel * for OPEN
430  * if fmt is NULL, OPEN will return the first matching entry,
431  * whereas other functions will run on all matching entries.
432  */
433 static int filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
434 {
435         struct ast_format_def *f;
436         int res = (action == ACTION_EXISTS) ? 0 : -1;
437
438         AST_RWLIST_RDLOCK(&formats);
439         /* Check for a specific format */
440         AST_RWLIST_TRAVERSE(&formats, f, list) {
441                 char *stringp, *ext = NULL;
442
443                 if (fmt && !exts_compare(f->exts, fmt))
444                         continue;
445
446                 /* Look for a file matching the supported extensions.
447                  * The file must exist, and for OPEN, must match
448                  * one of the formats supported by the channel.
449                  */
450                 stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
451                 while ( (ext = strsep(&stringp, "|")) ) {
452                         struct stat st;
453                         char *fn = build_filename(filename, ext);
454
455                         if (fn == NULL)
456                                 continue;
457
458                         if ( stat(fn, &st) ) { /* file not existent */
459                                 ast_free(fn);
460                                 continue;
461                         }
462                         /* for 'OPEN' we need to be sure that the format matches
463                          * what the channel can process
464                          */
465                         if (action == ACTION_OPEN) {
466                                 struct ast_channel *chan = (struct ast_channel *)arg2;
467                                 FILE *bfile;
468                                 struct ast_filestream *s;
469
470                                 if ((ast_format_cmp(ast_channel_writeformat(chan), &f->format) == AST_FORMAT_CMP_NOT_EQUAL) &&
471                                      !(((AST_FORMAT_GET_TYPE(f->format.id) == AST_FORMAT_TYPE_AUDIO) && fmt) ||
472                                           ((AST_FORMAT_GET_TYPE(f->format.id) == AST_FORMAT_TYPE_VIDEO) && fmt))) {
473                                         ast_free(fn);
474                                         continue;       /* not a supported format */
475                                 }
476                                 if ( (bfile = fopen(fn, "r")) == NULL) {
477                                         ast_free(fn);
478                                         continue;       /* cannot open file */
479                                 }
480                                 s = get_filestream(f, bfile);
481                                 if (!s) {
482                                         fclose(bfile);
483                                         ast_free(fn);   /* cannot allocate descriptor */
484                                         continue;
485                                 }
486                                 if (open_wrapper(s)) {
487                                         ast_free(fn);
488                                         ast_closestream(s);
489                                         continue;       /* cannot run open on file */
490                                 }
491                                 if (st.st_size == 0) {
492                                         ast_log(LOG_WARNING, "File %s detected to have zero size.\n", fn);
493                                 }
494                                 /* ok this is good for OPEN */
495                                 res = 1;        /* found */
496                                 s->lasttimeout = -1;
497                                 s->fmt = f;
498                                 s->trans = NULL;
499                                 s->filename = NULL;
500                                 if (AST_FORMAT_GET_TYPE(s->fmt->format.id) == AST_FORMAT_TYPE_AUDIO) {
501                                         if (ast_channel_stream(chan))
502                                                 ast_closestream(ast_channel_stream(chan));
503                                         ast_channel_stream_set(chan, s);
504                                 } else {
505                                         if (ast_channel_vstream(chan))
506                                                 ast_closestream(ast_channel_vstream(chan));
507                                         ast_channel_vstream_set(chan, s);
508                                 }
509                                 ast_free(fn);
510                                 break;
511                         }
512                         switch (action) {
513                         case ACTION_OPEN:
514                                 break;  /* will never get here */
515
516                         case ACTION_EXISTS:     /* return the matching format */
517                                 /* if arg2 is present, it is a format capabilities structure.
518                                  * Add this format to the set of formats this file can be played in */
519                                 if (arg2) {
520                                         ast_format_cap_add((struct ast_format_cap *) arg2, &f->format);
521                                 }
522                                 res = 1; /* file does exist and format it exists in is returned in arg2 */
523                                 break;
524
525                         case ACTION_DELETE:
526                                 if ( (res = unlink(fn)) )
527                                         ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
528                                 break;
529
530                         case ACTION_RENAME:
531                         case ACTION_COPY: {
532                                 char *nfn = build_filename((const char *)arg2, ext);
533                                 if (!nfn)
534                                         ast_log(LOG_WARNING, "Out of memory\n");
535                                 else {
536                                         res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
537                                         if (res)
538                                                 ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
539                                                         action == ACTION_COPY ? "copy" : "rename",
540                                                          fn, nfn, strerror(errno));
541                                         ast_free(nfn);
542                                 }
543                             }
544                                 break;
545
546                         default:
547                                 ast_log(LOG_WARNING, "Unknown helper %d\n", action);
548                         }
549                         ast_free(fn);
550                 }
551         }
552         AST_RWLIST_UNLOCK(&formats);
553         return res;
554 }
555
556 static int is_absolute_path(const char *filename)
557 {
558         return filename[0] == '/';
559 }
560
561 /*!
562  * \brief test if a file exists for a given format.
563  * \note result_cap is OPTIONAL
564  * \retval 1, true and result_cap represents format capabilities file exists in.
565  * \retval 0, false
566  */
567 static int fileexists_test(const char *filename, const char *fmt, const char *lang,
568                            char *buf, int buflen, struct ast_format_cap *result_cap)
569 {
570         if (buf == NULL) {
571                 return 0;
572         }
573
574         if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
575                 if (lang) {
576                         snprintf(buf, buflen, "%s/%s", lang, filename);
577                 } else {
578                         snprintf(buf, buflen, "%s", filename);
579                 }
580         } else { /* old layout */
581                 strcpy(buf, filename);  /* first copy the full string */
582                 if (lang) {
583                         /* insert the language and suffix if needed */
584                         const char *c = strrchr(filename, '/');
585                         int offset = c ? c - filename + 1 : 0;  /* points right after the last '/' */
586                         snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
587                 }
588         }
589
590         return filehelper(buf, result_cap, fmt, ACTION_EXISTS);
591 }
592
593 /*!
594  * \brief helper routine to locate a file with a given format
595  * and language preference.
596  *
597  * \note Try preflang, preflang with stripped '_' suffices, or NULL.
598  *
599  * \note The last parameter(s) point to a buffer of sufficient size,
600  * which on success is filled with the matching filename.
601  *
602  * \param filename, name of the file.
603  * \param fmt, format to look for the file in. OPTIONAL
604  * \param preflang, the perfered language
605  * \param buf, returns the matching filename
606  * \param buflen, size of the buf
607  * \param result_cap, OPTIONAL format capabilities result structure
608  *        returns what formats the file was found in.
609  *
610  * \retval 1, true. file exists and result format is set
611  * \retval 0, false. file does not exist.
612  */
613 static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
614                            char *buf, int buflen, struct ast_format_cap *result_cap)
615 {
616         char *lang;
617
618         if (buf == NULL) {
619                 return 0;
620         }
621
622         /* We try languages in the following order:
623          *    preflang (may include dialect and style codes)
624          *    lang (preflang without dialect - if any)
625          *    <none>
626          *    default (unless the same as preflang or lang without dialect)
627          */
628
629         lang = ast_strdupa(preflang);
630
631         /* Try preferred language, including removing any style or dialect codes */
632         while (!ast_strlen_zero(lang)) {
633                 char *end;
634
635                 if (fileexists_test(filename, fmt, lang, buf, buflen, result_cap)) {
636                         return 1;
637                 }
638
639                 if ((end = strrchr(lang, '_')) != NULL) {
640                         *end = '\0';
641                         continue;
642                 }
643
644                 break;
645         }
646
647         /* Try without any language */
648         if (fileexists_test(filename, fmt, NULL, buf, buflen, result_cap)) {
649                 return 1;
650         }
651
652         /* Finally try the default language unless it was already tried before */
653         if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
654                 if ((fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen, result_cap)) > 0) {
655                         return 1;
656                 }
657         }
658
659         return 0;
660 }
661
662 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
663 {
664         return ast_openstream_full(chan, filename, preflang, 0);
665 }
666
667 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
668 {
669         /*
670          * Use fileexists_core() to find a file in a compatible
671          * language and format, set up a suitable translator,
672          * and open the stream.
673          */
674         struct ast_format_cap *file_fmt_cap;
675         int res;
676         int buflen;
677         char *buf;
678
679         if (!asis) {
680                 /* do this first, otherwise we detect the wrong writeformat */
681                 ast_stopstream(chan);
682                 if (ast_channel_generator(chan))
683                         ast_deactivate_generator(chan);
684         }
685         if (preflang == NULL)
686                 preflang = "";
687         buflen = strlen(preflang) + strlen(filename) + 4;
688         buf = alloca(buflen);
689         if (buf == NULL)
690                 return NULL;
691
692         if (!(file_fmt_cap = ast_format_cap_alloc_nolock())) {
693                 return NULL;
694         }
695         if (!fileexists_core(filename, NULL, preflang, buf, buflen, file_fmt_cap) ||
696                 !ast_format_cap_has_type(file_fmt_cap, AST_FORMAT_TYPE_AUDIO)) {
697
698                 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
699                 file_fmt_cap = ast_format_cap_destroy(file_fmt_cap);
700                 return NULL;
701         }
702
703         /* Set the channel to a format we can work with and save off the previous format. */
704         ast_format_copy(ast_channel_oldwriteformat(chan), ast_channel_writeformat(chan));
705         /* Set the channel to the best format that exists for the file. */
706         res = ast_set_write_format_from_cap(chan, file_fmt_cap);
707         /* don't need this anymore now that the channel's write format is set. */
708         file_fmt_cap = ast_format_cap_destroy(file_fmt_cap);
709
710         if (res == -1) {        /* No format available that works with this channel */
711                 return NULL;
712         }
713         res = filehelper(buf, chan, NULL, ACTION_OPEN);
714         if (res >= 0)
715                 return ast_channel_stream(chan);
716         return NULL;
717 }
718
719 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
720 {
721         /* As above, but for video. But here we don't have translators
722          * so we must enforce a format.
723          */
724         struct ast_format tmp_fmt;
725         struct ast_format_cap *tmp_cap;
726         char *buf;
727         int buflen;
728         const char *fmt;
729         int fd;
730
731         if (preflang == NULL)
732                 preflang = "";
733         buflen = strlen(preflang) + strlen(filename) + 4;
734         buf = alloca(buflen);
735         if (buf == NULL)
736                 return NULL;
737
738         /* is the channel capable of video without translation ?*/
739         if (!ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_FORMAT_TYPE_VIDEO)) {
740                 return NULL;
741         }
742         if (!(tmp_cap = ast_format_cap_alloc_nolock())) {
743                 return NULL;
744         }
745         /* Video is supported, so see what video formats exist for this file */
746         if (!fileexists_core(filename, NULL, preflang, buf, buflen, tmp_cap)) {
747                 tmp_cap = ast_format_cap_destroy(tmp_cap);
748                 return NULL;
749         }
750
751         /* iterate over file formats and pick the first one compatible with the channel's native formats */
752         ast_format_cap_iter_start(tmp_cap);
753         while (!ast_format_cap_iter_next(tmp_cap, &tmp_fmt)) {
754                 fmt = ast_getformatname(&tmp_fmt);
755                 if ((AST_FORMAT_GET_TYPE(tmp_fmt.id) != AST_FORMAT_TYPE_VIDEO) ||
756                         !ast_format_cap_iscompatible(ast_channel_nativeformats(chan), &tmp_fmt)) {
757                         continue;
758                 }
759
760                 fd = filehelper(buf, chan, fmt, ACTION_OPEN);
761                 if (fd >= 0) {
762                         ast_format_cap_iter_end(tmp_cap);
763                         tmp_cap = ast_format_cap_destroy(tmp_cap);
764                         return ast_channel_vstream(chan);
765                 }
766                 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
767         }
768         ast_format_cap_iter_end(tmp_cap);
769         tmp_cap = ast_format_cap_destroy(tmp_cap);
770
771         return NULL;
772 }
773
774 static struct ast_frame *read_frame(struct ast_filestream *s, int *whennext)
775 {
776         struct ast_frame *fr, *new_fr;
777
778         if (!s || !s->fmt) {
779                 return NULL;
780         }
781
782         if (!(fr = s->fmt->read(s, whennext))) {
783                 return NULL;
784         }
785
786         if (!(new_fr = ast_frisolate(fr))) {
787                 ast_frfree(fr);
788                 return NULL;
789         }
790
791         if (new_fr != fr) {
792                 ast_frfree(fr);
793                 fr = new_fr;
794         }
795
796         return fr;
797 }
798
799 struct ast_frame *ast_readframe(struct ast_filestream *s)
800 {
801         int whennext = 0;
802
803         return read_frame(s, &whennext);
804 }
805
806 enum fsread_res {
807         FSREAD_FAILURE,
808         FSREAD_SUCCESS_SCHED,
809         FSREAD_SUCCESS_NOSCHED,
810 };
811
812 static int ast_fsread_audio(const void *data);
813
814 static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
815 {
816         int whennext = 0;
817
818         while (!whennext) {
819                 struct ast_frame *fr;
820
821                 if (s->orig_chan_name && strcasecmp(ast_channel_name(s->owner), s->orig_chan_name)) {
822                         goto return_failure;
823                 }
824
825                 fr = read_frame(s, &whennext);
826
827                 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
828                         if (fr) {
829                                 ast_log(LOG_WARNING, "Failed to write frame\n");
830                                 ast_frfree(fr);
831                         }
832                         goto return_failure;
833                 }
834
835                 if (fr) {
836                         ast_frfree(fr);
837                 }
838         }
839
840         if (whennext != s->lasttimeout) {
841                 if (ast_channel_timingfd(s->owner) > -1) {
842                         float samp_rate = (float) ast_format_rate(&s->fmt->format);
843                         unsigned int rate;
844
845                         rate = (unsigned int) roundf(samp_rate / ((float) whennext));
846
847                         ast_settimeout(s->owner, rate, ast_fsread_audio, s);
848                 } else {
849                         ast_channel_streamid_set(s->owner, ast_sched_add(ast_channel_sched(s->owner), whennext / (ast_format_rate(&s->fmt->format) / 1000), ast_fsread_audio, s));
850                 }
851                 s->lasttimeout = whennext;
852                 return FSREAD_SUCCESS_NOSCHED;
853         }
854         return FSREAD_SUCCESS_SCHED;
855
856 return_failure:
857         ast_channel_streamid_set(s->owner, -1);
858         ast_settimeout(s->owner, 0, NULL, NULL);
859         return FSREAD_FAILURE;
860 }
861
862 static int ast_fsread_audio(const void *data)
863 {
864         struct ast_filestream *fs = (struct ast_filestream *)data;
865         enum fsread_res res;
866
867         res = ast_readaudio_callback(fs);
868
869         if (res == FSREAD_SUCCESS_SCHED)
870                 return 1;
871
872         return 0;
873 }
874
875 static int ast_fsread_video(const void *data);
876
877 static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
878 {
879         int whennext = 0;
880
881         while (!whennext) {
882                 struct ast_frame *fr = read_frame(s, &whennext);
883
884                 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
885                         if (fr) {
886                                 ast_log(LOG_WARNING, "Failed to write frame\n");
887                                 ast_frfree(fr);
888                         }
889                         ast_channel_vstreamid_set(s->owner, -1);
890                         return FSREAD_FAILURE;
891                 }
892
893                 if (fr) {
894                         ast_frfree(fr);
895                 }
896         }
897
898         if (whennext != s->lasttimeout) {
899                 ast_channel_vstreamid_set(s->owner, ast_sched_add(ast_channel_sched(s->owner), whennext / (ast_format_rate(&s->fmt->format) / 1000), ast_fsread_video, s));
900                 s->lasttimeout = whennext;
901                 return FSREAD_SUCCESS_NOSCHED;
902         }
903
904         return FSREAD_SUCCESS_SCHED;
905 }
906
907 static int ast_fsread_video(const void *data)
908 {
909         struct ast_filestream *fs = (struct ast_filestream *)data;
910         enum fsread_res res;
911
912         res = ast_readvideo_callback(fs);
913
914         if (res == FSREAD_SUCCESS_SCHED)
915                 return 1;
916
917         return 0;
918 }
919
920 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
921 {
922         s->owner = chan;
923         return 0;
924 }
925
926 int ast_playstream(struct ast_filestream *s)
927 {
928         enum fsread_res res;
929
930         if (AST_FORMAT_GET_TYPE(s->fmt->format.id) == AST_FORMAT_TYPE_AUDIO)
931                 res = ast_readaudio_callback(s);
932         else
933                 res = ast_readvideo_callback(s);
934
935         return (res == FSREAD_FAILURE) ? -1 : 0;
936 }
937
938 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
939 {
940         return fs->fmt->seek(fs, sample_offset, whence);
941 }
942
943 int ast_truncstream(struct ast_filestream *fs)
944 {
945         return fs->fmt->trunc(fs);
946 }
947
948 off_t ast_tellstream(struct ast_filestream *fs)
949 {
950         return fs->fmt->tell(fs);
951 }
952
953 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
954 {
955         return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
956 }
957
958 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
959 {
960         return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
961 }
962
963 int ast_closestream(struct ast_filestream *f)
964 {
965         /* This used to destroy the filestream, but it now just decrements a refcount.
966          * We close the stream in order to quit queuing frames now, because we might
967          * change the writeformat, which could result in a subsequent write error, if
968          * the format is different. */
969         filestream_close(f);
970         ao2_ref(f, -1);
971         return 0;
972 }
973
974
975 /*
976  * Look the various language-specific places where a file could exist.
977  */
978 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
979 {
980         char *buf;
981         int buflen;
982
983         if (preflang == NULL)
984                 preflang = "";
985         buflen = strlen(preflang) + strlen(filename) + 4;       /* room for everything */
986         buf = alloca(buflen);
987         if (buf == NULL)
988                 return 0;
989         return fileexists_core(filename, fmt, preflang, buf, buflen, NULL) ? 1 : 0;
990 }
991
992 int ast_filedelete(const char *filename, const char *fmt)
993 {
994         return filehelper(filename, NULL, fmt, ACTION_DELETE);
995 }
996
997 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
998 {
999         return filehelper(filename, filename2, fmt, ACTION_RENAME);
1000 }
1001
1002 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
1003 {
1004         return filehelper(filename, filename2, fmt, ACTION_COPY);
1005 }
1006
1007 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
1008 {
1009         struct ast_filestream *fs;
1010         struct ast_filestream *vfs=NULL;
1011         char fmt[256];
1012         off_t pos;
1013         int seekattempt;
1014         int res;
1015
1016         fs = ast_openstream(chan, filename, preflang);
1017         if (!fs) {
1018                 ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), ast_channel_nativeformats(chan)), strerror(errno));
1019                 return -1;
1020         }
1021
1022         /* check to see if there is any data present (not a zero length file),
1023          * done this way because there is no where for ast_openstream_full to
1024          * return the file had no data. */
1025         pos = ftello(fs->f);
1026         seekattempt = fseeko(fs->f, -1, SEEK_END);
1027         if (seekattempt) {
1028                 if (errno == EINVAL) {
1029                         /* Zero-length file, as opposed to a pipe */
1030                         return 0;
1031                 } else {
1032                         ast_seekstream(fs, 0, SEEK_SET);
1033                 }
1034         } else {
1035                 fseeko(fs->f, pos, SEEK_SET);
1036         }
1037
1038         vfs = ast_openvstream(chan, filename, preflang);
1039         if (vfs) {
1040                 ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_getformatname(&vfs->fmt->format));
1041         }
1042
1043         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_MASQ_NOSTREAM))
1044                 fs->orig_chan_name = ast_strdup(ast_channel_name(chan));
1045         if (ast_applystream(chan, fs))
1046                 return -1;
1047         if (vfs && ast_applystream(chan, vfs))
1048                 return -1;
1049         res = ast_playstream(fs);
1050         if (!res && vfs)
1051                 res = ast_playstream(vfs);
1052         ast_verb(3, "<%s> Playing '%s.%s' (language '%s')\n", ast_channel_name(chan), filename, ast_getformatname(ast_channel_writeformat(chan)), preflang ? preflang : "default");
1053
1054         return res;
1055 }
1056
1057 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
1058 {
1059         FILE *bfile;
1060         struct ast_format_def *f;
1061         struct ast_filestream *fs = NULL;
1062         char *fn;
1063         int format_found = 0;
1064
1065         AST_RWLIST_RDLOCK(&formats);
1066
1067         AST_RWLIST_TRAVERSE(&formats, f, list) {
1068                 fs = NULL;
1069                 if (!exts_compare(f->exts, type))
1070                         continue;
1071                 else
1072                         format_found = 1;
1073
1074                 fn = build_filename(filename, type);
1075                 errno = 0;
1076                 bfile = fopen(fn, "r");
1077
1078                 if (!bfile || (fs = get_filestream(f, bfile)) == NULL || open_wrapper(fs) ) {
1079                         ast_log(LOG_WARNING, "Unable to open %s\n", fn);
1080                         if (fs) {
1081                                 ast_closestream(fs);
1082                         }
1083                         fs = NULL;
1084                         bfile = NULL;
1085                         ast_free(fn);
1086                         break;
1087                 }
1088                 /* found it */
1089                 fs->trans = NULL;
1090                 fs->fmt = f;
1091                 fs->flags = flags;
1092                 fs->mode = mode;
1093                 fs->filename = ast_strdup(filename);
1094                 fs->vfs = NULL;
1095                 break;
1096         }
1097
1098         AST_RWLIST_UNLOCK(&formats);
1099         if (!format_found)
1100                 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1101
1102         return fs;
1103 }
1104
1105 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
1106 {
1107         int fd, myflags = 0;
1108         /* compiler claims this variable can be used before initialization... */
1109         FILE *bfile = NULL;
1110         struct ast_format_def *f;
1111         struct ast_filestream *fs = NULL;
1112         char *buf = NULL;
1113         size_t size = 0;
1114         int format_found = 0;
1115
1116         AST_RWLIST_RDLOCK(&formats);
1117
1118         /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
1119         /* We really can't use O_APPEND as it will break WAV header updates */
1120         if (flags & O_APPEND) {
1121                 flags &= ~O_APPEND;
1122         } else {
1123                 myflags = O_TRUNC;
1124         }
1125
1126         myflags |= O_WRONLY | O_CREAT;
1127
1128         /* XXX need to fix this - we should just do the fopen,
1129          * not open followed by fdopen()
1130          */
1131         AST_RWLIST_TRAVERSE(&formats, f, list) {
1132                 char *fn, *orig_fn = NULL;
1133                 if (fs)
1134                         break;
1135
1136                 if (!exts_compare(f->exts, type))
1137                         continue;
1138                 else
1139                         format_found = 1;
1140
1141                 fn = build_filename(filename, type);
1142                 fd = open(fn, flags | myflags, mode);
1143                 if (fd > -1) {
1144                         /* fdopen() the resulting file stream */
1145                         bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1146                         if (!bfile) {
1147                                 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1148                                 close(fd);
1149                                 fd = -1;
1150                         }
1151                 }
1152
1153                 if (ast_opt_cache_record_files && (fd > -1)) {
1154                         char *c;
1155
1156                         fclose(bfile);  /* this also closes fd */
1157                         /*
1158                           We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
1159                           What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
1160                         */
1161                         orig_fn = ast_strdupa(fn);
1162                         for (c = fn; *c; c++)
1163                                 if (*c == '/')
1164                                         *c = '_';
1165
1166                         size = strlen(fn) + strlen(record_cache_dir) + 2;
1167                         buf = alloca(size);
1168                         strcpy(buf, record_cache_dir);
1169                         strcat(buf, "/");
1170                         strcat(buf, fn);
1171                         ast_free(fn);
1172                         fn = buf;
1173                         fd = open(fn, flags | myflags, mode);
1174                         if (fd > -1) {
1175                                 /* fdopen() the resulting file stream */
1176                                 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1177                                 if (!bfile) {
1178                                         ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1179                                         close(fd);
1180                                         fd = -1;
1181                                 }
1182                         }
1183                 }
1184                 if (fd > -1) {
1185                         errno = 0;
1186                         fs = get_filestream(f, bfile);
1187                         if (fs) {
1188                                 if ((fs->write_buffer = ast_malloc(32768))) {
1189                                         setvbuf(fs->f, fs->write_buffer, _IOFBF, 32768);
1190                                 }
1191                         }
1192                         if (!fs || rewrite_wrapper(fs, comment)) {
1193                                 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
1194                                 close(fd);
1195                                 if (orig_fn) {
1196                                         unlink(fn);
1197                                         unlink(orig_fn);
1198                                 }
1199                                 if (fs) {
1200                                         ast_closestream(fs);
1201                                         fs = NULL;
1202                                 }
1203                                 continue;
1204                         }
1205                         fs->trans = NULL;
1206                         fs->fmt = f;
1207                         fs->flags = flags;
1208                         fs->mode = mode;
1209                         if (orig_fn) {
1210                                 fs->realfilename = ast_strdup(orig_fn);
1211                                 fs->filename = ast_strdup(fn);
1212                         } else {
1213                                 fs->realfilename = NULL;
1214                                 fs->filename = ast_strdup(filename);
1215                         }
1216                         fs->vfs = NULL;
1217                         /* If truncated, we'll be at the beginning; if not truncated, then append */
1218                         f->seek(fs, 0, SEEK_END);
1219                 } else if (errno != EEXIST) {
1220                         ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
1221                         if (orig_fn)
1222                                 unlink(orig_fn);
1223                 }
1224                 /* if buf != NULL then fn is already free and pointing to it */
1225                 if (!buf)
1226                         ast_free(fn);
1227         }
1228
1229         AST_RWLIST_UNLOCK(&formats);
1230
1231         if (!format_found)
1232                 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1233
1234         return fs;
1235 }
1236
1237 /*!
1238  * \brief the core of all waitstream() functions
1239  */
1240 static int waitstream_core(struct ast_channel *c, const char *breakon,
1241         const char *forward, const char *reverse, int skip_ms,
1242         int audiofd, int cmdfd,  const char *context)
1243 {
1244         const char *orig_chan_name = NULL;
1245         int err = 0;
1246
1247         if (!breakon)
1248                 breakon = "";
1249         if (!forward)
1250                 forward = "";
1251         if (!reverse)
1252                 reverse = "";
1253
1254         /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
1255         ast_set_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1256
1257         if (ast_test_flag(ast_channel_flags(c), AST_FLAG_MASQ_NOSTREAM))
1258                 orig_chan_name = ast_strdupa(ast_channel_name(c));
1259
1260         while (ast_channel_stream(c)) {
1261                 int res;
1262                 int ms;
1263
1264                 if (orig_chan_name && strcasecmp(orig_chan_name, ast_channel_name(c))) {
1265                         ast_stopstream(c);
1266                         err = 1;
1267                         break;
1268                 }
1269
1270                 ms = ast_sched_wait(ast_channel_sched(c));
1271
1272                 if (ms < 0 && !ast_channel_timingfunc(c)) {
1273                         ast_stopstream(c);
1274                         break;
1275                 }
1276                 if (ms < 0)
1277                         ms = 1000;
1278                 if (cmdfd < 0) {
1279                         res = ast_waitfor(c, ms);
1280                         if (res < 0) {
1281                                 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1282                                 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1283                                 return res;
1284                         }
1285                 } else {
1286                         int outfd;
1287                         struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1288                         if (!rchan && (outfd < 0) && (ms)) {
1289                                 /* Continue */
1290                                 if (errno == EINTR)
1291                                         continue;
1292                                 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1293                                 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1294                                 return -1;
1295                         } else if (outfd > -1) { /* this requires cmdfd set */
1296                                 /* The FD we were watching has something waiting */
1297                                 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1298                                 return 1;
1299                         }
1300                         /* if rchan is set, it is 'c' */
1301                         res = rchan ? 1 : 0; /* map into 'res' values */
1302                 }
1303                 if (res > 0) {
1304                         struct ast_frame *fr = ast_read(c);
1305                         if (!fr) {
1306                                 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1307                                 return -1;
1308                         }
1309                         switch (fr->frametype) {
1310                         case AST_FRAME_DTMF_END:
1311                                 if (context) {
1312                                         const char exten[2] = { fr->subclass.integer, '\0' };
1313                                         if (ast_exists_extension(c, context, exten, 1,
1314                                                 S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, NULL))) {
1315                                                 res = fr->subclass.integer;
1316                                                 ast_frfree(fr);
1317                                                 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1318                                                 return res;
1319                                         }
1320                                 } else {
1321                                         res = fr->subclass.integer;
1322                                         if (strchr(forward, res)) {
1323                                                 int eoftest;
1324                                                 ast_stream_fastforward(ast_channel_stream(c), skip_ms);
1325                                                 eoftest = fgetc(ast_channel_stream(c)->f);
1326                                                 if (feof(ast_channel_stream(c)->f)) {
1327                                                         ast_stream_rewind(ast_channel_stream(c), skip_ms);
1328                                                 } else {
1329                                                         ungetc(eoftest, ast_channel_stream(c)->f);
1330                                                 }
1331                                         } else if (strchr(reverse, res)) {
1332                                                 ast_stream_rewind(ast_channel_stream(c), skip_ms);
1333                                         } else if (strchr(breakon, res)) {
1334                                                 ast_frfree(fr);
1335                                                 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1336                                                 return res;
1337                                         }
1338                                 }
1339                                 break;
1340                         case AST_FRAME_CONTROL:
1341                                 switch (fr->subclass.integer) {
1342                                 case AST_CONTROL_HANGUP:
1343                                 case AST_CONTROL_BUSY:
1344                                 case AST_CONTROL_CONGESTION:
1345                                         ast_frfree(fr);
1346                                         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1347                                         return -1;
1348                                 case AST_CONTROL_RINGING:
1349                                 case AST_CONTROL_ANSWER:
1350                                 case AST_CONTROL_VIDUPDATE:
1351                                 case AST_CONTROL_SRCUPDATE:
1352                                 case AST_CONTROL_SRCCHANGE:
1353                                 case AST_CONTROL_HOLD:
1354                                 case AST_CONTROL_UNHOLD:
1355                                 case AST_CONTROL_CONNECTED_LINE:
1356                                 case AST_CONTROL_REDIRECTING:
1357                                 case AST_CONTROL_AOC:
1358                                 case AST_CONTROL_UPDATE_RTP_PEER:
1359                                 case -1:
1360                                         /* Unimportant */
1361                                         break;
1362                                 default:
1363                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass.integer);
1364                                 }
1365                                 break;
1366                         case AST_FRAME_VOICE:
1367                                 /* Write audio if appropriate */
1368                                 if (audiofd > -1) {
1369                                         if (write(audiofd, fr->data.ptr, fr->datalen) < 0) {
1370                                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
1371                                         }
1372                                 }
1373                         default:
1374                                 /* Ignore all others */
1375                                 break;
1376                         }
1377                         ast_frfree(fr);
1378                 }
1379                 ast_sched_runq(ast_channel_sched(c));
1380         }
1381
1382         ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1383
1384         return (err || ast_channel_softhangup_internal_flag(c)) ? -1 : 0;
1385 }
1386
1387 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *reverse, int ms)
1388 {
1389         return waitstream_core(c, breakon, forward, reverse, ms,
1390                 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */);
1391 }
1392
1393 int ast_waitstream(struct ast_channel *c, const char *breakon)
1394 {
1395         return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL);
1396 }
1397
1398 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1399 {
1400         return waitstream_core(c, breakon, NULL, NULL, 0,
1401                 audiofd, cmdfd, NULL /* no context */);
1402 }
1403
1404 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1405 {
1406         /* Waitstream, with return in the case of a valid 1 digit extension */
1407         /* in the current or specified context being pressed */
1408
1409         if (!context)
1410                 context = ast_channel_context(c);
1411         return waitstream_core(c, NULL, NULL, NULL, 0,
1412                 -1, -1, context);
1413 }
1414
1415 /*
1416  * if the file name is non-empty, try to play it.
1417  * Return 0 if success, -1 if error, digit if interrupted by a digit.
1418  * If digits == "" then we can simply check for non-zero.
1419  */
1420 int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
1421 {
1422         int res = 0;
1423         if (!ast_strlen_zero(file)) {
1424                 ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", file, ast_channel_name(chan));
1425                 res = ast_streamfile(chan, file, ast_channel_language(chan));
1426                 if (!res) {
1427                         res = ast_waitstream(chan, digits);
1428                 }
1429         }
1430         return res;
1431 }
1432
1433 char *ast_format_str_reduce(char *fmts)
1434 {
1435         struct ast_format_def *f;
1436         struct ast_format_def *fmts_ptr[AST_MAX_FORMATS];
1437         char *fmts_str[AST_MAX_FORMATS];
1438         char *stringp, *type;
1439         char *orig = fmts;
1440         int i, j, x, first, found = 0;
1441         int len = strlen(fmts) + 1;
1442         int res;
1443
1444         if (AST_RWLIST_RDLOCK(&formats)) {
1445                 ast_log(LOG_WARNING, "Unable to lock format list\n");
1446                 return NULL;
1447         }
1448
1449         stringp = ast_strdupa(fmts);
1450
1451         for (x = 0; (type = strsep(&stringp, "|")) && x < AST_MAX_FORMATS; x++) {
1452                 AST_RWLIST_TRAVERSE(&formats, f, list) {
1453                         if (exts_compare(f->exts, type)) {
1454                                 found = 1;
1455                                 break;
1456                         }
1457                 }
1458
1459                 fmts_str[x] = type;
1460                 if (found) {
1461                         fmts_ptr[x] = f;
1462                 } else {
1463                         fmts_ptr[x] = NULL;
1464                 }
1465         }
1466         AST_RWLIST_UNLOCK(&formats);
1467
1468         first = 1;
1469         for (i = 0; i < x; i++) {
1470                 /* ignore invalid entries */
1471                 if (!fmts_ptr[i]) {
1472                         ast_log(LOG_WARNING, "ignoring unknown format '%s'\n", fmts_str[i]);
1473                         continue;
1474                 }
1475
1476                 /* special handling for the first entry */
1477                 if (first) {
1478                         res = snprintf(fmts, len, "%s", fmts_str[i]);
1479                         fmts += res;
1480                         len -= res;
1481                         first = 0;
1482                         continue;
1483                 }
1484
1485                 found = 0;
1486                 for (j = 0; j < i; j++) {
1487                         /* this is a duplicate */
1488                         if (fmts_ptr[j] == fmts_ptr[i]) {
1489                                 found = 1;
1490                                 break;
1491                         }
1492                 }
1493
1494                 if (!found) {
1495                         res = snprintf(fmts, len, "|%s", fmts_str[i]);
1496                         fmts += res;
1497                         len -= res;
1498                 }
1499         }
1500
1501         if (first) {
1502                 ast_log(LOG_WARNING, "no known formats found in format list (%s)\n", orig);
1503                 return NULL;
1504         }
1505
1506         return orig;
1507 }
1508
1509 static char *handle_cli_core_show_file_formats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1510 {
1511 #define FORMAT "%-10s %-10s %-20s\n"
1512 #define FORMAT2 "%-10s %-10s %-20s\n"
1513         struct ast_format_def *f;
1514         int count_fmt = 0;
1515
1516         switch (cmd) {
1517         case CLI_INIT:
1518                 e->command = "core show file formats";
1519                 e->usage =
1520                         "Usage: core show file formats\n"
1521                         "       Displays currently registered file formats (if any).\n";
1522                 return NULL;
1523         case CLI_GENERATE:
1524                 return NULL;
1525         }
1526
1527         if (a->argc != 4)
1528                 return CLI_SHOWUSAGE;
1529
1530         ast_cli(a->fd, FORMAT, "Format", "Name", "Extensions");
1531         ast_cli(a->fd, FORMAT, "------", "----", "----------");
1532
1533         AST_RWLIST_RDLOCK(&formats);
1534         AST_RWLIST_TRAVERSE(&formats, f, list) {
1535                 ast_cli(a->fd, FORMAT2, ast_getformatname(&f->format), f->name, f->exts);
1536                 count_fmt++;
1537         }
1538         AST_RWLIST_UNLOCK(&formats);
1539         ast_cli(a->fd, "%d file formats registered.\n", count_fmt);
1540         return CLI_SUCCESS;
1541 #undef FORMAT
1542 #undef FORMAT2
1543 }
1544
1545 static struct ast_cli_entry cli_file[] = {
1546         AST_CLI_DEFINE(handle_cli_core_show_file_formats, "Displays file formats")
1547 };
1548
1549 int ast_file_init(void)
1550 {
1551         ast_cli_register_multiple(cli_file, ARRAY_LEN(cli_file));
1552         return 0;
1553 }