dda1b3d634fa58d66c05668dae11b4c4939bad41
[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 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
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>
40
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"
55
56 /*
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.
63  */
64 int ast_language_is_prefix = 1;
65
66 static AST_RWLIST_HEAD_STATIC(formats, ast_format);
67
68 int __ast_format_register(const struct ast_format *f, struct ast_module *mod)
69 {
70         struct ast_format *tmp;
71
72         AST_RWLIST_WRLOCK(&formats);
73         AST_RWLIST_TRAVERSE(&formats, tmp, list) {
74                 if (!strcasecmp(f->name, tmp->name)) {
75                         AST_RWLIST_UNLOCK(&formats);
76                         ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
77                         return -1;
78                 }
79         }
80         if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
81                 AST_RWLIST_UNLOCK(&formats);
82                 return -1;
83         }
84         *tmp = *f;
85         tmp->module = mod;
86         if (tmp->buf_size) {
87                 /*
88                  * Align buf_size properly, rounding up to the machine-specific
89                  * alignment for pointers.
90                  */
91                 struct _test_align { void *a, *b; } p;
92                 int align = (char *)&p.b - (char *)&p.a;
93                 tmp->buf_size = ((f->buf_size + align - 1)/align)*align;
94         }
95         
96         memset(&tmp->list, 0, sizeof(tmp->list));
97
98         AST_RWLIST_INSERT_HEAD(&formats, tmp, list);
99         AST_RWLIST_UNLOCK(&formats);
100         ast_verb(2, "Registered file format %s, extension(s) %s\n", f->name, f->exts);
101
102         return 0;
103 }
104
105 int ast_format_unregister(const char *name)
106 {
107         struct ast_format *tmp;
108         int res = -1;
109
110         AST_RWLIST_WRLOCK(&formats);
111         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
112                 if (!strcasecmp(name, tmp->name)) {
113                         AST_RWLIST_REMOVE_CURRENT(&formats, list);
114                         ast_free(tmp);
115                         res = 0;
116                 }
117         }
118         AST_RWLIST_TRAVERSE_SAFE_END
119         AST_RWLIST_UNLOCK(&formats);
120
121         if (!res)
122                 ast_verb(2, "Unregistered format %s\n", name);
123         else
124                 ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
125
126         return res;
127 }
128
129 int ast_stopstream(struct ast_channel *tmp)
130 {
131         /* Stop a running stream if there is one */
132         if (tmp->stream) {
133                 ast_closestream(tmp->stream);
134                 tmp->stream = NULL;
135                 if (tmp->oldwriteformat && ast_set_write_format(tmp, tmp->oldwriteformat))
136                         ast_log(LOG_WARNING, "Unable to restore format back to %d\n", tmp->oldwriteformat);
137         }
138         /* Stop the video stream too */
139         if (tmp->vstream != NULL) {
140                 ast_closestream(tmp->vstream);
141                 tmp->vstream = NULL;
142         }
143         return 0;
144 }
145
146 int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
147 {
148         int res = -1;
149         int alt = 0;
150         if (f->frametype == AST_FRAME_VIDEO) {
151                 if (fs->fmt->format < AST_FORMAT_MAX_AUDIO) {
152                         /* This is the audio portion.  Call the video one... */
153                         if (!fs->vfs && fs->filename) {
154                                 const char *type = ast_getformatname(f->subclass & ~0x1);
155                                 fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
156                                 ast_debug(1, "Opened video output file\n");
157                         }
158                         if (fs->vfs)
159                                 return ast_writestream(fs->vfs, f);
160                         /* else ignore */
161                         return 0;                               
162                 } else {
163                         /* Might / might not have mark set */
164                         alt = 1;
165                 }
166         } else if (f->frametype != AST_FRAME_VOICE) {
167                 ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
168                 return -1;
169         }
170         if (((fs->fmt->format | alt) & f->subclass) == f->subclass) {
171                 res =  fs->fmt->write(fs, f);
172                 if (res < 0) 
173                         ast_log(LOG_WARNING, "Natural write failed\n");
174                 else if (res > 0)
175                         ast_log(LOG_WARNING, "Huh??\n");
176         } else {
177                 /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
178                        the one we've setup a translator for, we do the "wrong thing" XXX */
179                 if (fs->trans && f->subclass != fs->lastwriteformat) {
180                         ast_translator_free_path(fs->trans);
181                         fs->trans = NULL;
182                 }
183                 if (!fs->trans) 
184                         fs->trans = ast_translator_build_path(fs->fmt->format, f->subclass);
185                 if (!fs->trans)
186                         ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
187                                 fs->fmt->name, ast_getformatname(f->subclass));
188                 else {
189                         struct ast_frame *trf;
190                         fs->lastwriteformat = f->subclass;
191                         /* Get the translated frame but don't consume the original in case they're using it on another stream */
192                         trf = ast_translate(fs->trans, f, 0);
193                         if (trf) {
194                                 res = fs->fmt->write(fs, trf);
195                                 if (res) 
196                                         ast_log(LOG_WARNING, "Translated frame write failed\n");
197                         } else
198                                 res = 0;
199                 }
200         }
201         return res;
202 }
203
204 static int copy(const char *infile, const char *outfile)
205 {
206         int ifd, ofd, len;
207         char buf[4096]; /* XXX make it lerger. */
208
209         if ((ifd = open(infile, O_RDONLY)) < 0) {
210                 ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
211                 return -1;
212         }
213         if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, AST_FILE_MODE)) < 0) {
214                 ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
215                 close(ifd);
216                 return -1;
217         }
218         while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
219                 int res;
220                 if (len < 0) {
221                         ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
222                         break;
223                 }
224                 /* XXX handle partial writes */
225                 res = write(ofd, buf, len);
226                 if (res != len) {
227                         ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
228                         len = -1; /* error marker */
229                         break;
230                 }
231         }
232         close(ifd);
233         close(ofd);
234         if (len < 0) {
235                 unlink(outfile);
236                 return -1; /* error */
237         }
238         return 0;       /* success */
239 }
240
241 /*!
242  * \brief construct a filename. Absolute pathnames are preserved,
243  * relative names are prefixed by the sounds/ directory.
244  * The wav49 suffix is replaced by 'WAV'.
245  * Returns a malloc'ed string to be freed by the caller.
246  */
247 static char *build_filename(const char *filename, const char *ext)
248 {
249         char *fn = NULL;
250
251         if (!strcmp(ext, "wav49"))
252                 ext = "WAV";
253
254         if (filename[0] == '/')
255                 asprintf(&fn, "%s.%s", filename, ext);
256         else
257                 asprintf(&fn, "%s/sounds/%s.%s",
258                         ast_config_AST_DATA_DIR, filename, ext);
259         return fn;
260 }
261
262 /* compare type against the list 'exts' */
263 /* XXX need a better algorithm */
264 static int exts_compare(const char *exts, const char *type)
265 {
266         char tmp[256];
267         char *stringp = tmp, *ext;
268
269         ast_copy_string(tmp, exts, sizeof(tmp));
270         while ((ext = strsep(&stringp, "|"))) {
271                 if (!strcmp(ext, type))
272                         return 1;
273         }
274
275         return 0;
276 }
277
278 static struct ast_filestream *get_filestream(struct ast_format *fmt, FILE *bfile)
279 {
280         struct ast_filestream *s;
281
282         int l = sizeof(*s) + fmt->buf_size + fmt->desc_size;    /* total allocation size */
283         if ( (s = ast_calloc(1, l)) == NULL)
284                 return NULL;
285         s->fmt = fmt;
286         s->f = bfile;
287
288         if (fmt->desc_size)
289                 s->private = ((char *)(s+1)) + fmt->buf_size;
290         if (fmt->buf_size)
291                 s->buf = (char *)(s+1);
292         s->fr.src = fmt->name;
293         return s;
294 }
295
296 /*
297  * Default implementations of open and rewrite.
298  * Only use them if you don't have expensive stuff to do.
299  */
300 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
301
302 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
303 {
304         struct ast_format *f = s->fmt;
305         int ret = -1;
306
307         if (mode == WRAP_OPEN && f->open && f->open(s))
308                 ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
309         else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
310                 ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
311         else {
312                 /* preliminary checks succeed. update usecount */
313                 ast_module_ref(f->module);
314                 ret = 0;
315         }
316         return ret;
317 }
318
319 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
320 {
321         return fn_wrapper(s, comment, WRAP_REWRITE);
322 }
323                 
324 static int open_wrapper(struct ast_filestream *s)
325 {
326         return fn_wrapper(s, NULL, WRAP_OPEN);
327 }
328
329 enum file_action {
330         ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
331         ACTION_DELETE,  /* delete file, return 0 on success, -1 on error */
332         ACTION_RENAME,  /* rename file. return 0 on success, -1 on error */
333         ACTION_OPEN,
334         ACTION_COPY     /* copy file. return 0 on success, -1 on error */
335 };
336
337 /*!
338  * \brief perform various actions on a file. Second argument
339  * arg2 depends on the command:
340  *      unused for EXISTS and DELETE
341  *      destination file name (const char *) for COPY and RENAME
342  *      struct ast_channel * for OPEN
343  * if fmt is NULL, OPEN will return the first matching entry,
344  * whereas other functions will run on all matching entries.
345  */
346 static int ast_filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
347 {
348         struct ast_format *f;
349         int res = (action == ACTION_EXISTS) ? 0 : -1;
350
351         AST_RWLIST_RDLOCK(&formats);
352         /* Check for a specific format */
353         AST_RWLIST_TRAVERSE(&formats, f, list) {
354                 char *stringp, *ext = NULL;
355
356                 if (fmt && !exts_compare(f->exts, fmt))
357                         continue;
358
359                 /* Look for a file matching the supported extensions.
360                  * The file must exist, and for OPEN, must match
361                  * one of the formats supported by the channel.
362                  */
363                 stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
364                 while ( (ext = strsep(&stringp, "|")) ) {
365                         struct stat st;
366                         char *fn = build_filename(filename, ext);
367
368                         if (fn == NULL)
369                                 continue;
370
371                         if ( stat(fn, &st) ) { /* file not existent */
372                                 ast_free(fn);
373                                 continue;
374                         }
375                         /* for 'OPEN' we need to be sure that the format matches
376                          * what the channel can process
377                          */
378                         if (action == ACTION_OPEN) {
379                                 struct ast_channel *chan = (struct ast_channel *)arg2;
380                                 FILE *bfile;
381                                 struct ast_filestream *s;
382
383                                 if ( !(chan->writeformat & f->format) &&
384                                      !(f->format >= AST_FORMAT_MAX_AUDIO && fmt)) {
385                                         ast_free(fn);
386                                         continue;       /* not a supported format */
387                                 }
388                                 if ( (bfile = fopen(fn, "r")) == NULL) {
389                                         ast_free(fn);
390                                         continue;       /* cannot open file */
391                                 }
392                                 s = get_filestream(f, bfile);
393                                 if (!s) {
394                                         fclose(bfile);
395                                         ast_free(fn);   /* cannot allocate descriptor */
396                                         continue;
397                                 }
398                                 if (open_wrapper(s)) {
399                                         fclose(bfile);
400                                         ast_free(fn);
401                                         ast_free(s);
402                                         continue;       /* cannot run open on file */
403                                 }
404                                 /* ok this is good for OPEN */
405                                 res = 1;        /* found */
406                                 s->lasttimeout = -1;
407                                 s->fmt = f;
408                                 s->trans = NULL;
409                                 s->filename = NULL;
410                                 if (s->fmt->format < AST_FORMAT_MAX_AUDIO) {
411                                         if (chan->stream)
412                                                 ast_closestream(chan->stream);
413                                         chan->stream = s;
414                                 } else {
415                                         if (chan->vstream)
416                                                 ast_closestream(chan->vstream);
417                                         chan->vstream = s;
418                                 }
419                                 ast_free(fn);
420                                 break;
421                         }
422                         switch (action) {
423                         case ACTION_OPEN:
424                                 break;  /* will never get here */
425
426                         case ACTION_EXISTS:     /* return the matching format */
427                                 res |= f->format;
428                                 break;
429
430                         case ACTION_DELETE:
431                                 if ( (res = unlink(fn)) )
432                                         ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
433                                 break;
434
435                         case ACTION_RENAME:
436                         case ACTION_COPY: {
437                                 char *nfn = build_filename((const char *)arg2, ext);
438                                 if (!nfn)
439                                         ast_log(LOG_WARNING, "Out of memory\n");
440                                 else {
441                                         res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
442                                         if (res)
443                                                 ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
444                                                         action == ACTION_COPY ? "copy" : "rename",
445                                                          fn, nfn, strerror(errno));
446                                         ast_free(nfn);
447                                 }
448                             }
449                                 break;
450
451                         default:
452                                 ast_log(LOG_WARNING, "Unknown helper %d\n", action);
453                         }
454                         ast_free(fn);
455                 }
456         }
457         AST_RWLIST_UNLOCK(&formats);
458         return res;
459 }
460
461 /*!
462  * \brief helper routine to locate a file with a given format
463  * and language preference.
464  * Try preflang, preflang with stripped '_' suffix, or NULL.
465  * In the standard asterisk, language goes just before the last component.
466  * In an alternative configuration, the language should be a prefix
467  * to the actual filename.
468  *
469  * The last parameter(s) point to a buffer of sufficient size,
470  * which on success is filled with the matching filename.
471  */
472 static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
473                 char *buf, int buflen)
474 {
475         int res = -1;
476         int langlen;    /* length of language string */
477         const char *c = strrchr(filename, '/');
478         int offset = c ? c - filename + 1 : 0;  /* points right after the last '/' */
479
480         if (preflang == NULL)
481                 preflang = "";
482         langlen = strlen(preflang);
483         
484         if (buflen < langlen + strlen(filename) + 2) {
485                 ast_log(LOG_WARNING, "buffer too small\n");
486                 buf[0] = '\0'; /* set to empty */
487                 buf = alloca(langlen + strlen(filename) + 2);   /* room for everything */
488         }
489         if (buf == NULL)
490                 return 0;
491         buf[0] = '\0';
492         for (;;) {
493                 if (ast_language_is_prefix) { /* new layout */
494                         if (langlen) {
495                                 strcpy(buf, preflang);
496                                 buf[langlen] = '/';
497                                 strcpy(buf + langlen + 1, filename);
498                         } else
499                                 strcpy(buf, filename);  /* first copy the full string */
500                 } else { /* old layout */
501                         strcpy(buf, filename);  /* first copy the full string */
502                         if (langlen) {
503                                 /* insert the language and suffix if needed */
504                                 strcpy(buf + offset, preflang);
505                                 sprintf(buf + offset + langlen, "/%s", filename + offset);
506                         }
507                 }
508                 res = ast_filehelper(buf, NULL, fmt, ACTION_EXISTS);
509                 if (res > 0)            /* found format */
510                         break;
511                 if (langlen == 0)       /* no more formats */
512                         break;
513                 if (preflang[langlen] == '_') /* we are on the local suffix */
514                         langlen = 0;    /* try again with no language */
515                 else
516                         langlen = (c = strchr(preflang, '_')) ? c - preflang : 0;
517         }
518         return res;
519 }
520
521 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
522 {
523         return ast_openstream_full(chan, filename, preflang, 0);
524 }
525
526 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
527 {
528         /* 
529          * Use fileexists_core() to find a file in a compatible
530          * language and format, set up a suitable translator,
531          * and open the stream.
532          */
533         int fmts, res, buflen;
534         char *buf;
535
536         if (!asis) {
537                 /* do this first, otherwise we detect the wrong writeformat */
538                 ast_stopstream(chan);
539                 if (chan->generator)
540                         ast_deactivate_generator(chan);
541         }
542         if (preflang == NULL)
543                 preflang = "";
544         buflen = strlen(preflang) + strlen(filename) + 2;
545         buf = alloca(buflen);
546         if (buf == NULL)
547                 return NULL;
548         fmts = fileexists_core(filename, NULL, preflang, buf, buflen);
549         if (fmts > 0)
550                 fmts &= AST_FORMAT_AUDIO_MASK;
551         if (fmts < 1) {
552                 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
553                 return NULL;
554         }
555         chan->oldwriteformat = chan->writeformat;
556         /* Set the channel to a format we can work with */
557         res = ast_set_write_format(chan, fmts);
558         res = ast_filehelper(buf, chan, NULL, ACTION_OPEN);
559         if (res >= 0)
560                 return chan->stream;
561         return NULL;
562 }
563
564 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
565 {
566         /* As above, but for video. But here we don't have translators
567          * so we must enforce a format.
568          */
569         unsigned int format;
570         char *buf;
571         int buflen;
572
573         if (preflang == NULL)
574                 preflang = "";
575         buflen = strlen(preflang) + strlen(filename) + 2;
576         buf = alloca(buflen);
577         if (buf == NULL)
578                 return NULL;
579
580         for (format = AST_FORMAT_MAX_AUDIO << 1; format <= AST_FORMAT_MAX_VIDEO; format = format << 1) {
581                 int fd;
582                 const char *fmt;
583
584                 if (!(chan->nativeformats & format))
585                         continue;
586                 fmt = ast_getformatname(format);
587                 if ( fileexists_core(filename, fmt, preflang, buf, buflen) < 1) /* no valid format */
588                         continue;
589                 fd = ast_filehelper(buf, chan, fmt, ACTION_OPEN);
590                 if (fd >= 0)
591                         return chan->vstream;
592                 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
593         }
594         return NULL;
595 }
596
597 struct ast_frame *ast_readframe(struct ast_filestream *s)
598 {
599         struct ast_frame *f = NULL;
600         int whennext = 0;       
601         if (s && s->fmt)
602                 f = s->fmt->read(s, &whennext);
603         return f;
604 }
605
606 static int ast_readaudio_callback(void *data)
607 {
608         struct ast_filestream *s = data;
609         int whennext = 0;
610
611         while (!whennext) {
612                 struct ast_frame *fr = s->fmt->read(s, &whennext);
613                 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
614                         if (fr)
615                                 ast_log(LOG_WARNING, "Failed to write frame\n");
616                         s->owner->streamid = -1;
617 #ifdef HAVE_ZAPTEL
618                         ast_settimeout(s->owner, 0, NULL, NULL);
619 #endif                  
620                         return 0;
621                 }
622         }
623         if (whennext != s->lasttimeout) {
624 #ifdef HAVE_ZAPTEL
625                 if (s->owner->timingfd > -1)
626                         ast_settimeout(s->owner, whennext, ast_readaudio_callback, s);
627                 else
628 #endif          
629                         s->owner->streamid = ast_sched_add(s->owner->sched, whennext/8, ast_readaudio_callback, s);
630                 s->lasttimeout = whennext;
631                 return 0;
632         }
633         return 1;
634 }
635
636 static int ast_readvideo_callback(void *data)
637 {
638         struct ast_filestream *s = data;
639         int whennext = 0;
640
641         while (!whennext) {
642                 struct ast_frame *fr = s->fmt->read(s, &whennext);
643                 if (!fr || ast_write(s->owner, fr)) { /* no stream or error, as above */
644                         if (fr)
645                                 ast_log(LOG_WARNING, "Failed to write frame\n");
646                         s->owner->vstreamid = -1;
647                         return 0;
648                 }
649         }
650         if (whennext != s->lasttimeout) {
651                 s->owner->vstreamid = ast_sched_add(s->owner->sched, whennext/8, ast_readvideo_callback, s);
652                 s->lasttimeout = whennext;
653                 return 0;
654         }
655         return 1;
656 }
657
658 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
659 {
660         s->owner = chan;
661         return 0;
662 }
663
664 int ast_playstream(struct ast_filestream *s)
665 {
666         if (s->fmt->format < AST_FORMAT_MAX_AUDIO)
667                 ast_readaudio_callback(s);
668         else
669                 ast_readvideo_callback(s);
670         return 0;
671 }
672
673 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
674 {
675         return fs->fmt->seek(fs, sample_offset, whence);
676 }
677
678 int ast_truncstream(struct ast_filestream *fs)
679 {
680         return fs->fmt->trunc(fs);
681 }
682
683 off_t ast_tellstream(struct ast_filestream *fs)
684 {
685         return fs->fmt->tell(fs);
686 }
687
688 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
689 {
690         return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
691 }
692
693 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
694 {
695         return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
696 }
697
698 int ast_closestream(struct ast_filestream *f)
699 {
700         char *cmd = NULL;
701         size_t size = 0;
702         /* Stop a running stream if there is one */
703         if (f->owner) {
704                 if (f->fmt->format < AST_FORMAT_MAX_AUDIO) {
705                         f->owner->stream = NULL;
706                         if (f->owner->streamid > -1)
707                                 ast_sched_del(f->owner->sched, f->owner->streamid);
708                         f->owner->streamid = -1;
709 #ifdef HAVE_ZAPTEL
710                         ast_settimeout(f->owner, 0, NULL, NULL);
711 #endif                  
712                 } else {
713                         f->owner->vstream = NULL;
714                         if (f->owner->vstreamid > -1)
715                                 ast_sched_del(f->owner->sched, f->owner->vstreamid);
716                         f->owner->vstreamid = -1;
717                 }
718         }
719         /* destroy the translator on exit */
720         if (f->trans)
721                 ast_translator_free_path(f->trans);
722
723         if (f->realfilename && f->filename) {
724                         size = strlen(f->filename) + strlen(f->realfilename) + 15;
725                         cmd = alloca(size);
726                         memset(cmd,0,size);
727                         snprintf(cmd,size,"/bin/mv -f %s %s",f->filename,f->realfilename);
728                         ast_safe_system(cmd);
729         }
730
731         if (f->filename)
732                 ast_free(f->filename);
733         if (f->realfilename)
734                 ast_free(f->realfilename);
735         if (f->fmt->close)
736                 f->fmt->close(f);
737         fclose(f->f);
738         if (f->vfs)
739                 ast_closestream(f->vfs);
740         ast_module_unref(f->fmt->module);
741         ast_free(f);
742         return 0;
743 }
744
745
746 /*
747  * Look the various language-specific places where a file could exist.
748  */
749 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
750 {
751         char *buf;
752         int buflen;
753
754         if (preflang == NULL)
755                 preflang = "";
756         buflen = strlen(preflang) + strlen(filename) + 2;       /* room for everything */
757         buf = alloca(buflen);
758         if (buf == NULL)
759                 return 0;
760         return fileexists_core(filename, fmt, preflang, buf, buflen);
761 }
762
763 int ast_filedelete(const char *filename, const char *fmt)
764 {
765         return ast_filehelper(filename, NULL, fmt, ACTION_DELETE);
766 }
767
768 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
769 {
770         return ast_filehelper(filename, filename2, fmt, ACTION_RENAME);
771 }
772
773 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
774 {
775         return ast_filehelper(filename, filename2, fmt, ACTION_COPY);
776 }
777
778 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
779 {
780         struct ast_filestream *fs;
781         struct ast_filestream *vfs=NULL;
782         char fmt[256];
783
784         fs = ast_openstream(chan, filename, preflang);
785         if (fs)
786                 vfs = ast_openvstream(chan, filename, preflang);
787         if (vfs) {
788                 ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_getformatname(vfs->fmt->format));
789         }
790         if (fs){
791                 if (ast_applystream(chan, fs))
792                         return -1;
793                 if (vfs && ast_applystream(chan, vfs))
794                         return -1;
795                 ast_playstream(fs);
796                 if (vfs)
797                         ast_playstream(vfs);
798                 ast_verb(3, "<%s> Playing '%s.%s' (language '%s')\n", chan->name, filename, ast_getformatname(chan->writeformat), preflang ? preflang : "default");
799
800                 return 0;
801         }
802         ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), chan->nativeformats), strerror(errno));
803         return -1;
804 }
805
806 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
807 {
808         FILE *bfile;
809         struct ast_format *f;
810         struct ast_filestream *fs = NULL;
811         char *fn;
812
813         AST_RWLIST_RDLOCK(&formats);
814
815         AST_RWLIST_TRAVERSE(&formats, f, list) {
816                 fs = NULL;
817                 if (!exts_compare(f->exts, type))
818                         continue;
819
820                 fn = build_filename(filename, type);
821                 errno = 0;
822                 bfile = fopen(fn, "r");
823                 if (!bfile || (fs = get_filestream(f, bfile)) == NULL ||
824                     open_wrapper(fs) ) {
825                         ast_log(LOG_WARNING, "Unable to open %s\n", fn);
826                         if (fs)
827                                 ast_free(fs);
828                         if (bfile)
829                                 fclose(bfile);
830                         ast_free(fn);
831                         continue;
832                 }
833                 /* found it */
834                 fs->trans = NULL;
835                 fs->fmt = f;
836                 fs->flags = flags;
837                 fs->mode = mode;
838                 fs->filename = ast_strdup(filename);
839                 fs->vfs = NULL;
840                 break;
841         }
842
843         AST_RWLIST_UNLOCK(&formats);
844         if (!fs) 
845                 ast_log(LOG_WARNING, "No such format '%s'\n", type);
846
847         return fs;
848 }
849
850 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
851 {
852         int fd, myflags = 0;
853         /* compiler claims this variable can be used before initialization... */
854         FILE *bfile = NULL;
855         struct ast_format *f;
856         struct ast_filestream *fs = NULL;
857         char *buf = NULL;
858         size_t size = 0;
859         int format_found = 0;
860
861         AST_RWLIST_RDLOCK(&formats);
862
863         /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
864         /* We really can't use O_APPEND as it will break WAV header updates */
865         if (flags & O_APPEND) { 
866                 flags &= ~O_APPEND;
867         } else {
868                 myflags = O_TRUNC;
869         }
870         
871         myflags |= O_WRONLY | O_CREAT;
872
873         /* XXX need to fix this - we should just do the fopen,
874          * not open followed by fdopen()
875          */
876         AST_RWLIST_TRAVERSE(&formats, f, list) {
877                 char *fn, *orig_fn = NULL;
878                 if (fs)
879                         break;
880
881                 if (!exts_compare(f->exts, type))
882                         continue;
883                 else
884                         format_found = 1;
885
886                 fn = build_filename(filename, type);
887                 fd = open(fn, flags | myflags, mode);
888                 if (fd > -1) {
889                         /* fdopen() the resulting file stream */
890                         bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
891                         if (!bfile) {
892                                 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
893                                 close(fd);
894                                 fd = -1;
895                         }
896                 }
897                 
898                 if (ast_opt_cache_record_files && (fd > -1)) {
899                         char *c;
900
901                         fclose(bfile);  /* this also closes fd */
902                         /*
903                           We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
904                           What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
905                         */
906                         orig_fn = ast_strdupa(fn);
907                         for (c = fn; *c; c++)
908                                 if (*c == '/')
909                                         *c = '_';
910
911                         size = strlen(fn) + strlen(record_cache_dir) + 2;
912                         buf = alloca(size);
913                         strcpy(buf, record_cache_dir);
914                         strcat(buf, "/");
915                         strcat(buf, fn);
916                         ast_free(fn);
917                         fn = buf;
918                         fd = open(fn, flags | myflags, mode);
919                         if (fd > -1) {
920                                 /* fdopen() the resulting file stream */
921                                 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
922                                 if (!bfile) {
923                                         ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
924                                         close(fd);
925                                         fd = -1;
926                                 }
927                         }
928                 }
929                 if (fd > -1) {
930                         errno = 0;
931                         fs = get_filestream(f, bfile);
932                         if (!fs || rewrite_wrapper(fs, comment)) {
933                                 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
934                                 close(fd);
935                                 if (orig_fn) {
936                                         unlink(fn);
937                                         unlink(orig_fn);
938                                 }
939                                 if (fs)
940                                         ast_free(fs);
941                                 fs = NULL;
942                                 continue;
943                         }
944                         fs->trans = NULL;
945                         fs->fmt = f;
946                         fs->flags = flags;
947                         fs->mode = mode;
948                         if (orig_fn) {
949                                 fs->realfilename = ast_strdup(orig_fn);
950                                 fs->filename = ast_strdup(fn);
951                         } else {
952                                 fs->realfilename = NULL;
953                                 fs->filename = ast_strdup(filename);
954                         }
955                         fs->vfs = NULL;
956                         /* If truncated, we'll be at the beginning; if not truncated, then append */
957                         f->seek(fs, 0, SEEK_END);
958                 } else if (errno != EEXIST) {
959                         ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
960                         if (orig_fn)
961                                 unlink(orig_fn);
962                 }
963                 /* if buf != NULL then fn is already free and pointing to it */
964                 if (!buf)
965                         ast_free(fn);
966         }
967
968         AST_RWLIST_UNLOCK(&formats);
969
970         if (!format_found)
971                 ast_log(LOG_WARNING, "No such format '%s'\n", type);
972
973         return fs;
974 }
975
976 /*!
977  * \brief the core of all waitstream() functions
978  */
979 static int waitstream_core(struct ast_channel *c, const char *breakon,
980         const char *forward, const char *rewind, int skip_ms,
981         int audiofd, int cmdfd,  const char *context)
982 {
983         if (!breakon)
984                 breakon = "";
985         if (!forward)
986                 forward = "";
987         if (!rewind)
988                 rewind = "";
989
990         /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
991         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
992         
993         while (c->stream) {
994                 int res;
995                 int ms = ast_sched_wait(c->sched);
996                 if (ms < 0 && !c->timingfunc) {
997                         ast_stopstream(c);
998                         break;
999                 }
1000                 if (ms < 0)
1001                         ms = 1000;
1002                 if (cmdfd < 0) {
1003                         res = ast_waitfor(c, ms);
1004                         if (res < 0) {
1005                                 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1006                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1007                                 return res;
1008                         }
1009                 } else {
1010                         int outfd;
1011                         struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1012                         if (!rchan && (outfd < 0) && (ms)) {
1013                                 /* Continue */
1014                                 if (errno == EINTR)
1015                                         continue;
1016                                 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1017                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1018                                 return -1;
1019                         } else if (outfd > -1) { /* this requires cmdfd set */
1020                                 /* The FD we were watching has something waiting */
1021                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1022                                 return 1;
1023                         }
1024                         /* if rchan is set, it is 'c' */
1025                         res = rchan ? 1 : 0; /* map into 'res' values */
1026                 }
1027                 if (res > 0) {
1028                         struct ast_frame *fr = ast_read(c);
1029                         if (!fr) {
1030                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1031                                 return -1;
1032                         }
1033                         switch (fr->frametype) {
1034                         case AST_FRAME_DTMF_END:
1035                                 if (context) {
1036                                         const char exten[2] = { fr->subclass, '\0' };
1037                                         if (ast_exists_extension(c, context, exten, 1, c->cid.cid_num)) {
1038                                                 res = fr->subclass;
1039                                                 ast_frfree(fr);
1040                                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1041                                                 return res;
1042                                         }
1043                                 } else {
1044                                         res = fr->subclass;
1045                                         if (strchr(forward,res)) {
1046                                                 ast_stream_fastforward(c->stream, skip_ms);
1047                                         } else if (strchr(rewind,res)) {
1048                                                 ast_stream_rewind(c->stream, skip_ms);
1049                                         } else if (strchr(breakon, res)) {
1050                                                 ast_frfree(fr);
1051                                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1052                                                 return res;
1053                                         }                                       
1054                                 }
1055                                 break;
1056                         case AST_FRAME_CONTROL:
1057                                 switch (fr->subclass) {
1058                                 case AST_CONTROL_HANGUP:
1059                                 case AST_CONTROL_BUSY:
1060                                 case AST_CONTROL_CONGESTION:
1061                                         ast_frfree(fr);
1062                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1063                                         return -1;
1064                                 case AST_CONTROL_RINGING:
1065                                 case AST_CONTROL_ANSWER:
1066                                 case AST_CONTROL_VIDUPDATE:
1067                                 case AST_CONTROL_HOLD:
1068                                 case AST_CONTROL_UNHOLD:
1069                                         /* Unimportant */
1070                                         break;
1071                                 default:
1072                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass);
1073                                 }
1074                                 break;
1075                         case AST_FRAME_VOICE:
1076                                 /* Write audio if appropriate */
1077                                 if (audiofd > -1)
1078                                         write(audiofd, fr->data, fr->datalen);
1079                         default:
1080                                 /* Ignore all others */
1081                                 break;
1082                         }
1083                         ast_frfree(fr);
1084                 }
1085                 ast_sched_runq(c->sched);
1086         }
1087
1088         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1089
1090         return (c->_softhangup ? -1 : 0);
1091 }
1092
1093 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *rewind, int ms)
1094 {
1095         return waitstream_core(c, breakon, forward, rewind, ms,
1096                 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */);
1097 }
1098
1099 int ast_waitstream(struct ast_channel *c, const char *breakon)
1100 {
1101         return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL);
1102 }
1103
1104 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1105 {
1106         return waitstream_core(c, breakon, NULL, NULL, 0,
1107                 audiofd, cmdfd, NULL /* no context */);
1108 }
1109
1110 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1111 {
1112         /* Waitstream, with return in the case of a valid 1 digit extension */
1113         /* in the current or specified context being pressed */
1114
1115         if (!context)
1116                 context = c->context;
1117         return waitstream_core(c, NULL, NULL, NULL, 0,
1118                 -1, -1, context);
1119 }
1120
1121 /*
1122  * if the file name is non-empty, try to play it.
1123  * Return 0 if success, -1 if error, digit if interrupted by a digit.
1124  * If digits == "" then we can simply check for non-zero.
1125  */
1126 int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
1127 {
1128         int res = 0;
1129         if (!ast_strlen_zero(file)) {
1130                 res = ast_streamfile(chan, file, chan->language);
1131                 if (!res)
1132                         res = ast_waitstream(chan, digits);
1133         }
1134         return res;
1135
1136
1137 static int show_file_formats(int fd, int argc, char *argv[])
1138 {
1139 #define FORMAT "%-10s %-10s %-20s\n"
1140 #define FORMAT2 "%-10s %-10s %-20s\n"
1141         struct ast_format *f;
1142         int count_fmt = 0;
1143
1144         if (argc != 4)
1145                 return RESULT_SHOWUSAGE;
1146         ast_cli(fd, FORMAT, "Format", "Name", "Extensions");
1147
1148         AST_RWLIST_RDLOCK(&formats);
1149         AST_RWLIST_TRAVERSE(&formats, f, list) {
1150                 ast_cli(fd, FORMAT2, ast_getformatname(f->format), f->name, f->exts);
1151                 count_fmt++;
1152         }
1153         AST_RWLIST_UNLOCK(&formats);
1154         ast_cli(fd, "%d file formats registered.\n", count_fmt);
1155         return RESULT_SUCCESS;
1156 #undef FORMAT
1157 #undef FORMAT2
1158 }
1159
1160 static const char show_file_formats_usage[] = 
1161 "Usage: core show file formats\n"
1162 "       Displays currently registered file formats (if any)\n";
1163
1164 struct ast_cli_entry cli_file[] = {
1165         { { "core", "show", "file", "formats" },
1166         show_file_formats, "Displays file formats",
1167         show_file_formats_usage },
1168 };
1169
1170 int ast_file_init(void)
1171 {
1172         ast_cli_register_multiple(cli_file, sizeof(cli_file) / sizeof(struct ast_cli_entry));
1173         return 0;
1174 }