don't mark these allocations as 'cache' allocations when caching has been disabled
[asterisk-bristuff.git] / main / file.c
blob6c78632626ab068275ccbbfb3888523c528389c8
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
19 /*! \file
21 * \brief Generic File Format Support.
23 * \author Mark Spencer <markster@digium.com>
26 #include "asterisk.h"
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include <sys/types.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <stdio.h>
36 #include <fcntl.h>
37 #include <dirent.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
41 #include "asterisk/frame.h"
42 #include "asterisk/file.h"
43 #include "asterisk/cli.h"
44 #include "asterisk/logger.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/sched.h"
47 #include "asterisk/options.h"
48 #include "asterisk/translate.h"
49 #include "asterisk/utils.h"
50 #include "asterisk/lock.h"
51 #include "asterisk/app.h"
52 #include "asterisk/pbx.h"
53 #include "asterisk/linkedlists.h"
54 #include "asterisk/module.h"
57 * The following variable controls the layout of localized sound files.
58 * If 0, use the historical layout with prefix just before the filename
59 * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
60 * if 1 put the prefix at the beginning of the filename
61 * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
62 * The latter permits a language to be entirely in one directory.
64 int ast_language_is_prefix;
66 static AST_LIST_HEAD_STATIC(formats, ast_format);
68 int __ast_format_register(const struct ast_format *f, struct ast_module *mod)
70 struct ast_format *tmp;
72 if (AST_LIST_LOCK(&formats)) {
73 ast_log(LOG_WARNING, "Unable to lock format list\n");
74 return -1;
76 AST_LIST_TRAVERSE(&formats, tmp, list) {
77 if (!strcasecmp(f->name, tmp->name)) {
78 AST_LIST_UNLOCK(&formats);
79 ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
80 return -1;
83 if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
84 AST_LIST_UNLOCK(&formats);
85 return -1;
87 *tmp = *f;
88 tmp->module = mod;
89 if (tmp->buf_size) {
91 * Align buf_size properly, rounding up to the machine-specific
92 * alignment for pointers.
94 struct _test_align { void *a, *b; } p;
95 int align = (char *)&p.b - (char *)&p.a;
96 tmp->buf_size = ((f->buf_size + align - 1)/align)*align;
99 memset(&tmp->list, 0, sizeof(tmp->list));
101 AST_LIST_INSERT_HEAD(&formats, tmp, list);
102 AST_LIST_UNLOCK(&formats);
103 if (option_verbose > 1)
104 ast_verbose( VERBOSE_PREFIX_2 "Registered file format %s, extension(s) %s\n", f->name, f->exts);
106 return 0;
109 int ast_format_unregister(const char *name)
111 struct ast_format *tmp;
112 int res = -1;
114 if (AST_LIST_LOCK(&formats)) {
115 ast_log(LOG_WARNING, "Unable to lock format list\n");
116 return -1;
118 AST_LIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
119 if (!strcasecmp(name, tmp->name)) {
120 AST_LIST_REMOVE_CURRENT(&formats, list);
121 free(tmp);
122 res = 0;
125 AST_LIST_TRAVERSE_SAFE_END
126 AST_LIST_UNLOCK(&formats);
128 if (!res) {
129 if (option_verbose > 1)
130 ast_verbose( VERBOSE_PREFIX_2 "Unregistered format %s\n", name);
131 } else
132 ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
134 return res;
137 int ast_stopstream(struct ast_channel *tmp)
139 /* Stop a running stream if there is one */
140 if (tmp->stream) {
141 ast_closestream(tmp->stream);
142 tmp->stream = NULL;
143 if (tmp->oldwriteformat && ast_set_write_format(tmp, tmp->oldwriteformat))
144 ast_log(LOG_WARNING, "Unable to restore format back to %d\n", tmp->oldwriteformat);
146 return 0;
149 int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
151 int res = -1;
152 int alt = 0;
153 if (f->frametype == AST_FRAME_VIDEO) {
154 if (fs->fmt->format < AST_FORMAT_MAX_AUDIO) {
155 /* This is the audio portion. Call the video one... */
156 if (!fs->vfs && fs->filename) {
157 const char *type = ast_getformatname(f->subclass & ~0x1);
158 fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
159 ast_log(LOG_DEBUG, "Opened video output file\n");
161 if (fs->vfs)
162 return ast_writestream(fs->vfs, f);
163 /* else ignore */
164 return 0;
165 } else {
166 /* Might / might not have mark set */
167 alt = 1;
169 } else if (f->frametype != AST_FRAME_VOICE) {
170 ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
171 return -1;
173 if (((fs->fmt->format | alt) & f->subclass) == f->subclass) {
174 res = fs->fmt->write(fs, f);
175 if (res < 0)
176 ast_log(LOG_WARNING, "Natural write failed\n");
177 else if (res > 0)
178 ast_log(LOG_WARNING, "Huh??\n");
179 } else {
180 /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
181 the one we've setup a translator for, we do the "wrong thing" XXX */
182 if (fs->trans && f->subclass != fs->lastwriteformat) {
183 ast_translator_free_path(fs->trans);
184 fs->trans = NULL;
186 if (!fs->trans)
187 fs->trans = ast_translator_build_path(fs->fmt->format, f->subclass);
188 if (!fs->trans)
189 ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
190 fs->fmt->name, ast_getformatname(f->subclass));
191 else {
192 struct ast_frame *trf;
193 fs->lastwriteformat = f->subclass;
194 /* Get the translated frame but don't consume the original in case they're using it on another stream */
195 trf = ast_translate(fs->trans, f, 0);
196 if (trf) {
197 res = fs->fmt->write(fs, trf);
198 if (res)
199 ast_log(LOG_WARNING, "Translated frame write failed\n");
200 } else
201 res = 0;
204 return res;
207 static int copy(const char *infile, const char *outfile)
209 int ifd, ofd, len;
210 char buf[4096]; /* XXX make it lerger. */
212 if ((ifd = open(infile, O_RDONLY)) < 0) {
213 ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
214 return -1;
216 if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, 0600)) < 0) {
217 ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
218 close(ifd);
219 return -1;
221 while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
222 int res;
223 if (len < 0) {
224 ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
225 break;
227 /* XXX handle partial writes */
228 res = write(ofd, buf, len);
229 if (res != len) {
230 ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
231 len = -1; /* error marker */
232 break;
235 close(ifd);
236 close(ofd);
237 if (len < 0) {
238 unlink(outfile);
239 return -1; /* error */
241 return 0; /* success */
245 * \brief construct a filename. Absolute pathnames are preserved,
246 * relative names are prefixed by the sounds/ directory.
247 * The wav49 suffix is replaced by 'WAV'.
248 * Returns a malloc'ed string to be freed by the caller.
250 static char *build_filename(const char *filename, const char *ext)
252 char *fn = NULL;
254 if (!strcmp(ext, "wav49"))
255 ext = "WAV";
257 if (filename[0] == '/')
258 asprintf(&fn, "%s.%s", filename, ext);
259 else
260 asprintf(&fn, "%s/sounds/%s.%s",
261 ast_config_AST_DATA_DIR, filename, ext);
262 return fn;
265 /* compare type against the list 'exts' */
266 /* XXX need a better algorithm */
267 static int exts_compare(const char *exts, const char *type)
269 char tmp[256];
270 char *stringp = tmp, *ext;
272 ast_copy_string(tmp, exts, sizeof(tmp));
273 while ((ext = strsep(&stringp, "|"))) {
274 if (!strcmp(ext, type))
275 return 1;
278 return 0;
281 static struct ast_filestream *get_filestream(struct ast_format *fmt, FILE *bfile)
283 struct ast_filestream *s;
285 int l = sizeof(*s) + fmt->buf_size + fmt->desc_size; /* total allocation size */
286 if ( (s = ast_calloc(1, l)) == NULL)
287 return NULL;
288 s->fmt = fmt;
289 s->f = bfile;
291 if (fmt->desc_size)
292 s->private = ((char *)(s+1)) + fmt->buf_size;
293 if (fmt->buf_size)
294 s->buf = (char *)(s+1);
295 s->fr.src = fmt->name;
296 return s;
300 * Default implementations of open and rewrite.
301 * Only use them if you don't have expensive stuff to do.
303 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
305 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
307 struct ast_format *f = s->fmt;
308 int ret = -1;
310 if (mode == WRAP_OPEN && f->open && f->open(s))
311 ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
312 else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
313 ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
314 else {
315 /* preliminary checks succeed. update usecount */
316 ast_module_ref(f->module);
317 ret = 0;
319 return ret;
322 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
324 return fn_wrapper(s, comment, WRAP_REWRITE);
327 static int open_wrapper(struct ast_filestream *s)
329 return fn_wrapper(s, NULL, WRAP_OPEN);
332 enum file_action {
333 ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
334 ACTION_DELETE, /* delete file, return 0 on success, -1 on error */
335 ACTION_RENAME, /* rename file. return 0 on success, -1 on error */
336 ACTION_OPEN,
337 ACTION_COPY /* copy file. return 0 on success, -1 on error */
341 * \brief perform various actions on a file. Second argument
342 * arg2 depends on the command:
343 * unused for EXISTS and DELETE
344 * destination file name (const char *) for COPY and RENAME
345 * struct ast_channel * for OPEN
346 * if fmt is NULL, OPEN will return the first matching entry,
347 * whereas other functions will run on all matching entries.
349 static int ast_filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
351 struct ast_format *f;
352 int res = (action == ACTION_EXISTS) ? 0 : -1;
354 if (AST_LIST_LOCK(&formats)) {
355 ast_log(LOG_WARNING, "Unable to lock format list\n");
356 return res;
358 /* Check for a specific format */
359 AST_LIST_TRAVERSE(&formats, f, list) {
360 char *stringp, *ext = NULL;
362 if (fmt && !exts_compare(f->exts, fmt))
363 continue;
365 /* Look for a file matching the supported extensions.
366 * The file must exist, and for OPEN, must match
367 * one of the formats supported by the channel.
369 stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
370 while ( (ext = strsep(&stringp, "|")) ) {
371 struct stat st;
372 char *fn = build_filename(filename, ext);
374 if (fn == NULL)
375 continue;
377 if ( stat(fn, &st) ) { /* file not existent */
378 free(fn);
379 continue;
381 /* for 'OPEN' we need to be sure that the format matches
382 * what the channel can process
384 if (action == ACTION_OPEN) {
385 struct ast_channel *chan = (struct ast_channel *)arg2;
386 FILE *bfile;
387 struct ast_filestream *s;
389 if ( !(chan->writeformat & f->format) &&
390 !(f->format >= AST_FORMAT_MAX_AUDIO && fmt)) {
391 free(fn);
392 continue; /* not a supported format */
394 if ( (bfile = fopen(fn, "r")) == NULL) {
395 free(fn);
396 continue; /* cannot open file */
398 s = get_filestream(f, bfile);
399 if (!s) {
400 fclose(bfile);
401 free(fn); /* cannot allocate descriptor */
402 continue;
404 if (open_wrapper(s)) {
405 fclose(bfile);
406 free(fn);
407 free(s);
408 continue; /* cannot run open on file */
410 /* ok this is good for OPEN */
411 res = 1; /* found */
412 s->lasttimeout = -1;
413 s->fmt = f;
414 s->trans = NULL;
415 s->filename = NULL;
416 if (s->fmt->format < AST_FORMAT_MAX_AUDIO)
417 chan->stream = s;
418 else
419 chan->vstream = s;
420 free(fn);
421 break;
423 switch (action) {
424 case ACTION_OPEN:
425 break; /* will never get here */
427 case ACTION_EXISTS: /* return the matching format */
428 res |= f->format;
429 break;
431 case ACTION_DELETE:
432 if ( (res = unlink(fn)) )
433 ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
434 break;
436 case ACTION_RENAME:
437 case ACTION_COPY: {
438 char *nfn = build_filename((const char *)arg2, ext);
439 if (!nfn)
440 ast_log(LOG_WARNING, "Out of memory\n");
441 else {
442 res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
443 if (res)
444 ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
445 action == ACTION_COPY ? "copy" : "rename",
446 fn, nfn, strerror(errno));
447 free(nfn);
450 break;
452 default:
453 ast_log(LOG_WARNING, "Unknown helper %d\n", action);
455 free(fn);
458 AST_LIST_UNLOCK(&formats);
459 return res;
463 * \brief helper routine to locate a file with a given format
464 * and language preference.
465 * Try preflang, preflang with stripped '_' suffix, or NULL.
466 * In the standard asterisk, language goes just before the last component.
467 * In an alternative configuration, the language should be a prefix
468 * to the actual filename.
470 * The last parameter(s) point to a buffer of sufficient size,
471 * which on success is filled with the matching filename.
473 static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
474 char *buf, int buflen)
476 int res = -1;
477 int langlen; /* length of language string */
478 const char *c = strrchr(filename, '/');
479 int offset = c ? c - filename + 1 : 0; /* points right after the last '/' */
481 if (preflang == NULL)
482 preflang = "";
483 langlen = strlen(preflang);
485 if (buflen < langlen + strlen(filename) + 2) {
486 ast_log(LOG_WARNING, "buffer too small\n");
487 buf[0] = '\0'; /* set to empty */
488 buf = alloca(langlen + strlen(filename) + 2); /* room for everything */
490 if (buf == NULL)
491 return 0;
492 buf[0] = '\0';
493 for (;;) {
494 if (ast_language_is_prefix) { /* new layout */
495 if (langlen) {
496 strcpy(buf, preflang);
497 buf[langlen] = '/';
498 strcpy(buf + langlen + 1, filename);
499 } else
500 strcpy(buf, filename); /* first copy the full string */
501 } else { /* old layout */
502 strcpy(buf, filename); /* first copy the full string */
503 if (langlen) {
504 /* insert the language and suffix if needed */
505 strcpy(buf + offset, preflang);
506 sprintf(buf + offset + langlen, "/%s", filename + offset);
509 res = ast_filehelper(buf, NULL, fmt, ACTION_EXISTS);
510 if (res > 0) /* found format */
511 break;
512 if (langlen == 0) /* no more formats */
513 break;
514 if (preflang[langlen] == '_') /* we are on the local suffix */
515 langlen = 0; /* try again with no language */
516 else
517 langlen = (c = strchr(preflang, '_')) ? c - preflang : 0;
519 return res;
522 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
524 return ast_openstream_full(chan, filename, preflang, 0);
527 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
530 * Use fileexists_core() to find a file in a compatible
531 * language and format, set up a suitable translator,
532 * and open the stream.
534 int fmts, res, buflen;
535 char *buf;
537 if (!asis) {
538 /* do this first, otherwise we detect the wrong writeformat */
539 ast_stopstream(chan);
540 if (chan->generator)
541 ast_deactivate_generator(chan);
543 if (preflang == NULL)
544 preflang = "";
545 buflen = strlen(preflang) + strlen(filename) + 2;
546 buf = alloca(buflen);
547 if (buf == NULL)
548 return NULL;
549 fmts = fileexists_core(filename, NULL, preflang, buf, buflen);
550 if (fmts > 0)
551 fmts &= AST_FORMAT_AUDIO_MASK;
552 if (fmts < 1) {
553 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
554 return NULL;
556 chan->oldwriteformat = chan->writeformat;
557 /* Set the channel to a format we can work with */
558 res = ast_set_write_format(chan, fmts);
559 res = ast_filehelper(buf, chan, NULL, ACTION_OPEN);
560 if (res >= 0)
561 return chan->stream;
562 return NULL;
565 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
567 /* As above, but for video. But here we don't have translators
568 * so we must enforce a format.
570 unsigned int format;
571 char *buf;
572 int buflen;
574 if (preflang == NULL)
575 preflang = "";
576 buflen = strlen(preflang) + strlen(filename) + 2;
577 buf = alloca(buflen);
578 if (buf == NULL)
579 return NULL;
581 for (format = AST_FORMAT_MAX_AUDIO << 1; format <= AST_FORMAT_MAX_VIDEO; format = format << 1) {
582 int fd;
583 const char *fmt;
585 if (!(chan->nativeformats & format))
586 continue;
587 fmt = ast_getformatname(format);
588 if ( fileexists_core(filename, fmt, preflang, buf, buflen) < 1) /* no valid format */
589 continue;
590 fd = ast_filehelper(buf, chan, fmt, ACTION_OPEN);
591 if (fd >= 0)
592 return chan->vstream;
593 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
595 return NULL;
598 struct ast_frame *ast_readframe(struct ast_filestream *s)
600 struct ast_frame *f = NULL;
601 int whennext = 0;
602 if (s && s->fmt)
603 f = s->fmt->read(s, &whennext);
604 return f;
607 static int ast_readaudio_callback(void *data)
609 struct ast_filestream *s = data;
610 int whennext = 0;
612 while(!whennext) {
613 struct ast_frame *fr = s->fmt->read(s, &whennext);
614 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
615 if (fr)
616 ast_log(LOG_WARNING, "Failed to write frame\n");
617 s->owner->streamid = -1;
618 #ifdef HAVE_ZAPTEL
619 ast_settimeout(s->owner, 0, NULL, NULL);
620 #endif
621 return 0;
624 if (whennext != s->lasttimeout) {
625 #ifdef HAVE_ZAPTEL
626 if (s->owner->timingfd > -1)
627 ast_settimeout(s->owner, whennext, ast_readaudio_callback, s);
628 else
629 #endif
630 s->owner->streamid = ast_sched_add(s->owner->sched, whennext/8, ast_readaudio_callback, s);
631 s->lasttimeout = whennext;
632 return 0;
634 return 1;
637 static int ast_readvideo_callback(void *data)
639 struct ast_filestream *s = data;
640 int whennext = 0;
642 while (!whennext) {
643 struct ast_frame *fr = s->fmt->read(s, &whennext);
644 if (!fr || ast_write(s->owner, fr)) { /* no stream or error, as above */
645 if (fr)
646 ast_log(LOG_WARNING, "Failed to write frame\n");
647 s->owner->vstreamid = -1;
648 return 0;
651 if (whennext != s->lasttimeout) {
652 s->owner->vstreamid = ast_sched_add(s->owner->sched, whennext/8, ast_readvideo_callback, s);
653 s->lasttimeout = whennext;
654 return 0;
656 return 1;
659 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
661 s->owner = chan;
662 return 0;
665 int ast_playstream(struct ast_filestream *s)
667 if (s->fmt->format < AST_FORMAT_MAX_AUDIO)
668 ast_readaudio_callback(s);
669 else
670 ast_readvideo_callback(s);
671 return 0;
674 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
676 return fs->fmt->seek(fs, sample_offset, whence);
679 int ast_truncstream(struct ast_filestream *fs)
681 return fs->fmt->trunc(fs);
684 off_t ast_tellstream(struct ast_filestream *fs)
686 return fs->fmt->tell(fs);
689 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
691 return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
694 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
696 return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
699 int ast_closestream(struct ast_filestream *f)
701 char *cmd = NULL;
702 size_t size = 0;
703 /* Stop a running stream if there is one */
704 if (f->owner) {
705 if (f->fmt->format < AST_FORMAT_MAX_AUDIO) {
706 f->owner->stream = NULL;
707 if (f->owner->streamid > -1)
708 ast_sched_del(f->owner->sched, f->owner->streamid);
709 f->owner->streamid = -1;
710 #ifdef HAVE_ZAPTEL
711 ast_settimeout(f->owner, 0, NULL, NULL);
712 #endif
713 } else {
714 f->owner->vstream = NULL;
715 if (f->owner->vstreamid > -1)
716 ast_sched_del(f->owner->sched, f->owner->vstreamid);
717 f->owner->vstreamid = -1;
720 /* destroy the translator on exit */
721 if (f->trans)
722 ast_translator_free_path(f->trans);
724 if (f->realfilename && f->filename) {
725 size = strlen(f->filename) + strlen(f->realfilename) + 15;
726 cmd = alloca(size);
727 memset(cmd,0,size);
728 snprintf(cmd,size,"/bin/mv -f %s %s",f->filename,f->realfilename);
729 ast_safe_system(cmd);
732 if (f->filename)
733 free(f->filename);
734 if (f->realfilename)
735 free(f->realfilename);
736 if (f->fmt->close)
737 f->fmt->close(f);
738 fclose(f->f);
739 if (f->vfs)
740 ast_closestream(f->vfs);
741 ast_module_unref(f->fmt->module);
742 free(f);
743 return 0;
748 * Look the various language-specific places where a file could exist.
750 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
752 char *buf;
753 int buflen;
755 if (preflang == NULL)
756 preflang = "";
757 buflen = strlen(preflang) + strlen(filename) + 2; /* room for everything */
758 buf = alloca(buflen);
759 if (buf == NULL)
760 return 0;
761 return fileexists_core(filename, fmt, preflang, buf, buflen);
764 int ast_filedelete(const char *filename, const char *fmt)
766 return ast_filehelper(filename, NULL, fmt, ACTION_DELETE);
769 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
771 return ast_filehelper(filename, filename2, fmt, ACTION_RENAME);
774 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
776 return ast_filehelper(filename, filename2, fmt, ACTION_COPY);
779 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
781 struct ast_filestream *fs;
782 struct ast_filestream *vfs=NULL;
783 char fmt[256];
785 fs = ast_openstream(chan, filename, preflang);
786 if (fs)
787 vfs = ast_openvstream(chan, filename, preflang);
788 if (vfs)
789 ast_log(LOG_DEBUG, "Ooh, found a video stream, too, format %s\n", ast_getformatname(vfs->fmt->format));
790 if (fs){
791 if (ast_applystream(chan, fs))
792 return -1;
793 if (vfs && ast_applystream(chan, vfs))
794 return -1;
795 if (ast_playstream(fs))
796 return -1;
797 if (vfs && ast_playstream(vfs))
798 return -1;
799 #if 1
800 if (option_verbose > 2)
801 ast_verbose(VERBOSE_PREFIX_3 "Playing '%s' (language '%s')\n", filename, preflang ? preflang : "default");
802 #endif
803 return 0;
805 ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), chan->nativeformats), strerror(errno));
806 return -1;
809 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
811 FILE *bfile;
812 struct ast_format *f;
813 struct ast_filestream *fs = NULL;
814 char *fn;
816 if (AST_LIST_LOCK(&formats)) {
817 ast_log(LOG_WARNING, "Unable to lock format list\n");
818 return NULL;
821 AST_LIST_TRAVERSE(&formats, f, list) {
822 fs = NULL;
823 if (!exts_compare(f->exts, type))
824 continue;
826 fn = build_filename(filename, type);
827 errno = 0;
828 bfile = fopen(fn, "r");
829 if (!bfile || (fs = get_filestream(f, bfile)) == NULL ||
830 open_wrapper(fs) ) {
831 ast_log(LOG_WARNING, "Unable to open %s\n", fn);
832 if (fs)
833 free(fs);
834 if (bfile)
835 fclose(bfile);
836 free(fn);
837 continue;
839 /* found it */
840 fs->trans = NULL;
841 fs->fmt = f;
842 fs->flags = flags;
843 fs->mode = mode;
844 fs->filename = strdup(filename);
845 fs->vfs = NULL;
846 break;
849 AST_LIST_UNLOCK(&formats);
850 if (!fs)
851 ast_log(LOG_WARNING, "No such format '%s'\n", type);
853 return fs;
856 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
858 int fd, myflags = 0;
859 /* compiler claims this variable can be used before initialization... */
860 FILE *bfile = NULL;
861 struct ast_format *f;
862 struct ast_filestream *fs = NULL;
863 char *buf = NULL;
864 size_t size = 0;
865 int format_found = 0;
867 if (AST_LIST_LOCK(&formats)) {
868 ast_log(LOG_WARNING, "Unable to lock format list\n");
869 return NULL;
872 /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
873 /* We really can't use O_APPEND as it will break WAV header updates */
874 if (flags & O_APPEND) {
875 flags &= ~O_APPEND;
876 } else {
877 myflags = O_TRUNC;
880 myflags |= O_WRONLY | O_CREAT;
882 /* XXX need to fix this - we should just do the fopen,
883 * not open followed by fdopen()
885 AST_LIST_TRAVERSE(&formats, f, list) {
886 char *fn, *orig_fn = NULL;
887 if (fs)
888 break;
890 if (!exts_compare(f->exts, type))
891 continue;
892 else
893 format_found = 1;
895 fn = build_filename(filename, type);
896 fd = open(fn, flags | myflags, mode);
897 if (fd > -1) {
898 /* fdopen() the resulting file stream */
899 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
900 if (!bfile) {
901 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
902 close(fd);
903 fd = -1;
907 if (ast_opt_cache_record_files && (fd > -1)) {
908 char *c;
910 fclose(bfile); /* this also closes fd */
912 We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
913 What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
915 orig_fn = ast_strdupa(fn);
916 for (c = fn; *c; c++)
917 if (*c == '/')
918 *c = '_';
920 size = strlen(fn) + strlen(record_cache_dir) + 2;
921 buf = alloca(size);
922 strcpy(buf, record_cache_dir);
923 strcat(buf, "/");
924 strcat(buf, fn);
925 free(fn);
926 fn = buf;
927 fd = open(fn, flags | myflags, mode);
928 if (fd > -1) {
929 /* fdopen() the resulting file stream */
930 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
931 if (!bfile) {
932 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
933 close(fd);
934 fd = -1;
938 if (fd > -1) {
939 errno = 0;
940 fs = get_filestream(f, bfile);
941 if (!fs || rewrite_wrapper(fs, comment)) {
942 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
943 close(fd);
944 if (orig_fn) {
945 unlink(fn);
946 unlink(orig_fn);
948 if (fs)
949 free(fs);
951 fs->trans = NULL;
952 fs->fmt = f;
953 fs->flags = flags;
954 fs->mode = mode;
955 if (orig_fn) {
956 fs->realfilename = strdup(orig_fn);
957 fs->filename = strdup(fn);
958 } else {
959 fs->realfilename = NULL;
960 fs->filename = strdup(filename);
962 fs->vfs = NULL;
963 /* If truncated, we'll be at the beginning; if not truncated, then append */
964 f->seek(fs, 0, SEEK_END);
965 } else if (errno != EEXIST) {
966 ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
967 if (orig_fn)
968 unlink(orig_fn);
970 /* if buf != NULL then fn is already free and pointing to it */
971 if (!buf)
972 free(fn);
975 AST_LIST_UNLOCK(&formats);
977 if (!format_found)
978 ast_log(LOG_WARNING, "No such format '%s'\n", type);
980 return fs;
984 * \brief the core of all waitstream() functions
986 static int waitstream_core(struct ast_channel *c, const char *breakon,
987 const char *forward, const char *rewind, int skip_ms,
988 int audiofd, int cmdfd, const char *context)
990 if (!breakon)
991 breakon = "";
992 if (!forward)
993 forward = "";
994 if (!rewind)
995 rewind = "";
997 while (c->stream) {
998 int res;
999 int ms = ast_sched_wait(c->sched);
1000 if (ms < 0 && !c->timingfunc) {
1001 ast_stopstream(c);
1002 break;
1004 if (ms < 0)
1005 ms = 1000;
1006 if (cmdfd < 0) {
1007 res = ast_waitfor(c, ms);
1008 if (res < 0) {
1009 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1010 return res;
1012 } else {
1013 int outfd;
1014 struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1015 if (!rchan && (outfd < 0) && (ms)) {
1016 /* Continue */
1017 if (errno == EINTR)
1018 continue;
1019 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1020 return -1;
1021 } else if (outfd > -1) { /* this requires cmdfd set */
1022 /* The FD we were watching has something waiting */
1023 return 1;
1025 /* if rchan is set, it is 'c' */
1026 res = rchan ? 1 : 0; /* map into 'res' values */
1028 if (res > 0) {
1029 struct ast_frame *fr = ast_read(c);
1030 if (!fr)
1031 return -1;
1032 switch(fr->frametype) {
1033 case AST_FRAME_DTMF_END:
1034 if (context) {
1035 const char exten[2] = { fr->subclass, '\0' };
1036 if (ast_exists_extension(c, context, exten, 1, c->cid.cid_num)) {
1037 ast_frfree(fr);
1038 return res;
1040 } else {
1041 res = fr->subclass;
1042 if (strchr(forward,res)) {
1043 ast_stream_fastforward(c->stream, skip_ms);
1044 } else if (strchr(rewind,res)) {
1045 ast_stream_rewind(c->stream, skip_ms);
1046 } else if (strchr(breakon, res)) {
1047 ast_frfree(fr);
1048 return res;
1051 break;
1052 case AST_FRAME_CONTROL:
1053 switch(fr->subclass) {
1054 case AST_CONTROL_HANGUP:
1055 case AST_CONTROL_BUSY:
1056 case AST_CONTROL_CONGESTION:
1057 ast_frfree(fr);
1058 return -1;
1059 case AST_CONTROL_RINGING:
1060 case AST_CONTROL_ANSWER:
1061 case AST_CONTROL_VIDUPDATE:
1062 case AST_CONTROL_HOLD:
1063 case AST_CONTROL_UNHOLD:
1064 /* Unimportant */
1065 break;
1066 default:
1067 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass);
1069 break;
1070 case AST_FRAME_VOICE:
1071 /* Write audio if appropriate */
1072 if (audiofd > -1)
1073 write(audiofd, fr->data, fr->datalen);
1074 default:
1075 /* Ignore all others */
1076 break;
1078 ast_frfree(fr);
1080 ast_sched_runq(c->sched);
1082 return (c->_softhangup ? -1 : 0);
1085 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *rewind, int ms)
1087 return waitstream_core(c, breakon, forward, rewind, ms,
1088 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */);
1091 int ast_waitstream(struct ast_channel *c, const char *breakon)
1093 return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL);
1096 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1098 return waitstream_core(c, breakon, NULL, NULL, 0,
1099 audiofd, cmdfd, NULL /* no context */);
1102 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1104 /* Waitstream, with return in the case of a valid 1 digit extension */
1105 /* in the current or specified context being pressed */
1107 if (!context)
1108 context = c->context;
1109 return waitstream_core(c, NULL, NULL, NULL, 0,
1110 -1, -1, context);
1114 * if the file name is non-empty, try to play it.
1115 * Return 0 if success, -1 if error, digit if interrupted by a digit.
1116 * If digits == "" then we can simply check for non-zero.
1118 int ast_stream_and_wait(struct ast_channel *chan, const char *file,
1119 const char *language, const char *digits)
1121 int res = 0;
1122 if (!ast_strlen_zero(file)) {
1123 res = ast_streamfile(chan, file, language);
1124 if (!res)
1125 res = ast_waitstream(chan, digits);
1127 return res;
1130 static int show_file_formats(int fd, int argc, char *argv[])
1132 #define FORMAT "%-10s %-10s %-20s\n"
1133 #define FORMAT2 "%-10s %-10s %-20s\n"
1134 struct ast_format *f;
1135 int count_fmt = 0;
1137 if (argc != 3)
1138 return RESULT_SHOWUSAGE;
1139 ast_cli(fd, FORMAT, "Format", "Name", "Extensions");
1141 if (AST_LIST_LOCK(&formats)) {
1142 ast_log(LOG_WARNING, "Unable to lock format list\n");
1143 return -1;
1146 AST_LIST_TRAVERSE(&formats, f, list) {
1147 ast_cli(fd, FORMAT2, ast_getformatname(f->format), f->name, f->exts);
1148 count_fmt++;
1150 AST_LIST_UNLOCK(&formats);
1151 ast_cli(fd, "%d file formats registered.\n", count_fmt);
1152 return RESULT_SUCCESS;
1153 #undef FORMAT
1154 #undef FORMAT2
1157 char show_file_formats_usage[] =
1158 "Usage: core show file formats\n"
1159 " Displays currently registered file formats (if any)\n";
1161 struct ast_cli_entry cli_show_file_formats_deprecated = {
1162 { "show", "file", "formats" },
1163 show_file_formats, NULL,
1164 NULL };
1166 struct ast_cli_entry cli_file[] = {
1167 { { "core", "show", "file", "formats" },
1168 show_file_formats, "Displays file formats",
1169 show_file_formats_usage, NULL, &cli_show_file_formats_deprecated },
1172 int ast_file_init(void)
1174 ast_cli_register_multiple(cli_file, sizeof(cli_file) / sizeof(struct ast_cli_entry));
1175 return 0;