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