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