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