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