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