make Local channel return sensible device state values
[asterisk-bristuff.git] / file.c
blob55bacb193ab76a7f2b521e902d137a7937e414ac
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 #define MOD_LOADER
55 #include "asterisk/module.h"
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.
65 int ast_language_is_prefix;
67 static AST_LIST_HEAD_STATIC(formats, ast_format);
69 int ast_format_register(const struct ast_format *f)
71 struct ast_format *tmp;
73 if (f->module == NULL) {
74 ast_log(LOG_WARNING, "Missing module pointer, you need to supply one\n");
75 return -1;
77 if (AST_LIST_LOCK(&formats)) {
78 ast_log(LOG_WARNING, "Unable to lock format list\n");
79 return -1;
81 AST_LIST_TRAVERSE(&formats, tmp, list) {
82 if (!strcasecmp(f->name, tmp->name)) {
83 AST_LIST_UNLOCK(&formats);
84 ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
85 return -1;
88 tmp = ast_calloc(1, sizeof(struct ast_format));
89 if (!tmp) {
90 AST_LIST_UNLOCK(&formats);
91 return -1;
93 *tmp = *f;
94 if (tmp->buf_size) {
96 * Align buf_size properly, rounding up to the machine-specific
97 * alignment for pointers.
99 struct _test_align { void *a, *b; } p;
100 int align = (char *)&p.b - (char *)&p.a;
101 tmp->buf_size = ((f->buf_size + align - 1)/align)*align;
104 memset(&tmp->list, 0, sizeof(tmp->list));
106 AST_LIST_INSERT_HEAD(&formats, tmp, list);
107 AST_LIST_UNLOCK(&formats);
108 if (option_verbose > 1)
109 ast_verbose( VERBOSE_PREFIX_2 "Registered file format %s, extension(s) %s\n", f->name, f->exts);
110 return 0;
113 int ast_format_unregister(const char *name)
115 struct ast_format *tmp;
116 int res = -1;
118 if (AST_LIST_LOCK(&formats)) {
119 ast_log(LOG_WARNING, "Unable to lock format list\n");
120 return -1;
122 AST_LIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
123 if (!strcasecmp(name, tmp->name)) {
124 AST_LIST_REMOVE_CURRENT(&formats, list);
125 free(tmp);
126 res = 0;
129 AST_LIST_TRAVERSE_SAFE_END
130 AST_LIST_UNLOCK(&formats);
132 if (!res) {
133 if (option_verbose > 1)
134 ast_verbose( VERBOSE_PREFIX_2 "Unregistered format %s\n", name);
135 } else
136 ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
138 return res;
141 int ast_stopstream(struct ast_channel *tmp)
143 /* Stop a running stream if there is one */
144 if (tmp->stream) {
145 ast_closestream(tmp->stream);
146 tmp->stream = NULL;
147 if (tmp->oldwriteformat && ast_set_write_format(tmp, tmp->oldwriteformat))
148 ast_log(LOG_WARNING, "Unable to restore format back to %d\n", tmp->oldwriteformat);
150 return 0;
153 int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
155 int res = -1;
156 int alt = 0;
157 if (f->frametype == AST_FRAME_VIDEO) {
158 if (fs->fmt->format < AST_FORMAT_MAX_AUDIO) {
159 /* This is the audio portion. Call the video one... */
160 if (!fs->vfs && fs->filename) {
161 const char *type = ast_getformatname(f->subclass & ~0x1);
162 fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
163 ast_log(LOG_DEBUG, "Opened video output file\n");
165 if (fs->vfs)
166 return ast_writestream(fs->vfs, f);
167 /* else ignore */
168 return 0;
169 } else {
170 /* Might / might not have mark set */
171 alt = 1;
173 } else if (f->frametype != AST_FRAME_VOICE) {
174 ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
175 return -1;
177 if (((fs->fmt->format | alt) & f->subclass) == f->subclass) {
178 res = fs->fmt->write(fs, f);
179 if (res < 0)
180 ast_log(LOG_WARNING, "Natural write failed\n");
181 else if (res > 0)
182 ast_log(LOG_WARNING, "Huh??\n");
183 } else {
184 /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
185 the one we've setup a translator for, we do the "wrong thing" XXX */
186 if (fs->trans && f->subclass != fs->lastwriteformat) {
187 ast_translator_free_path(fs->trans);
188 fs->trans = NULL;
190 if (!fs->trans)
191 fs->trans = ast_translator_build_path(fs->fmt->format, f->subclass);
192 if (!fs->trans)
193 ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
194 fs->fmt->name, ast_getformatname(f->subclass));
195 else {
196 struct ast_frame *trf;
197 fs->lastwriteformat = f->subclass;
198 /* Get the translated frame but don't consume the original in case they're using it on another stream */
199 trf = ast_translate(fs->trans, f, 0);
200 if (trf) {
201 res = fs->fmt->write(fs, trf);
202 if (res)
203 ast_log(LOG_WARNING, "Translated frame write failed\n");
204 } else
205 res = 0;
208 return res;
211 static int copy(const char *infile, const char *outfile)
213 int ifd, ofd, len;
214 char buf[4096]; /* XXX make it lerger. */
216 if ((ifd = open(infile, O_RDONLY)) < 0) {
217 ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
218 return -1;
220 if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, 0600)) < 0) {
221 ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
222 close(ifd);
223 return -1;
225 while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
226 int res;
227 if (len < 0) {
228 ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
229 break;
231 /* XXX handle partial writes */
232 res = write(ofd, buf, len);
233 if (res != len) {
234 ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
235 len = -1; /* error marker */
236 break;
239 close(ifd);
240 close(ofd);
241 if (len < 0) {
242 unlink(outfile);
243 return -1; /* error */
245 return 0; /* success */
249 * \brief construct a filename. Absolute pathnames are preserved,
250 * relative names are prefixed by the sounds/ directory.
251 * The wav49 suffix is replaced by 'WAV'.
252 * Returns a malloc'ed string to be freed by the caller.
254 static char *build_filename(const char *filename, const char *ext)
256 char *fn = NULL;
258 if (!strcmp(ext, "wav49"))
259 ext = "WAV";
261 if (filename[0] == '/')
262 asprintf(&fn, "%s.%s", filename, ext);
263 else
264 asprintf(&fn, "%s/sounds/%s.%s",
265 ast_config_AST_DATA_DIR, filename, ext);
266 return fn;
269 /* compare type against the list 'exts' */
270 /* XXX need a better algorithm */
271 static int exts_compare(const char *exts, const char *type)
273 char tmp[256];
274 char *stringp = tmp, *ext;
276 ast_copy_string(tmp, exts, sizeof(tmp));
277 while ((ext = strsep(&stringp, "|"))) {
278 if (!strcmp(ext, type))
279 return 1;
282 return 0;
285 static struct ast_filestream *get_filestream(struct ast_format *fmt, FILE *bfile)
287 struct ast_filestream *s;
289 int l = sizeof(*s) + fmt->buf_size + fmt->desc_size; /* total allocation size */
290 if ( (s = ast_calloc(1, l)) == NULL)
291 return NULL;
292 s->fmt = fmt;
293 s->f = bfile;
295 if (fmt->desc_size)
296 s->private = ((char *)(s+1)) + fmt->buf_size;
297 if (fmt->buf_size)
298 s->buf = (char *)(s+1);
299 s->fr.src = fmt->name;
300 return s;
304 * Default implementations of open and rewrite.
305 * Only use them if you don't have expensive stuff to do.
307 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
309 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
311 struct ast_format *f = s->fmt;
312 int ret = -1;
314 if (mode == WRAP_OPEN && f->open && f->open(s))
315 ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
316 else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
317 ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
318 else {
319 /* preliminary checks succeed. update usecount */
320 ast_atomic_fetchadd_int(&f->module->usecnt, +1);
321 ret = 0;
322 ast_update_use_count();
324 return ret;
327 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
329 return fn_wrapper(s, comment, WRAP_REWRITE);
332 static int open_wrapper(struct ast_filestream *s)
334 return fn_wrapper(s, NULL, WRAP_OPEN);
337 enum file_action {
338 ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
339 ACTION_DELETE, /* delete file, return 0 on success, -1 on error */
340 ACTION_RENAME, /* rename file. return 0 on success, -1 on error */
341 ACTION_OPEN,
342 ACTION_COPY /* copy file. return 0 on success, -1 on error */
346 * \brief perform various actions on a file. Second argument
347 * arg2 depends on the command:
348 * unused for EXISTS and DELETE
349 * destination file name (const char *) for COPY and RENAME
350 * struct ast_channel * for OPEN
351 * if fmt is NULL, OPEN will return the first matching entry,
352 * whereas other functions will run on all matching entries.
354 static int ast_filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
356 struct ast_format *f;
357 int res = (action == ACTION_EXISTS) ? 0 : -1;
359 if (AST_LIST_LOCK(&formats)) {
360 ast_log(LOG_WARNING, "Unable to lock format list\n");
361 return res;
363 /* Check for a specific format */
364 AST_LIST_TRAVERSE(&formats, f, list) {
365 char *stringp, *ext = NULL;
367 if (fmt && !exts_compare(f->exts, fmt))
368 continue;
370 /* Look for a file matching the supported extensions.
371 * The file must exist, and for OPEN, must match
372 * one of the formats supported by the channel.
374 stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
375 while ( (ext = strsep(&stringp, "|")) ) {
376 struct stat st;
377 char *fn = build_filename(filename, ext);
379 if (fn == NULL)
380 continue;
382 if ( stat(fn, &st) ) { /* file not existent */
383 free(fn);
384 continue;
386 /* for 'OPEN' we need to be sure that the format matches
387 * what the channel can process
389 if (action == ACTION_OPEN) {
390 struct ast_channel *chan = (struct ast_channel *)arg2;
391 FILE *bfile;
392 struct ast_filestream *s;
394 if ( !(chan->writeformat & f->format) &&
395 !(f->format >= AST_FORMAT_MAX_AUDIO && fmt)) {
396 free(fn);
397 continue; /* not a supported format */
399 if ( (bfile = fopen(fn, "r")) == NULL) {
400 free(fn);
401 continue; /* cannot open file */
403 s = get_filestream(f, bfile);
404 if (!s) {
405 fclose(bfile);
406 free(fn); /* cannot allocate descriptor */
407 continue;
409 if (open_wrapper(s)) {
410 fclose(bfile);
411 free(fn);
412 free(s);
413 continue; /* cannot run open on file */
415 /* ok this is good for OPEN */
416 res = 1; /* found */
417 s->lasttimeout = -1;
418 s->fmt = f;
419 s->trans = NULL;
420 s->filename = NULL;
421 if (s->fmt->format < AST_FORMAT_MAX_AUDIO)
422 chan->stream = s;
423 else
424 chan->vstream = s;
425 break;
427 switch (action) {
428 case ACTION_OPEN:
429 break; /* will never get here */
431 case ACTION_EXISTS: /* return the matching format */
432 res |= f->format;
433 break;
435 case ACTION_DELETE:
436 if ( (res = unlink(fn)) )
437 ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
438 break;
440 case ACTION_RENAME:
441 case ACTION_COPY: {
442 char *nfn = build_filename((const char *)arg2, ext);
443 if (!nfn)
444 ast_log(LOG_WARNING, "Out of memory\n");
445 else {
446 res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
447 if (res)
448 ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
449 action == ACTION_COPY ? "copy" : "rename",
450 fn, nfn, strerror(errno));
451 free(nfn);
454 break;
456 default:
457 ast_log(LOG_WARNING, "Unknown helper %d\n", action);
459 free(fn);
462 AST_LIST_UNLOCK(&formats);
463 return res;
467 * \brief helper routine to locate a file with a given format
468 * and language preference.
469 * Try preflang, preflang with stripped '_' suffix, or NULL.
470 * In the standard asterisk, language goes just before the last component.
471 * In an alternative configuration, the language should be a prefix
472 * to the actual filename.
474 * The last parameter(s) point to a buffer of sufficient size,
475 * which on success is filled with the matching filename.
477 static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
478 char *buf, int buflen)
480 int res = -1;
481 int langlen; /* length of language string */
482 const char *c = strrchr(filename, '/');
483 int offset = c ? c - filename + 1 : 0; /* points right after the last '/' */
485 if (preflang == NULL)
486 preflang = "";
487 langlen = strlen(preflang);
489 if (buflen < langlen + strlen(filename) + 2) {
490 ast_log(LOG_WARNING, "buffer too small\n");
491 buf[0] = '\0'; /* set to empty */
492 buf = alloca(langlen + strlen(filename) + 2); /* room for everything */
494 if (buf == NULL)
495 return 0;
496 buf[0] = '\0';
497 for (;;) {
498 if (ast_language_is_prefix) { /* new layout */
499 if (langlen) {
500 strcpy(buf, preflang);
501 buf[langlen] = '/';
502 strcpy(buf + langlen + 1, filename);
503 } else
504 strcpy(buf, filename); /* first copy the full string */
505 } else { /* old layout */
506 strcpy(buf, filename); /* first copy the full string */
507 if (langlen) {
508 /* insert the language and suffix if needed */
509 strcpy(buf + offset, preflang);
510 sprintf(buf + offset + langlen, "/%s", filename + offset);
513 res = ast_filehelper(buf, NULL, fmt, ACTION_EXISTS);
514 if (res > 0) /* found format */
515 break;
516 if (langlen == 0) /* no more formats */
517 break;
518 if (preflang[langlen] == '_') /* we are on the local suffix */
519 langlen = 0; /* try again with no language */
520 else
521 langlen = (c = strchr(preflang, '_')) ? c - preflang : 0;
523 return res;
526 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
528 return ast_openstream_full(chan, filename, preflang, 0);
531 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
534 * Use fileexists_core() to find a file in a compatible
535 * language and format, set up a suitable translator,
536 * and open the stream.
538 int fmts, res, buflen;
539 char *buf;
541 if (!asis) {
542 /* do this first, otherwise we detect the wrong writeformat */
543 ast_stopstream(chan);
544 if (chan->generator)
545 ast_deactivate_generator(chan);
547 if (preflang == NULL)
548 preflang = "";
549 buflen = strlen(preflang) + strlen(filename) + 2;
550 buf = alloca(buflen);
551 if (buf == NULL)
552 return NULL;
553 fmts = fileexists_core(filename, NULL, preflang, buf, buflen);
554 if (fmts > 0)
555 fmts &= AST_FORMAT_AUDIO_MASK;
556 if (fmts < 1) {
557 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
558 return NULL;
560 chan->oldwriteformat = chan->writeformat;
561 /* Set the channel to a format we can work with */
562 res = ast_set_write_format(chan, fmts);
563 res = ast_filehelper(buf, chan, NULL, ACTION_OPEN);
564 if (res >= 0)
565 return chan->stream;
566 return NULL;
569 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
571 /* As above, but for video. But here we don't have translators
572 * so we must enforce a format.
574 unsigned int format;
575 char *buf;
576 int buflen;
578 if (preflang == NULL)
579 preflang = "";
580 buflen = strlen(preflang) + strlen(filename) + 2;
581 buf = alloca(buflen);
582 if (buf == NULL)
583 return NULL;
585 for (format = AST_FORMAT_MAX_AUDIO << 1; format <= AST_FORMAT_MAX_VIDEO; format = format << 1) {
586 int fd;
587 const char *fmt;
589 if (!(chan->nativeformats & format))
590 continue;
591 fmt = ast_getformatname(format);
592 if ( fileexists_core(filename, fmt, preflang, buf, buflen) < 1) /* no valid format */
593 continue;
594 fd = ast_filehelper(buf, chan, fmt, ACTION_OPEN);
595 if (fd >= 0)
596 return chan->vstream;
597 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
599 return NULL;
602 struct ast_frame *ast_readframe(struct ast_filestream *s)
604 struct ast_frame *f = NULL;
605 int whennext = 0;
606 if (s && s->fmt)
607 f = s->fmt->read(s, &whennext);
608 return f;
611 static int ast_readaudio_callback(void *data)
613 struct ast_filestream *s = data;
614 int whennext = 0;
616 while(!whennext) {
617 struct ast_frame *fr = s->fmt->read(s, &whennext);
618 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
619 if (fr)
620 ast_log(LOG_WARNING, "Failed to write frame\n");
621 s->owner->streamid = -1;
622 #ifdef HAVE_ZAPTEL
623 ast_settimeout(s->owner, 0, NULL, NULL);
624 #endif
625 return 0;
628 if (whennext != s->lasttimeout) {
629 #ifdef HAVE_ZAPTEL
630 if (s->owner->timingfd > -1)
631 ast_settimeout(s->owner, whennext, ast_readaudio_callback, s);
632 else
633 #endif
634 s->owner->streamid = ast_sched_add(s->owner->sched, whennext/8, ast_readaudio_callback, s);
635 s->lasttimeout = whennext;
636 return 0;
638 return 1;
641 static int ast_readvideo_callback(void *data)
643 struct ast_filestream *s = data;
644 int whennext = 0;
646 while (!whennext) {
647 struct ast_frame *fr = s->fmt->read(s, &whennext);
648 if (!fr || ast_write(s->owner, fr)) { /* no stream or error, as above */
649 if (fr)
650 ast_log(LOG_WARNING, "Failed to write frame\n");
651 s->owner->vstreamid = -1;
652 return 0;
655 if (whennext != s->lasttimeout) {
656 s->owner->vstreamid = ast_sched_add(s->owner->sched, whennext/8, ast_readvideo_callback, s);
657 s->lasttimeout = whennext;
658 return 0;
660 return 1;
663 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
665 s->owner = chan;
666 return 0;
669 int ast_playstream(struct ast_filestream *s)
671 if (s->fmt->format < AST_FORMAT_MAX_AUDIO)
672 ast_readaudio_callback(s);
673 else
674 ast_readvideo_callback(s);
675 return 0;
678 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
680 return fs->fmt->seek(fs, sample_offset, whence);
683 int ast_truncstream(struct ast_filestream *fs)
685 return fs->fmt->trunc(fs);
688 off_t ast_tellstream(struct ast_filestream *fs)
690 return fs->fmt->tell(fs);
693 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
695 return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
698 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
700 return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
703 int ast_closestream(struct ast_filestream *f)
705 char *cmd = NULL;
706 size_t size = 0;
707 /* Stop a running stream if there is one */
708 if (f->owner) {
709 if (f->fmt->format < AST_FORMAT_MAX_AUDIO) {
710 f->owner->stream = NULL;
711 if (f->owner->streamid > -1)
712 ast_sched_del(f->owner->sched, f->owner->streamid);
713 f->owner->streamid = -1;
714 #ifdef HAVE_ZAPTEL
715 ast_settimeout(f->owner, 0, NULL, NULL);
716 #endif
717 } else {
718 f->owner->vstream = NULL;
719 if (f->owner->vstreamid > -1)
720 ast_sched_del(f->owner->sched, f->owner->vstreamid);
721 f->owner->vstreamid = -1;
724 /* destroy the translator on exit */
725 if (f->trans)
726 ast_translator_free_path(f->trans);
728 if (f->realfilename && f->filename) {
729 size = strlen(f->filename) + strlen(f->realfilename) + 15;
730 cmd = alloca(size);
731 memset(cmd,0,size);
732 snprintf(cmd,size,"/bin/mv -f %s %s",f->filename,f->realfilename);
733 ast_safe_system(cmd);
736 if (f->filename)
737 free(f->filename);
738 if (f->realfilename)
739 free(f->realfilename);
740 if (f->fmt->close)
741 f->fmt->close(f);
742 fclose(f->f);
743 if (f->vfs)
744 ast_closestream(f->vfs);
745 ast_atomic_fetchadd_int(&f->fmt->module->usecnt, -1);
746 ast_update_use_count();
747 free(f);
748 return 0;
753 * Look the various language-specific places where a file could exist.
755 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
757 char *buf;
758 int buflen;
760 if (preflang == NULL)
761 preflang = "";
762 buflen = strlen(preflang) + strlen(filename) + 2; /* room for everything */
763 buf = alloca(buflen);
764 if (buf == NULL)
765 return 0;
766 return fileexists_core(filename, fmt, preflang, buf, buflen);
769 int ast_filedelete(const char *filename, const char *fmt)
771 return ast_filehelper(filename, NULL, fmt, ACTION_DELETE);
774 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
776 return ast_filehelper(filename, filename2, fmt, ACTION_RENAME);
779 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
781 return ast_filehelper(filename, filename2, fmt, ACTION_COPY);
784 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
786 struct ast_filestream *fs;
787 struct ast_filestream *vfs=NULL;
788 char fmt[256];
790 fs = ast_openstream(chan, filename, preflang);
791 if (fs)
792 vfs = ast_openvstream(chan, filename, preflang);
793 if (vfs)
794 ast_log(LOG_DEBUG, "Ooh, found a video stream, too, format %s\n", ast_getformatname(vfs->fmt->format));
795 if (fs){
796 if (ast_applystream(chan, fs))
797 return -1;
798 if (vfs && ast_applystream(chan, vfs))
799 return -1;
800 if (ast_playstream(fs))
801 return -1;
802 if (vfs && ast_playstream(vfs))
803 return -1;
804 #if 1
805 if (option_verbose > 2)
806 ast_verbose(VERBOSE_PREFIX_3 "Playing '%s' (language '%s')\n", filename, preflang ? preflang : "default");
807 #endif
808 return 0;
810 ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), chan->nativeformats), strerror(errno));
811 return -1;
814 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
816 FILE *bfile;
817 struct ast_format *f;
818 struct ast_filestream *fs = NULL;
819 char *fn;
821 if (AST_LIST_LOCK(&formats)) {
822 ast_log(LOG_WARNING, "Unable to lock format list\n");
823 return NULL;
826 AST_LIST_TRAVERSE(&formats, f, list) {
827 fs = NULL;
828 if (!exts_compare(f->exts, type))
829 continue;
831 fn = build_filename(filename, type);
832 errno = 0;
833 bfile = fopen(fn, "r");
834 if (!bfile || (fs = get_filestream(f, bfile)) == NULL ||
835 open_wrapper(fs) ) {
836 ast_log(LOG_WARNING, "Unable to open %s\n", fn);
837 fclose(bfile);
838 free(fn);
839 if (fs)
840 free(fs);
841 continue;
843 /* found it */
844 fs->trans = NULL;
845 fs->fmt = f;
846 fs->flags = flags;
847 fs->mode = mode;
848 fs->filename = strdup(filename);
849 fs->vfs = NULL;
850 break;
853 AST_LIST_UNLOCK(&formats);
854 if (!fs)
855 ast_log(LOG_WARNING, "No such format '%s'\n", type);
857 return fs;
860 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
862 int fd, myflags = 0;
863 /* compiler claims this variable can be used before initialization... */
864 FILE *bfile = NULL;
865 struct ast_format *f;
866 struct ast_filestream *fs = NULL;
867 char *buf = NULL;
868 size_t size = 0;
869 int format_found = 0;
871 if (AST_LIST_LOCK(&formats)) {
872 ast_log(LOG_WARNING, "Unable to lock format list\n");
873 return NULL;
876 /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
877 /* We really can't use O_APPEND as it will break WAV header updates */
878 if (flags & O_APPEND) {
879 flags &= ~O_APPEND;
880 } else {
881 myflags = O_TRUNC;
884 myflags |= O_WRONLY | O_CREAT;
886 /* XXX need to fix this - we should just do the fopen,
887 * not open followed by fdopen()
889 AST_LIST_TRAVERSE(&formats, f, list) {
890 char *fn, *orig_fn = NULL;
891 if (fs)
892 break;
894 if (!exts_compare(f->exts, type))
895 continue;
896 else
897 format_found = 1;
899 fn = build_filename(filename, type);
900 fd = open(fn, flags | myflags, mode);
901 if (fd > -1) {
902 /* fdopen() the resulting file stream */
903 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
904 if (!bfile) {
905 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
906 close(fd);
907 fd = -1;
911 if (ast_opt_cache_record_files && (fd > -1)) {
912 char *c;
914 fclose(bfile); /* this also closes fd */
916 We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
917 What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
919 orig_fn = ast_strdupa(fn);
920 for (c = fn; *c; c++)
921 if (*c == '/')
922 *c = '_';
924 size = strlen(fn) + strlen(record_cache_dir) + 2;
925 buf = alloca(size);
926 strcpy(buf, record_cache_dir);
927 strcat(buf, "/");
928 strcat(buf, fn);
929 free(fn);
930 fn = buf;
931 fd = open(fn, flags | myflags, mode);
932 if (fd > -1) {
933 /* fdopen() the resulting file stream */
934 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
935 if (!bfile) {
936 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
937 close(fd);
938 fd = -1;
942 if (fd > -1) {
943 errno = 0;
944 fs = get_filestream(f, bfile);
945 if (!fs || rewrite_wrapper(fs, comment)) {
946 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
947 close(fd);
948 if (orig_fn) {
949 unlink(fn);
950 unlink(orig_fn);
952 if (fs)
953 free(fs);
955 fs->trans = NULL;
956 fs->fmt = f;
957 fs->flags = flags;
958 fs->mode = mode;
959 if (orig_fn) {
960 fs->realfilename = strdup(orig_fn);
961 fs->filename = strdup(fn);
962 } else {
963 fs->realfilename = NULL;
964 fs->filename = strdup(filename);
966 fs->vfs = NULL;
967 /* If truncated, we'll be at the beginning; if not truncated, then append */
968 f->seek(fs, 0, SEEK_END);
969 } else if (errno != EEXIST) {
970 ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
971 if (orig_fn)
972 unlink(orig_fn);
974 /* if buf != NULL then fn is already free and pointing to it */
975 if (!buf)
976 free(fn);
979 AST_LIST_UNLOCK(&formats);
981 if (!format_found)
982 ast_log(LOG_WARNING, "No such format '%s'\n", type);
984 return fs;
988 * \brief the core of all waitstream() functions
990 static int waitstream_core(struct ast_channel *c, const char *breakon,
991 const char *forward, const char *rewind, int skip_ms,
992 int audiofd, int cmdfd, const char *context)
994 if (!breakon)
995 breakon = "";
996 if (!forward)
997 forward = "";
998 if (!rewind)
999 rewind = "";
1001 while (c->stream) {
1002 int res;
1003 int ms = ast_sched_wait(c->sched);
1004 if (ms < 0 && !c->timingfunc) {
1005 ast_stopstream(c);
1006 break;
1008 if (ms < 0)
1009 ms = 1000;
1010 if (!cmdfd) {
1011 res = ast_waitfor(c, ms);
1012 if (res < 0) {
1013 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1014 return res;
1016 } else {
1017 int outfd;
1018 struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1019 if (!rchan && (outfd < 0) && (ms)) {
1020 /* Continue */
1021 if (errno == EINTR)
1022 continue;
1023 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1024 return -1;
1025 } else if (outfd > -1) { /* this requires cmdfd set */
1026 /* The FD we were watching has something waiting */
1027 return 1;
1029 /* if rchan is set, it is 'c' */
1030 res = rchan ? 1 : 0; /* map into 'res' values */
1032 if (res > 0) {
1033 struct ast_frame *fr = ast_read(c);
1034 if (!fr)
1035 return -1;
1036 switch(fr->frametype) {
1037 case AST_FRAME_DTMF:
1038 if (context) {
1039 const char exten[2] = { fr->subclass, '\0' };
1040 if (ast_exists_extension(c, context, exten, 1, c->cid.cid_num)) {
1041 ast_frfree(fr);
1042 return res;
1044 } else {
1045 res = fr->subclass;
1046 if (strchr(forward,res)) {
1047 ast_stream_fastforward(c->stream, skip_ms);
1048 } else if (strchr(rewind,res)) {
1049 ast_stream_rewind(c->stream, skip_ms);
1050 } else if (strchr(breakon, res)) {
1051 ast_frfree(fr);
1052 return res;
1055 break;
1056 case AST_FRAME_CONTROL:
1057 switch(fr->subclass) {
1058 case AST_CONTROL_HANGUP:
1059 ast_frfree(fr);
1060 return -1;
1061 case AST_CONTROL_RINGING:
1062 case AST_CONTROL_ANSWER:
1063 case AST_CONTROL_VIDUPDATE:
1064 /* Unimportant */
1065 break;
1066 default:
1067 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass);
1069 case AST_FRAME_VOICE:
1070 /* Write audio if appropriate */
1071 if (audiofd > -1)
1072 write(audiofd, fr->data, fr->datalen);
1074 /* Ignore all others */
1075 ast_frfree(fr);
1077 ast_sched_runq(c->sched);
1079 return (c->_softhangup ? -1 : 0);
1082 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *rewind, int ms)
1084 return waitstream_core(c, breakon, forward, rewind, ms,
1085 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */);
1088 int ast_waitstream(struct ast_channel *c, const char *breakon)
1090 return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL);
1093 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1095 return waitstream_core(c, breakon, NULL, NULL, 0,
1096 audiofd, cmdfd, NULL /* no context */);
1099 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1101 /* Waitstream, with return in the case of a valid 1 digit extension */
1102 /* in the current or specified context being pressed */
1104 if (!context)
1105 context = c->context;
1106 return waitstream_core(c, NULL, NULL, NULL, 0,
1107 -1, -1, context);
1111 * if the file name is non-empty, try to play it.
1112 * Return 0 if success, -1 if error, digit if interrupted by a digit.
1113 * If digits == "" then we can simply check for non-zero.
1115 int ast_stream_and_wait(struct ast_channel *chan, const char *file,
1116 const char *language, const char *digits)
1118 int res = 0;
1119 if (!ast_strlen_zero(file)) {
1120 res = ast_streamfile(chan, file, language);
1121 if (!res)
1122 res = ast_waitstream(chan, digits);
1124 return res;
1127 static int show_file_formats(int fd, int argc, char *argv[])
1129 #define FORMAT "%-10s %-10s %-20s\n"
1130 #define FORMAT2 "%-10s %-10s %-20s\n"
1131 struct ast_format *f;
1132 int count_fmt = 0;
1134 if (argc != 3)
1135 return RESULT_SHOWUSAGE;
1136 ast_cli(fd, FORMAT, "Format", "Name", "Extensions");
1138 if (AST_LIST_LOCK(&formats)) {
1139 ast_log(LOG_WARNING, "Unable to lock format list\n");
1140 return -1;
1143 AST_LIST_TRAVERSE(&formats, f, list) {
1144 ast_cli(fd, FORMAT2, ast_getformatname(f->format), f->name, f->exts);
1145 count_fmt++;
1147 AST_LIST_UNLOCK(&formats);
1148 ast_cli(fd, "%d file formats registered.\n", count_fmt);
1149 return RESULT_SUCCESS;
1150 #undef FORMAT
1151 #undef FORMAT2
1154 struct ast_cli_entry show_file =
1156 { "show", "file", "formats" },
1157 show_file_formats,
1158 "Displays file formats",
1159 "Usage: show file formats\n"
1160 " displays currently registered file formats (if any)\n"
1163 int ast_file_init(void)
1165 ast_cli_register(&show_file);
1166 return 0;