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