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