silly people that don't want to install/run autoconf :-)
[asterisk/asterisk.git] / app.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, 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 Convenient Application Routines
22  *
23  * \author Mark Spencer <markster@digium.com> 
24  */
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/time.h>
30 #include <signal.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <dirent.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <regex.h>
37
38 #include "asterisk.h"
39
40 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41
42 #include "asterisk/channel.h"
43 #include "asterisk/pbx.h"
44 #include "asterisk/file.h"
45 #include "asterisk/app.h"
46 #include "asterisk/dsp.h"
47 #include "asterisk/logger.h"
48 #include "asterisk/options.h"
49 #include "asterisk/utils.h"
50 #include "asterisk/lock.h"
51 #include "asterisk/indications.h"
52
53 #define MAX_OTHER_FORMATS 10
54
55
56 /* !
57 This function presents a dialtone and reads an extension into 'collect' 
58 which must be a pointer to a **pre-initialized** array of char having a 
59 size of 'size' suitable for writing to.  It will collect no more than the smaller 
60 of 'maxlen' or 'size' minus the original strlen() of collect digits.
61 \return 0 if extension does not exist, 1 if extension exists
62 */
63 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout) 
64 {
65         struct tone_zone_sound *ts;
66         int res=0, x=0;
67
68         if(maxlen > size)
69                 maxlen = size;
70         
71         if(!timeout && chan->pbx)
72                 timeout = chan->pbx->dtimeout;
73         else if(!timeout)
74                 timeout = 5;
75         
76         ts = ast_get_indication_tone(chan->zone,"dial");
77         if (ts && ts->data[0])
78                 res = ast_playtones_start(chan, 0, ts->data, 0);
79         else 
80                 ast_log(LOG_NOTICE,"Huh....? no dial for indications?\n");
81         
82         for (x = strlen(collect); x < maxlen; ) {
83                 res = ast_waitfordigit(chan, timeout);
84                 if (!ast_ignore_pattern(context, collect))
85                         ast_playtones_stop(chan);
86                 if (res < 1)
87                         break;
88                 collect[x++] = res;
89                 if (!ast_matchmore_extension(chan, context, collect, 1, chan->cid.cid_num)) {
90                         if (collect[x-1] == '#') {
91                                 /* Not a valid extension, ending in #, assume the # was to finish dialing */
92                                 collect[x-1] = '\0';
93                         }
94                         break;
95                 }
96         }
97         if (res >= 0)
98                 res = ast_exists_extension(chan, context, collect, 1, chan->cid.cid_num) ? 1 : 0;
99         return res;
100 }
101
102
103
104 /*! \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for 
105    "ludicrous time" (essentially never times out) */
106 int ast_app_getdata(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout)
107 {
108         int res,to,fto;
109         /* XXX Merge with full version? XXX */
110         if (maxlen)
111                 s[0] = '\0';
112         if (prompt) {
113                 res = ast_streamfile(c, prompt, c->language);
114                 if (res < 0)
115                         return res;
116         }
117         fto = c->pbx ? c->pbx->rtimeout * 1000 : 6000;
118         to = c->pbx ? c->pbx->dtimeout * 1000 : 2000;
119
120         if (timeout > 0) 
121                 fto = to = timeout;
122         if (timeout < 0) 
123                 fto = to = 1000000000;
124         res = ast_readstring(c, s, maxlen, to, fto, "#");
125         return res;
126 }
127
128
129 int ast_app_getdata_full(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
130 {
131         int res,to,fto;
132         if (prompt) {
133                 res = ast_streamfile(c, prompt, c->language);
134                 if (res < 0)
135                         return res;
136         }
137         fto = 6000;
138         to = 2000;
139         if (timeout > 0) 
140                 fto = to = timeout;
141         if (timeout < 0) 
142                 fto = to = 1000000000;
143         res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
144         return res;
145 }
146
147 int ast_app_getvoice(struct ast_channel *c, char *dest, char *dstfmt, char *prompt, int silence, int maxsec)
148 {
149         int res;
150         struct ast_filestream *writer;
151         int rfmt;
152         int totalms=0, total;
153         
154         struct ast_frame *f;
155         struct ast_dsp *sildet;
156         /* Play prompt if requested */
157         if (prompt) {
158                 res = ast_stream_and_wait(c, prompt, c->language, "");
159                 if (res < 0)
160                         return res;
161         }
162         rfmt = c->readformat;
163         res = ast_set_read_format(c, AST_FORMAT_SLINEAR);
164         if (res < 0) {
165                 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
166                 return -1;
167         }
168         sildet = ast_dsp_new();
169         if (!sildet) {
170                 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
171                 return -1;
172         }
173         writer = ast_writefile(dest, dstfmt, "Voice file", 0, 0, 0666);
174         if (!writer) {
175                 ast_log(LOG_WARNING, "Unable to open file '%s' in format '%s' for writing\n", dest, dstfmt);
176                 ast_dsp_free(sildet);
177                 return -1;
178         }
179         for(;;) {
180                 if ((res = ast_waitfor(c, 2000)) < 0) {
181                         ast_log(LOG_NOTICE, "Waitfor failed while recording file '%s' format '%s'\n", dest, dstfmt);
182                         break;
183                 }
184                 if (res) {
185                         f = ast_read(c);
186                         if (!f) {
187                                 ast_log(LOG_NOTICE, "Hungup while recording file '%s' format '%s'\n", dest, dstfmt);
188                                 break;
189                         }
190                         if ((f->frametype == AST_FRAME_DTMF) && (f->subclass == '#')) {
191                                 /* Ended happily with DTMF */
192                                 ast_frfree(f);
193                                 break;
194                         } else if (f->frametype == AST_FRAME_VOICE) {
195                                 ast_dsp_silence(sildet, f, &total); 
196                                 if (total > silence) {
197                                         /* Ended happily with silence */
198                                         ast_frfree(f);
199                                         break;
200                                 }
201                                 totalms += f->samples / 8;
202                                 if (totalms > maxsec * 1000) {
203                                         /* Ended happily with too much stuff */
204                                         ast_log(LOG_NOTICE, "Constraining voice on '%s' to %d seconds\n", c->name, maxsec);
205                                         ast_frfree(f);
206                                         break;
207                                 }
208                                 res = ast_writestream(writer, f);
209                                 if (res < 0) {
210                                         ast_log(LOG_WARNING, "Failed to write to stream at %s!\n", dest);
211                                         ast_frfree(f);
212                                         break;
213                                 }
214                                         
215                         }
216                         ast_frfree(f);
217                 }
218         }
219         res = ast_set_read_format(c, rfmt);
220         if (res)
221                 ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", c->name);
222         ast_dsp_free(sildet);
223         ast_closestream(writer);
224         return 0;
225 }
226
227 static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
228 static int (*ast_messagecount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
229
230 void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
231                               int (*messagecount_func)(const char *mailbox, int *newmsgs, int *oldmsgs))
232 {
233         ast_has_voicemail_func = has_voicemail_func;
234         ast_messagecount_func = messagecount_func;
235 }
236
237 void ast_uninstall_vm_functions(void)
238 {
239         ast_has_voicemail_func = NULL;
240         ast_messagecount_func = NULL;
241 }
242
243 int ast_app_has_voicemail(const char *mailbox, const char *folder)
244 {
245         static int warned = 0;
246         if (ast_has_voicemail_func)
247                 return ast_has_voicemail_func(mailbox, folder);
248
249         if ((option_verbose > 2) && !warned) {
250                 ast_verbose(VERBOSE_PREFIX_3 "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
251                 warned++;
252         }
253         return 0;
254 }
255
256
257 int ast_app_messagecount(const char *mailbox, int *newmsgs, int *oldmsgs)
258 {
259         static int warned = 0;
260         if (newmsgs)
261                 *newmsgs = 0;
262         if (oldmsgs)
263                 *oldmsgs = 0;
264         if (ast_messagecount_func)
265                 return ast_messagecount_func(mailbox, newmsgs, oldmsgs);
266
267         if (!warned && (option_verbose > 2)) {
268                 warned++;
269                 ast_verbose(VERBOSE_PREFIX_3 "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
270         }
271
272         return 0;
273 }
274
275 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between) 
276 {
277         const char *ptr;
278         int res = 0;
279         struct ast_frame f = {
280                 .frametype = AST_FRAME_DTMF,
281                 .src = "ast_dtmf_stream"
282         };
283
284         if (!between)
285                 between = 100;
286
287         if (peer)
288                 res = ast_autoservice_start(peer);
289
290         if (!res)
291                 res = ast_waitfor(chan, 100);
292
293         /* ast_waitfor will return the number of remaining ms on success */
294         if (res < 0)
295                 return res;
296
297         for (ptr = digits; *ptr; ptr++) {
298                 if (*ptr == 'w') {
299                         /* 'w' -- wait half a second */
300                         if ((res = ast_safe_sleep(chan, 500)))
301                                 break;
302                 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
303                         /* Character represents valid DTMF */
304                         if (*ptr == 'f' || *ptr == 'F') {
305                                 /* ignore return values if not supported by channel */
306                                 ast_indicate(chan, AST_CONTROL_FLASH);
307                         } else {
308                                 f.subclass = *ptr;
309                                 if ((res = ast_write(chan, &f)))
310                                         break;
311                         }
312                         /* pause between digits */
313                         if ((res = ast_safe_sleep(chan, between)))
314                                 break;
315                 } else
316                         ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n",*ptr);
317         }
318
319         if (peer) {
320                 /* Stop autoservice on the peer channel, but don't overwrite any error condition 
321                    that has occurred previously while acting on the primary channel */
322                 if (ast_autoservice_stop(peer) && !res)
323                         res = -1;
324         }
325
326         return res;
327 }
328
329 struct linear_state {
330         int fd;
331         int autoclose;
332         int allowoverride;
333         int origwfmt;
334 };
335
336 static void linear_release(struct ast_channel *chan, void *params)
337 {
338         struct linear_state *ls = params;
339         if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt)) {
340                 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", chan->name, ls->origwfmt);
341         }
342         if (ls->autoclose)
343                 close(ls->fd);
344         free(params);
345 }
346
347 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
348 {
349         struct ast_frame f;
350         short buf[2048 + AST_FRIENDLY_OFFSET / 2];
351         struct linear_state *ls = data;
352         int res;
353         len = samples * 2;
354         if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
355                 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" ,len);
356                 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
357         }
358         memset(&f, 0, sizeof(f));
359         res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
360         if (res > 0) {
361                 f.frametype = AST_FRAME_VOICE;
362                 f.subclass = AST_FORMAT_SLINEAR;
363                 f.data = buf + AST_FRIENDLY_OFFSET/2;
364                 f.datalen = res;
365                 f.samples = res / 2;
366                 f.offset = AST_FRIENDLY_OFFSET;
367                 ast_write(chan, &f);
368                 if (res == len)
369                         return 0;
370         }
371         return -1;
372 }
373
374 static void *linear_alloc(struct ast_channel *chan, void *params)
375 {
376         struct linear_state *ls;
377         /* In this case, params is already malloc'd */
378         if (params) {
379                 ls = params;
380                 if (ls->allowoverride)
381                         ast_set_flag(chan, AST_FLAG_WRITE_INT);
382                 else
383                         ast_clear_flag(chan, AST_FLAG_WRITE_INT);
384                 ls->origwfmt = chan->writeformat;
385                 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
386                         ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", chan->name);
387                         free(ls);
388                         ls = params = NULL;
389                 }
390         }
391         return params;
392 }
393
394 static struct ast_generator linearstream = 
395 {
396         alloc: linear_alloc,
397         release: linear_release,
398         generate: linear_generator,
399 };
400
401 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
402 {
403         struct linear_state *lin;
404         char tmpf[256];
405         int res = -1;
406         int autoclose = 0;
407         if (fd < 0) {
408                 if (ast_strlen_zero(filename))
409                         return -1;
410                 autoclose = 1;
411                 if (filename[0] == '/') 
412                         ast_copy_string(tmpf, filename, sizeof(tmpf));
413                 else
414                         snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", (char *)ast_config_AST_DATA_DIR, "sounds", filename);
415                 fd = open(tmpf, O_RDONLY);
416                 if (fd < 0){
417                         ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
418                         return -1;
419                 }
420         }
421         if ((lin = ast_calloc(1, sizeof(*lin)))) {
422                 lin->fd = fd;
423                 lin->allowoverride = allowoverride;
424                 lin->autoclose = autoclose;
425                 res = ast_activate_generator(chan, &linearstream, lin);
426         }
427         return res;
428 }
429
430 int ast_control_streamfile(struct ast_channel *chan, const char *file,
431                            const char *fwd, const char *rev,
432                            const char *stop, const char *pause,
433                            const char *restart, int skipms) 
434 {
435         char *breaks = NULL;
436         char *end = NULL;
437         int blen = 2;
438         int res;
439         long pause_restart_point = 0;
440
441         if (stop)
442                 blen += strlen(stop);
443         if (pause)
444                 blen += strlen(pause);
445         if (restart)
446                 blen += strlen(restart);
447
448         if (blen > 2) {
449                 breaks = alloca(blen + 1);
450                 breaks[0] = '\0';
451                 if (stop)
452                         strcat(breaks, stop);
453                 if (pause)
454                         strcat(breaks, pause);
455                 if (restart)
456                         strcat(breaks, restart);
457         }
458         if (chan->_state != AST_STATE_UP)
459                 res = ast_answer(chan);
460
461         if (file) {
462                 if ((end = strchr(file,':'))) {
463                         if (!strcasecmp(end, ":end")) {
464                                 *end = '\0';
465                                 end++;
466                         }
467                 }
468         }
469
470         for (;;) {
471                 ast_stopstream(chan);
472                 res = ast_streamfile(chan, file, chan->language);
473                 if (!res) {
474                         if (pause_restart_point) {
475                                 ast_seekstream(chan->stream, pause_restart_point, SEEK_SET);
476                                 pause_restart_point = 0;
477                         }
478                         else if (end) {
479                                 ast_seekstream(chan->stream, 0, SEEK_END);
480                                 end = NULL;
481                         };
482                         res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
483                 }
484
485                 if (res < 1)
486                         break;
487
488                 /* We go at next loop if we got the restart char */
489                 if (restart && strchr(restart, res)) {
490                         ast_log(LOG_DEBUG, "we'll restart the stream here at next loop\n");
491                         pause_restart_point = 0;
492                         continue;
493                 }
494
495                 if (pause && strchr(pause, res)) {
496                         pause_restart_point = ast_tellstream(chan->stream);
497                         for (;;) {
498                                 ast_stopstream(chan);
499                                 res = ast_waitfordigit(chan, 1000);
500                                 if (!res)
501                                         continue;
502                                 else if (res == -1 || strchr(pause, res) || (stop && strchr(stop, res)))
503                                         break;
504                         }
505                         if (res == *pause) {
506                                 res = 0;
507                                 continue;
508                         }
509                 }
510
511                 if (res == -1)
512                         break;
513
514                 /* if we get one of our stop chars, return it to the calling function */
515                 if (stop && strchr(stop, res))
516                         break;
517         }
518
519         ast_stopstream(chan);
520
521         return res;
522 }
523
524 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
525 {
526         int d;
527         d = ast_streamfile(chan, fn, chan->language);
528         if (d)
529                 return d;
530         d = ast_waitstream(chan, AST_DIGIT_ANY);
531         ast_stopstream(chan);
532         return d;
533 }
534
535 static int global_silence_threshold = 128;
536 static int global_maxsilence = 0;
537
538 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
539  * @param chan Channel to playback to/record from.
540  * @param playfile Filename of sound to play before recording begins.
541  * @param recordfile Filename to record to.
542  * @param maxtime Maximum length of recording (in milliseconds).
543  * @param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
544  * @param duration Where to store actual length of the recorded message (in milliseconds).
545  * @param beep Whether to play a beep before starting to record.
546  * @param silencethreshold 
547  * @param maxsilence Length of silence that will end a recording (in milliseconds).
548  * @param path Optional filesystem path to unlock.
549  * @param prepend If true, prepend the recorded audio to an existing file.
550  * @param acceptdtmf DTMF digits that will end the recording.
551  * @param canceldtmf DTMF digits that will cancel the recording.
552  */
553
554 static int __ast_play_and_record(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int beep, int silencethreshold, int maxsilence, const char *path, int prepend, const char *acceptdtmf, const char *canceldtmf)
555 {
556         int d = 0;
557         char *fmts;
558         char comment[256];
559         int x, fmtcnt = 1, res = -1, outmsg = 0;
560         struct ast_filestream *others[MAX_OTHER_FORMATS];
561         char *sfmt[MAX_OTHER_FORMATS];
562         char *stringp = NULL;
563         time_t start, end;
564         struct ast_dsp *sildet = NULL;   /* silence detector dsp */
565         int totalsilence = 0;
566         int rfmt = 0;
567         struct ast_silence_generator *silgen = NULL;
568         char prependfile[80];
569
570         if (silencethreshold < 0)
571                 silencethreshold = global_silence_threshold;
572
573         if (maxsilence < 0)
574                 maxsilence = global_maxsilence;
575
576         /* barf if no pointer passed to store duration in */
577         if (duration == NULL) {
578                 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
579                 return -1;
580         }
581
582         ast_log(LOG_DEBUG,"play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
583         snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, chan->name);
584
585         if (playfile || beep) {
586                 if (!beep)
587                         d = ast_play_and_wait(chan, playfile);
588                 if (d > -1)
589                         d = ast_stream_and_wait(chan, "beep", chan->language, "");
590                 if (d < 0)
591                         return -1;
592         }
593
594         if (prepend) {
595                 ast_copy_string(prependfile, recordfile, sizeof(prependfile));  
596                 strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
597         }
598
599         fmts = ast_strdupa(fmt);
600
601         stringp = fmts;
602         strsep(&stringp, "|");
603         ast_log(LOG_DEBUG,"Recording Formats: sfmts=%s\n", fmts);
604         sfmt[0] = ast_strdupa(fmts);
605
606         while((fmt = strsep(&stringp, "|"))) {
607                 if (fmtcnt > MAX_OTHER_FORMATS - 1) {
608                         ast_log(LOG_WARNING, "Please increase MAX_OTHER_FORMATS in app.c\n");
609                         break;
610                 }
611                 sfmt[fmtcnt++] = ast_strdupa(fmt);
612         }
613
614         time(&start);
615         end = start;  /* pre-initialize end to be same as start in case we never get into loop */
616         for (x = 0; x < fmtcnt; x++) {
617                 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, 0700);
618                 if (option_verbose > 2)
619                         ast_verbose(VERBOSE_PREFIX_3 "x=%d, open writing:  %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
620
621                 if (!others[x]) {
622                         break;
623                 }
624         }
625
626         if (path)
627                 ast_unlock_path(path);
628
629         if (maxsilence > 0) {
630                 sildet = ast_dsp_new(); /* Create the silence detector */
631                 if (!sildet) {
632                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
633                         return -1;
634                 }
635                 ast_dsp_set_threshold(sildet, silencethreshold);
636                 rfmt = chan->readformat;
637                 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
638                 if (res < 0) {
639                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
640                         ast_dsp_free(sildet);
641                         return -1;
642                 }
643         }
644
645         if (!prepend) {
646                 /* Request a video update */
647                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
648
649                 if (ast_opt_transmit_silence)
650                         silgen = ast_channel_start_silence_generator(chan);
651         }
652
653         if (x == fmtcnt) {
654                 /* Loop forever, writing the packets we read to the writer(s), until
655                    we read a digit or get a hangup */
656                 struct ast_frame *f;
657                 for (;;) {
658                         res = ast_waitfor(chan, 2000);
659                         if (!res) {
660                                 ast_log(LOG_DEBUG, "One waitfor failed, trying another\n");
661                                 /* Try one more time in case of masq */
662                                 res = ast_waitfor(chan, 2000);
663                                 if (!res) {
664                                         ast_log(LOG_WARNING, "No audio available on %s??\n", chan->name);
665                                         res = -1;
666                                 }
667                         }
668
669                         if (res < 0) {
670                                 f = NULL;
671                                 break;
672                         }
673                         f = ast_read(chan);
674                         if (!f)
675                                 break;
676                         if (f->frametype == AST_FRAME_VOICE) {
677                                 /* write each format */
678                                 for (x = 0; x < fmtcnt; x++) {
679                                         if (prepend && !others[x])
680                                                 break;
681                                         res = ast_writestream(others[x], f);
682                                 }
683
684                                 /* Silence Detection */
685                                 if (maxsilence > 0) {
686                                         int dspsilence = 0;
687                                         ast_dsp_silence(sildet, f, &dspsilence);
688                                         if (dspsilence)
689                                                 totalsilence = dspsilence;
690                                         else
691                                                 totalsilence = 0;
692
693                                         if (totalsilence > maxsilence) {
694                                                 /* Ended happily with silence */
695                                                 if (option_verbose > 2)
696                                                         ast_verbose( VERBOSE_PREFIX_3 "Recording automatically stopped after a silence of %d seconds\n", totalsilence/1000);
697                                                 res = 'S';
698                                                 outmsg = 2;
699                                                 break;
700                                         }
701                                 }
702                                 /* Exit on any error */
703                                 if (res) {
704                                         ast_log(LOG_WARNING, "Error writing frame\n");
705                                         break;
706                                 }
707                         } else if (f->frametype == AST_FRAME_VIDEO) {
708                                 /* Write only once */
709                                 ast_writestream(others[0], f);
710                         } else if (f->frametype == AST_FRAME_DTMF) {
711                                 if (prepend) {
712                                 /* stop recording with any digit */
713                                         if (option_verbose > 2) 
714                                                 ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
715                                         res = 't';
716                                         outmsg = 2;
717                                         break;
718                                 }
719                                 if (strchr(acceptdtmf, f->subclass)) {
720                                         if (option_verbose > 2)
721                                                 ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
722                                         res = f->subclass;
723                                         outmsg = 2;
724                                         break;
725                                 }
726                                 if (strchr(canceldtmf, f->subclass)) {
727                                         if (option_verbose > 2)
728                                                 ast_verbose(VERBOSE_PREFIX_3 "User cancelled message by pressing %c\n", f->subclass);
729                                         res = f->subclass;
730                                         outmsg = 0;
731                                         break;
732                                 }
733                         }
734                         if (maxtime) {
735                                 time(&end);
736                                 if (maxtime < (end - start)) {
737                                         if (option_verbose > 2)
738                                                 ast_verbose(VERBOSE_PREFIX_3 "Took too long, cutting it short...\n");
739                                         res = 't';
740                                         outmsg = 2;
741                                         break;
742                                 }
743                         }
744                         ast_frfree(f);
745                 }
746                 if (!f) {
747                         if (option_verbose > 2)
748                                 ast_verbose(VERBOSE_PREFIX_3 "User hung up\n");
749                         res = -1;
750                         outmsg = 1;
751                 } else {
752                         ast_frfree(f);
753                 }
754                 if (end == start) time(&end);
755         } else {
756                 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
757         }
758
759         if (!prepend) {
760                 if (silgen)
761                         ast_channel_stop_silence_generator(chan, silgen);
762         }
763         *duration = end - start;
764
765         if (!prepend) {
766                 for (x = 0; x < fmtcnt; x++) {
767                         if (!others[x])
768                                 break;
769                         if (res > 0)
770                                 ast_stream_rewind(others[x], totalsilence ? totalsilence-200 : 200);
771                         ast_truncstream(others[x]);
772                         ast_closestream(others[x]);
773                 }
774         }
775
776         if (prepend && outmsg) {
777                 struct ast_filestream *realfiles[MAX_OTHER_FORMATS];
778                 struct ast_frame *fr;
779
780                 for (x = 0; x < fmtcnt; x++) {
781                         snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
782                         realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
783                         if (!others[x] || !realfiles[x])
784                                 break;
785                         ast_stream_rewind(others[x], totalsilence ? totalsilence-200 : 200);
786                         ast_truncstream(others[x]);
787                         /* add the original file too */
788                         while ((fr = ast_readframe(realfiles[x]))) {
789                                 ast_writestream(others[x], fr);
790                                 ast_frfree(fr);
791                         }
792                         ast_closestream(others[x]);
793                         ast_closestream(realfiles[x]);
794                         ast_filerename(prependfile, recordfile, sfmt[x]);
795                         if (option_verbose > 3)
796                                 ast_verbose(VERBOSE_PREFIX_4 "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
797                         ast_filedelete(prependfile, sfmt[x]);
798                 }
799         }
800         if (rfmt && ast_set_read_format(chan, rfmt)) {
801                 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(rfmt), chan->name);
802         }
803         if (outmsg == 2) {
804                 ast_stream_and_wait(chan, "auth-thankyou", chan->language, "");
805         }
806         if (sildet)
807                 ast_dsp_free(sildet);
808         return res;
809 }
810
811 static char default_acceptdtmf[] = "#";
812 static char default_canceldtmf[] = "";
813
814 int ast_play_and_record_full(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int silencethreshold, int maxsilence, const char *path, const char *acceptdtmf, const char *canceldtmf)
815 {
816         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, 0, silencethreshold, maxsilence, path, 0, S_OR(acceptdtmf, default_acceptdtmf), S_OR(canceldtmf, default_canceldtmf));
817 }
818
819 int ast_play_and_record(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int silencethreshold, int maxsilence, const char *path)
820 {
821         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf);
822 }
823
824 int ast_play_and_prepend(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime, char *fmt, int *duration, int beep, int silencethreshold, int maxsilence)
825 {
826         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf);
827 }
828
829 /* Channel group core functions */
830
831 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
832 {
833         int res=0;
834         char tmp[256];
835         char *grp=NULL, *cat=NULL;
836
837         if (!ast_strlen_zero(data)) {
838                 ast_copy_string(tmp, data, sizeof(tmp));
839                 grp = tmp;
840                 cat = strchr(tmp, '@');
841                 if (cat) {
842                         *cat = '\0';
843                         cat++;
844                 }
845         }
846
847         if (!ast_strlen_zero(grp))
848                 ast_copy_string(group, grp, group_max);
849         else
850                 res = -1;
851
852         if (cat)
853                 snprintf(category, category_max, "%s_%s", GROUP_CATEGORY_PREFIX, cat);
854         else
855                 ast_copy_string(category, GROUP_CATEGORY_PREFIX, category_max);
856
857         return res;
858 }
859
860 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
861 {
862         int res=0;
863         char group[80] = "";
864         char category[80] = "";
865
866         if (!ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
867                 pbx_builtin_setvar_helper(chan, category, group);
868         } else
869                 res = -1;
870
871         return res;
872 }
873
874 int ast_app_group_get_count(const char *group, const char *category)
875 {
876         struct ast_channel *chan;
877         int count = 0;
878         const char *test;
879         char cat[80];
880         const char *s;
881
882         if (ast_strlen_zero(group))
883                 return 0;
884
885         s = S_OR(category, GROUP_CATEGORY_PREFIX);
886         ast_copy_string(cat, s, sizeof(cat));
887
888         chan = NULL;
889         while ((chan = ast_channel_walk_locked(chan)) != NULL) {
890                 test = pbx_builtin_getvar_helper(chan, cat);
891                 if (test && !strcasecmp(test, group))
892                         count++;
893                 ast_channel_unlock(chan);
894         }
895
896         return count;
897 }
898
899 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
900 {
901         regex_t regexbuf;
902         struct ast_channel *chan;
903         int count = 0;
904         const char *test;
905         char cat[80];
906         const char *s;
907
908         if (ast_strlen_zero(groupmatch))
909                 return 0;
910
911         /* if regex compilation fails, return zero matches */
912         if (regcomp(&regexbuf, groupmatch, REG_EXTENDED | REG_NOSUB))
913                 return 0;
914
915         s = S_OR(category, GROUP_CATEGORY_PREFIX);
916         ast_copy_string(cat, s, sizeof(cat));
917
918         chan = NULL;
919         while ((chan = ast_channel_walk_locked(chan)) != NULL) {
920                 test = pbx_builtin_getvar_helper(chan, cat);
921                 if (test && !regexec(&regexbuf, test, 0, NULL, 0))
922                         count++;
923                 ast_channel_unlock(chan);
924         }
925
926         regfree(&regexbuf);
927
928         return count;
929 }
930
931 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
932 {
933         int argc;
934         char *scan;
935         int paren = 0, quote = 0;
936
937         if (!buf || !array || !arraylen)
938                 return 0;
939
940         memset(array, 0, arraylen * sizeof(*array));
941
942         scan = buf;
943
944         for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
945                 array[argc] = scan;
946                 for (; *scan; scan++) {
947                         if (*scan == '(')
948                                 paren++;
949                         else if (*scan == ')') {
950                                 if (paren)
951                                         paren--;
952                         } else if (*scan == '"') {
953                                 quote = quote ? 0 : 1;
954                                 /* Remove quote character from argument */
955                                 memmove(scan, scan + 1, strlen(scan));
956                                 scan--;
957                         } else if (*scan == '\\') {
958                                 /* Literal character, don't parse */
959                                 memmove(scan, scan + 1, strlen(scan));
960                         } else if ((*scan == delim) && !paren && !quote) {
961                                 *scan++ = '\0';
962                                 break;
963                         }
964                 }
965         }
966
967         if (*scan)
968                 array[argc++] = scan;
969
970         return argc;
971 }
972
973 enum AST_LOCK_RESULT ast_lock_path(const char *path)
974 {
975         char *s;
976         char *fs;
977         int res;
978         int fd;
979         int lp = strlen(path);
980         time_t start;
981
982         if (!(s = alloca(lp + 10)) || !(fs = alloca(lp + 20))) {
983                 ast_log(LOG_WARNING, "Out of memory!\n");
984                 return AST_LOCK_FAILURE;
985         }
986
987         snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
988         fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, 0600);
989         if (fd < 0) {
990                 fprintf(stderr, "Unable to create lock file '%s': %s\n", path, strerror(errno));
991                 return AST_LOCK_PATH_NOT_FOUND;
992         }
993         close(fd);
994
995         snprintf(s, strlen(path) + 9, "%s/.lock", path);
996         time(&start);
997         while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5))
998                 usleep(1);
999         if (res) {
1000                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
1001                 return AST_LOCK_TIMEOUT;
1002         } else {
1003                 unlink(fs);
1004                 ast_log(LOG_DEBUG, "Locked path '%s'\n", path);
1005                 return AST_LOCK_SUCCESS;
1006         }
1007 }
1008
1009 int ast_unlock_path(const char *path)
1010 {
1011         char *s;
1012         if (!(s = alloca(strlen(path) + 10)))
1013                 return -1;
1014         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1015         ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
1016         return unlink(s);
1017 }
1018
1019 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path) 
1020 {
1021         int silencethreshold = 128; 
1022         int maxsilence=0;
1023         int res = 0;
1024         int cmd = 0;
1025         int max_attempts = 3;
1026         int attempts = 0;
1027         int recorded = 0;
1028         int message_exists = 0;
1029         /* Note that urgent and private are for flagging messages as such in the future */
1030
1031         /* barf if no pointer passed to store duration in */
1032         if (duration == NULL) {
1033                 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1034                 return -1;
1035         }
1036
1037         cmd = '3';       /* Want to start by recording */
1038
1039         while ((cmd >= 0) && (cmd != 't')) {
1040                 switch (cmd) {
1041                 case '1':
1042                         if (!message_exists) {
1043                                 /* In this case, 1 is to record a message */
1044                                 cmd = '3';
1045                                 break;
1046                         } else {
1047                                 ast_stream_and_wait(chan, "vm-msgsaved", chan->language, "");
1048                                 cmd = 't';
1049                                 return res;
1050                         }
1051                 case '2':
1052                         /* Review */
1053                         ast_verbose(VERBOSE_PREFIX_3 "Reviewing the recording\n");
1054                         cmd = ast_stream_and_wait(chan, recordfile, chan->language, AST_DIGIT_ANY);
1055                         break;
1056                 case '3':
1057                         message_exists = 0;
1058                         /* Record */
1059                         if (recorded == 1)
1060                                 ast_verbose(VERBOSE_PREFIX_3 "Re-recording\n");
1061                         else    
1062                                 ast_verbose(VERBOSE_PREFIX_3 "Recording\n");
1063                         recorded = 1;
1064                         cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path);
1065                         if (cmd == -1) {
1066                         /* User has hung up, no options to give */
1067                                 return cmd;
1068                         }
1069                         if (cmd == '0') {
1070                                 break;
1071                         } else if (cmd == '*') {
1072                                 break;
1073                         } 
1074                         else {
1075                                 /* If all is well, a message exists */
1076                                 message_exists = 1;
1077                                 cmd = 0;
1078                         }
1079                         break;
1080                 case '4':
1081                 case '5':
1082                 case '6':
1083                 case '7':
1084                 case '8':
1085                 case '9':
1086                 case '*':
1087                 case '#':
1088                         cmd = ast_play_and_wait(chan, "vm-sorry");
1089                         break;
1090                 default:
1091                         if (message_exists) {
1092                                 cmd = ast_play_and_wait(chan, "vm-review");
1093                         }
1094                         else {
1095                                 cmd = ast_play_and_wait(chan, "vm-torerecord");
1096                                 if (!cmd)
1097                                         cmd = ast_waitfordigit(chan, 600);
1098                         }
1099                         
1100                         if (!cmd)
1101                                 cmd = ast_waitfordigit(chan, 6000);
1102                         if (!cmd) {
1103                                 attempts++;
1104                         }
1105                         if (attempts > max_attempts) {
1106                                 cmd = 't';
1107                         }
1108                 }
1109         }
1110         if (cmd == 't')
1111                 cmd = 0;
1112         return cmd;
1113 }
1114
1115 #define RES_UPONE (1 << 16)
1116 #define RES_EXIT  (1 << 17)
1117 #define RES_REPEAT (1 << 18)
1118 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1119
1120 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1121 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1122 {
1123         int res;
1124         int (*ivr_func)(struct ast_channel *, void *);
1125         char *c;
1126         char *n;
1127         
1128         switch(option->action) {
1129         case AST_ACTION_UPONE:
1130                 return RES_UPONE;
1131         case AST_ACTION_EXIT:
1132                 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1133         case AST_ACTION_REPEAT:
1134                 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1135         case AST_ACTION_RESTART:
1136                 return RES_RESTART ;
1137         case AST_ACTION_NOOP:
1138                 return 0;
1139         case AST_ACTION_BACKGROUND:
1140                 res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, AST_DIGIT_ANY);
1141                 if (res < 0) {
1142                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1143                         res = 0;
1144                 }
1145                 return res;
1146         case AST_ACTION_PLAYBACK:
1147                 res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, "");
1148                 if (res < 0) {
1149                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1150                         res = 0;
1151                 }
1152                 return res;
1153         case AST_ACTION_MENU:
1154                 res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata);
1155                 /* Do not pass entry errors back up, treaat ast though ti was an "UPONE" */
1156                 if (res == -2)
1157                         res = 0;
1158                 return res;
1159         case AST_ACTION_WAITOPTION:
1160                 res = ast_waitfordigit(chan, 1000 * (chan->pbx ? chan->pbx->rtimeout : 10));
1161                 if (!res)
1162                         return 't';
1163                 return res;
1164         case AST_ACTION_CALLBACK:
1165                 ivr_func = option->adata;
1166                 res = ivr_func(chan, cbdata);
1167                 return res;
1168         case AST_ACTION_TRANSFER:
1169                 res = ast_parseable_goto(chan, option->adata);
1170                 return 0;
1171         case AST_ACTION_PLAYLIST:
1172         case AST_ACTION_BACKLIST:
1173                 res = 0;
1174                 c = ast_strdupa(option->adata);
1175                 if (c) {
1176                         while((n = strsep(&c, ";")))
1177                                 if ((res = ast_stream_and_wait(chan, n, chan->language,
1178                                                 (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : "")))
1179                                         break;
1180                         ast_stopstream(chan);
1181                 }
1182                 return res;
1183         default:
1184                 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1185                 return 0;
1186         };
1187         return -1;
1188 }
1189
1190 static int option_exists(struct ast_ivr_menu *menu, char *option)
1191 {
1192         int x;
1193         for (x=0;menu->options[x].option;x++)
1194                 if (!strcasecmp(menu->options[x].option, option))
1195                         return x;
1196         return -1;
1197 }
1198
1199 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1200 {
1201         int x;
1202         for (x=0;menu->options[x].option;x++)
1203                 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) && 
1204                                 (menu->options[x].option[strlen(option)]))
1205                         return x;
1206         return -1;
1207 }
1208
1209 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1210 {
1211         int res=0;
1212         int ms;
1213         while(option_matchmore(menu, exten)) {
1214                 ms = chan->pbx ? chan->pbx->dtimeout : 5000;
1215                 if (strlen(exten) >= maxexten - 1) 
1216                         break;
1217                 res = ast_waitfordigit(chan, ms);
1218                 if (res < 1)
1219                         break;
1220                 exten[strlen(exten) + 1] = '\0';
1221                 exten[strlen(exten)] = res;
1222         }
1223         return res > 0 ? 0 : res;
1224 }
1225
1226 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1227 {
1228         /* Execute an IVR menu structure */
1229         int res=0;
1230         int pos = 0;
1231         int retries = 0;
1232         char exten[AST_MAX_EXTENSION] = "s";
1233         if (option_exists(menu, "s") < 0) {
1234                 strcpy(exten, "g");
1235                 if (option_exists(menu, "g") < 0) {
1236                         ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1237                         return -1;
1238                 }
1239         }
1240         while(!res) {
1241                 while(menu->options[pos].option) {
1242                         if (!strcasecmp(menu->options[pos].option, exten)) {
1243                                 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1244                                 ast_log(LOG_DEBUG, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1245                                 if (res < 0)
1246                                         break;
1247                                 else if (res & RES_UPONE)
1248                                         return 0;
1249                                 else if (res & RES_EXIT)
1250                                         return res;
1251                                 else if (res & RES_REPEAT) {
1252                                         int maxretries = res & 0xffff;
1253                                         if ((res & RES_RESTART) == RES_RESTART) {
1254                                                 retries = 0;
1255                                         } else
1256                                                 retries++;
1257                                         if (!maxretries)
1258                                                 maxretries = 3;
1259                                         if ((maxretries > 0) && (retries >= maxretries)) {
1260                                                 ast_log(LOG_DEBUG, "Max retries %d exceeded\n", maxretries);
1261                                                 return -2;
1262                                         } else {
1263                                                 if (option_exists(menu, "g") > -1) 
1264                                                         strcpy(exten, "g");
1265                                                 else if (option_exists(menu, "s") > -1)
1266                                                         strcpy(exten, "s");
1267                                         }
1268                                         pos=0;
1269                                         continue;
1270                                 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1271                                         ast_log(LOG_DEBUG, "Got start of extension, %c\n", res);
1272                                         exten[1] = '\0';
1273                                         exten[0] = res;
1274                                         if ((res = read_newoption(chan, menu, exten, sizeof(exten))))
1275                                                 break;
1276                                         if (option_exists(menu, exten) < 0) {
1277                                                 if (option_exists(menu, "i")) {
1278                                                         ast_log(LOG_DEBUG, "Invalid extension entered, going to 'i'!\n");
1279                                                         strcpy(exten, "i");
1280                                                         pos = 0;
1281                                                         continue;
1282                                                 } else {
1283                                                         ast_log(LOG_DEBUG, "Aborting on invalid entry, with no 'i' option!\n");
1284                                                         res = -2;
1285                                                         break;
1286                                                 }
1287                                         } else {
1288                                                 ast_log(LOG_DEBUG, "New existing extension: %s\n", exten);
1289                                                 pos = 0;
1290                                                 continue;
1291                                         }
1292                                 }
1293                         }
1294                         pos++;
1295                 }
1296                 ast_log(LOG_DEBUG, "Stopping option '%s', res is %d\n", exten, res);
1297                 pos = 0;
1298                 if (!strcasecmp(exten, "s"))
1299                         strcpy(exten, "g");
1300                 else
1301                         break;
1302         }
1303         return res;
1304 }
1305
1306 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1307 {
1308         int res;
1309         res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1310         /* Hide internal coding */
1311         if (res > 0)
1312                 res = 0;
1313         return res;
1314 }
1315         
1316 char *ast_read_textfile(const char *filename)
1317 {
1318         int fd;
1319         char *output=NULL;
1320         struct stat filesize;
1321         int count=0;
1322         int res;
1323         if(stat(filename,&filesize)== -1){
1324                 ast_log(LOG_WARNING,"Error can't stat %s\n", filename);
1325                 return NULL;
1326         }
1327         count=filesize.st_size + 1;
1328         fd = open(filename, O_RDONLY);
1329         if (fd < 0) {
1330                 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1331                 return NULL;
1332         }
1333         if ((output = ast_malloc(count))) {
1334                 res = read(fd, output, count - 1);
1335                 if (res == count - 1) {
1336                         output[res] = '\0';
1337                 } else {
1338                         ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count -  1, strerror(errno));
1339                         free(output);
1340                         output = NULL;
1341                 }
1342         }
1343         close(fd);
1344         return output;
1345 }
1346
1347 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
1348 {
1349         char *s;
1350         int curarg;
1351         unsigned int argloc;
1352         char *arg;
1353         int res = 0;
1354
1355         ast_clear_flag(flags, AST_FLAGS_ALL);
1356
1357         if (!optstr)
1358                 return 0;
1359
1360         s = optstr;
1361         while (*s) {
1362                 curarg = *s++ & 0x7f;   /* the array (in app.h) has 128 entries */
1363                 ast_set_flag(flags, options[curarg].flag);
1364                 argloc = options[curarg].arg_index;
1365                 if (*s == '(') {
1366                         /* Has argument */
1367                         arg = ++s;
1368                         s = strchr(s, ')');
1369                         if (*s) {
1370                                 if (argloc)
1371                                         args[argloc - 1] = arg;
1372                                 *s++ = '\0';
1373                         } else {
1374                                 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
1375                                 res = -1;
1376                         }
1377                 } else if (argloc) {
1378                         args[argloc - 1] = NULL;
1379                 }
1380         }
1381
1382         return res;
1383 }