866d5530ea5482a20efaa3a1c92800c2529c3b79
[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 x;
1070         char *scan;
1071         char delims[2];
1072
1073         if (!buf || !array || !arraylen)
1074                 return 0;
1075
1076         memset(array, 0, arraylen * sizeof(*array));
1077
1078         scan = buf;
1079         delims[0] = delim;
1080         delims[1] = '\0';
1081         x = 0;
1082
1083         while (x < arraylen - 1) {
1084                 array[x] = strsep(&scan, delims);
1085                 x++;
1086                 if (!scan)
1087                         break;
1088         }
1089
1090         if (scan)
1091                 array[x++] = scan;
1092
1093         return x;
1094 }
1095
1096 enum AST_LOCK_RESULT ast_lock_path(const char *path)
1097 {
1098         char *s;
1099         char *fs;
1100         int res;
1101         int fd;
1102         time_t start;
1103
1104         s = alloca(strlen(path) + 10);
1105         fs = alloca(strlen(path) + 20);
1106
1107         if (!fs || !s) {
1108                 ast_log(LOG_WARNING, "Out of memory!\n");
1109                 return AST_LOCK_FAILURE;
1110         }
1111
1112         snprintf(fs, strlen(path) + 19, "%s/.lock-%08x", path, rand());
1113         fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, 0600);
1114         if (fd < 0) {
1115                 fprintf(stderr, "Unable to create lock file '%s': %s\n", path, strerror(errno));
1116                 return AST_LOCK_PATH_NOT_FOUND;
1117         }
1118         close(fd);
1119
1120         snprintf(s, strlen(path) + 9, "%s/.lock", path);
1121         time(&start);
1122         while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5))
1123                 usleep(1);
1124         if (res) {
1125                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
1126                 return AST_LOCK_TIMEOUT;
1127         } else {
1128                 unlink(fs);
1129                 ast_log(LOG_DEBUG, "Locked path '%s'\n", path);
1130                 return AST_LOCK_SUCCESS;
1131         }
1132 }
1133
1134 int ast_unlock_path(const char *path)
1135 {
1136         char *s;
1137         s = alloca(strlen(path) + 10);
1138         if (!s)
1139                 return -1;
1140         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1141         ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
1142         return unlink(s);
1143 }
1144
1145 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path) 
1146 {
1147         int silencethreshold = 128; 
1148         int maxsilence=0;
1149         int res = 0;
1150         int cmd = 0;
1151         int max_attempts = 3;
1152         int attempts = 0;
1153         int recorded = 0;
1154         int message_exists = 0;
1155         /* Note that urgent and private are for flagging messages as such in the future */
1156
1157         /* barf if no pointer passed to store duration in */
1158         if (duration == NULL) {
1159                 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1160                 return -1;
1161         }
1162
1163         cmd = '3';       /* Want to start by recording */
1164
1165         while ((cmd >= 0) && (cmd != 't')) {
1166                 switch (cmd) {
1167                 case '1':
1168                         if (!message_exists) {
1169                                 /* In this case, 1 is to record a message */
1170                                 cmd = '3';
1171                                 break;
1172                         } else {
1173                                 ast_streamfile(chan, "vm-msgsaved", chan->language);
1174                                 ast_waitstream(chan, "");
1175                                 cmd = 't';
1176                                 return res;
1177                         }
1178                 case '2':
1179                         /* Review */
1180                         ast_verbose(VERBOSE_PREFIX_3 "Reviewing the recording\n");
1181                         ast_streamfile(chan, recordfile, chan->language);
1182                         cmd = ast_waitstream(chan, AST_DIGIT_ANY);
1183                         break;
1184                 case '3':
1185                         message_exists = 0;
1186                         /* Record */
1187                         if (recorded == 1)
1188                                 ast_verbose(VERBOSE_PREFIX_3 "Re-recording\n");
1189                         else    
1190                                 ast_verbose(VERBOSE_PREFIX_3 "Recording\n");
1191                         recorded = 1;
1192                         cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path);
1193                         if (cmd == -1) {
1194                         /* User has hung up, no options to give */
1195                                 return cmd;
1196                         }
1197                         if (cmd == '0') {
1198                                 break;
1199                         } else if (cmd == '*') {
1200                                 break;
1201                         } 
1202                         else {
1203                                 /* If all is well, a message exists */
1204                                 message_exists = 1;
1205                                 cmd = 0;
1206                         }
1207                         break;
1208                 case '4':
1209                 case '5':
1210                 case '6':
1211                 case '7':
1212                 case '8':
1213                 case '9':
1214                 case '*':
1215                 case '#':
1216                         cmd = ast_play_and_wait(chan, "vm-sorry");
1217                         break;
1218                 default:
1219                         if (message_exists) {
1220                                 cmd = ast_play_and_wait(chan, "vm-review");
1221                         }
1222                         else {
1223                                 cmd = ast_play_and_wait(chan, "vm-torerecord");
1224                                 if (!cmd)
1225                                         cmd = ast_waitfordigit(chan, 600);
1226                         }
1227                         
1228                         if (!cmd)
1229                                 cmd = ast_waitfordigit(chan, 6000);
1230                         if (!cmd) {
1231                                 attempts++;
1232                         }
1233                         if (attempts > max_attempts) {
1234                                 cmd = 't';
1235                         }
1236                 }
1237         }
1238         if (cmd == 't')
1239                 cmd = 0;
1240         return cmd;
1241 }
1242
1243 #define RES_UPONE (1 << 16)
1244 #define RES_EXIT  (1 << 17)
1245 #define RES_REPEAT (1 << 18)
1246 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1247
1248 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1249 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1250 {
1251         int res;
1252         int (*ivr_func)(struct ast_channel *, void *);
1253         char *c;
1254         char *n;
1255         
1256         switch(option->action) {
1257         case AST_ACTION_UPONE:
1258                 return RES_UPONE;
1259         case AST_ACTION_EXIT:
1260                 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1261         case AST_ACTION_REPEAT:
1262                 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1263         case AST_ACTION_RESTART:
1264                 return RES_RESTART ;
1265         case AST_ACTION_NOOP:
1266                 return 0;
1267         case AST_ACTION_BACKGROUND:
1268                 res = ast_streamfile(chan, (char *)option->adata, chan->language);
1269                 if (!res) {
1270                         res = ast_waitstream(chan, AST_DIGIT_ANY);
1271                 } else {
1272                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1273                         res = 0;
1274                 }
1275                 return res;
1276         case AST_ACTION_PLAYBACK:
1277                 res = ast_streamfile(chan, (char *)option->adata, chan->language);
1278                 if (!res) {
1279                         res = ast_waitstream(chan, "");
1280                 } else {
1281                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1282                         res = 0;
1283                 }
1284                 return res;
1285         case AST_ACTION_MENU:
1286                 res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata);
1287                 /* Do not pass entry errors back up, treaat ast though ti was an "UPONE" */
1288                 if (res == -2)
1289                         res = 0;
1290                 return res;
1291         case AST_ACTION_WAITOPTION:
1292                 res = ast_waitfordigit(chan, 1000 * (chan->pbx ? chan->pbx->rtimeout : 10));
1293                 if (!res)
1294                         return 't';
1295                 return res;
1296         case AST_ACTION_CALLBACK:
1297                 ivr_func = option->adata;
1298                 res = ivr_func(chan, cbdata);
1299                 return res;
1300         case AST_ACTION_TRANSFER:
1301                 res = ast_parseable_goto(chan, option->adata);
1302                 return 0;
1303         case AST_ACTION_PLAYLIST:
1304         case AST_ACTION_BACKLIST:
1305                 res = 0;
1306                 c = ast_strdupa(option->adata);
1307                 if (c) {
1308                         while((n = strsep(&c, ";")))
1309                                 if ((res = ast_streamfile(chan, n, chan->language)) || (res = ast_waitstream(chan, (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : "")))
1310                                         break;
1311                         ast_stopstream(chan);
1312                 }
1313                 return res;
1314         default:
1315                 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1316                 return 0;
1317         };
1318         return -1;
1319 }
1320
1321 static int option_exists(struct ast_ivr_menu *menu, char *option)
1322 {
1323         int x;
1324         for (x=0;menu->options[x].option;x++)
1325                 if (!strcasecmp(menu->options[x].option, option))
1326                         return x;
1327         return -1;
1328 }
1329
1330 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1331 {
1332         int x;
1333         for (x=0;menu->options[x].option;x++)
1334                 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) && 
1335                                 (menu->options[x].option[strlen(option)]))
1336                         return x;
1337         return -1;
1338 }
1339
1340 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1341 {
1342         int res=0;
1343         int ms;
1344         while(option_matchmore(menu, exten)) {
1345                 ms = chan->pbx ? chan->pbx->dtimeout : 5000;
1346                 if (strlen(exten) >= maxexten - 1) 
1347                         break;
1348                 res = ast_waitfordigit(chan, ms);
1349                 if (res < 1)
1350                         break;
1351                 exten[strlen(exten) + 1] = '\0';
1352                 exten[strlen(exten)] = res;
1353         }
1354         return res > 0 ? 0 : res;
1355 }
1356
1357 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1358 {
1359         /* Execute an IVR menu structure */
1360         int res=0;
1361         int pos = 0;
1362         int retries = 0;
1363         char exten[AST_MAX_EXTENSION] = "s";
1364         if (option_exists(menu, "s") < 0) {
1365                 strcpy(exten, "g");
1366                 if (option_exists(menu, "g") < 0) {
1367                         ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1368                         return -1;
1369                 }
1370         }
1371         while(!res) {
1372                 while(menu->options[pos].option) {
1373                         if (!strcasecmp(menu->options[pos].option, exten)) {
1374                                 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1375                                 ast_log(LOG_DEBUG, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1376                                 if (res < 0)
1377                                         break;
1378                                 else if (res & RES_UPONE)
1379                                         return 0;
1380                                 else if (res & RES_EXIT)
1381                                         return res;
1382                                 else if (res & RES_REPEAT) {
1383                                         int maxretries = res & 0xffff;
1384                                         if ((res & RES_RESTART) == RES_RESTART) {
1385                                                 retries = 0;
1386                                         } else
1387                                                 retries++;
1388                                         if (!maxretries)
1389                                                 maxretries = 3;
1390                                         if ((maxretries > 0) && (retries >= maxretries)) {
1391                                                 ast_log(LOG_DEBUG, "Max retries %d exceeded\n", maxretries);
1392                                                 return -2;
1393                                         } else {
1394                                                 if (option_exists(menu, "g") > -1) 
1395                                                         strcpy(exten, "g");
1396                                                 else if (option_exists(menu, "s") > -1)
1397                                                         strcpy(exten, "s");
1398                                         }
1399                                         pos=0;
1400                                         continue;
1401                                 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1402                                         ast_log(LOG_DEBUG, "Got start of extension, %c\n", res);
1403                                         exten[1] = '\0';
1404                                         exten[0] = res;
1405                                         if ((res = read_newoption(chan, menu, exten, sizeof(exten))))
1406                                                 break;
1407                                         if (option_exists(menu, exten) < 0) {
1408                                                 if (option_exists(menu, "i")) {
1409                                                         ast_log(LOG_DEBUG, "Invalid extension entered, going to 'i'!\n");
1410                                                         strcpy(exten, "i");
1411                                                         pos = 0;
1412                                                         continue;
1413                                                 } else {
1414                                                         ast_log(LOG_DEBUG, "Aborting on invalid entry, with no 'i' option!\n");
1415                                                         res = -2;
1416                                                         break;
1417                                                 }
1418                                         } else {
1419                                                 ast_log(LOG_DEBUG, "New existing extension: %s\n", exten);
1420                                                 pos = 0;
1421                                                 continue;
1422                                         }
1423                                 }
1424                         }
1425                         pos++;
1426                 }
1427                 ast_log(LOG_DEBUG, "Stopping option '%s', res is %d\n", exten, res);
1428                 pos = 0;
1429                 if (!strcasecmp(exten, "s"))
1430                         strcpy(exten, "g");
1431                 else
1432                         break;
1433         }
1434         return res;
1435 }
1436
1437 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1438 {
1439         int res;
1440         res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1441         /* Hide internal coding */
1442         if (res > 0)
1443                 res = 0;
1444         return res;
1445 }
1446         
1447 char *ast_read_textfile(const char *filename)
1448 {
1449         int fd;
1450         char *output=NULL;
1451         struct stat filesize;
1452         int count=0;
1453         int res;
1454         if(stat(filename,&filesize)== -1){
1455                 ast_log(LOG_WARNING,"Error can't stat %s\n", filename);
1456                 return NULL;
1457         }
1458         count=filesize.st_size + 1;
1459         fd = open(filename, O_RDONLY);
1460         if (fd < 0) {
1461                 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1462                 return NULL;
1463         }
1464         output=(char *)malloc(count);
1465         if (output) {
1466                 res = read(fd, output, count - 1);
1467                 if (res == count - 1) {
1468                         output[res] = '\0';
1469                 } else {
1470                         ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count -  1, strerror(errno));
1471                         free(output);
1472                         output = NULL;
1473                 }
1474         } else 
1475                 ast_log(LOG_WARNING, "Out of memory!\n");
1476         close(fd);
1477         return output;
1478 }
1479
1480 int ast_parseoptions(const struct ast_option *options, struct ast_flags *flags, char **args, char *optstr)
1481 {
1482         char *s;
1483         int curarg;
1484         int argloc;
1485         char *arg;
1486         int res = 0;
1487         flags->flags = 0;
1488         if (!optstr)
1489                 return 0;
1490         s = optstr;
1491         while(*s) {
1492                 curarg = *s & 0x7f;
1493                 flags->flags |= options[curarg].flag;
1494                 argloc = options[curarg].argoption;
1495                 s++;
1496                 if (*s == '(') {
1497                         /* Has argument */
1498                         s++;
1499                         arg = s;
1500                         while(*s && (*s != ')')) s++;
1501                         if (*s) {
1502                                 if (argloc)
1503                                         args[argloc - 1] = arg;
1504                                 *s = '\0';
1505                                 s++;
1506                         } else {
1507                                 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c'\n", curarg);
1508                                 res = -1;
1509                         }
1510                 } else if (argloc)
1511                         args[argloc - 1] = NULL;
1512         }
1513         return res;
1514 }
1515