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