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