fix channel walking problems from recent changes (bug #4494)
[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         struct timeval started, ended;
412         long elapsed = 0,last_elapsed =0;
413         char *breaks=NULL;
414         char *end=NULL;
415         int blen=2;
416         int res=0;
417
418         if (stop)
419                 blen += strlen(stop);
420         if (pause)
421                 blen += strlen(pause);
422
423         if (blen > 2) {
424                 breaks = alloca(blen + 1);
425                 breaks[0] = '\0';
426                 strcat(breaks, stop);
427                 strcat(breaks, pause);
428         }
429         if (chan->_state != AST_STATE_UP)
430                 res = ast_answer(chan);
431
432         if (chan)
433                 ast_stopstream(chan);
434
435
436         if (file) {
437                 if ((end = strchr(file,':'))) {
438                         if (!strcasecmp(end, ":end")) {
439                                 *end = '\0';
440                                 end++;
441                         }
442                 }
443         }
444
445         for (;;) {
446                 gettimeofday(&started,NULL);
447
448                 if (chan)
449                         ast_stopstream(chan);
450                 res = ast_streamfile(chan, file, chan->language);
451                 if (!res) {
452                         if (end) {
453                                 ast_seekstream(chan->stream, 0, SEEK_END);
454                                 end=NULL;
455                         }
456                         res = 1;
457                         if (elapsed) {
458                                 ast_stream_fastforward(chan->stream, elapsed);
459                                 last_elapsed = elapsed - 200;
460                         }
461                         if (res)
462                                 res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
463                         else
464                                 break;
465                 }
466
467                 if (res < 1)
468                         break;
469
470                 if (pause != NULL && strchr(pause, res)) {
471                         gettimeofday(&ended, NULL);
472                         elapsed = (((ended.tv_sec * 1000) + ended.tv_usec / 1000) - ((started.tv_sec * 1000) + started.tv_usec / 1000) + last_elapsed);
473                         for(;;) {
474                                 if (chan)
475                                         ast_stopstream(chan);
476                                 res = ast_waitfordigit(chan, 1000);
477                                 if (res == 0)
478                                         continue;
479                                 else if (res == -1 || strchr(pause, res) || (stop && strchr(stop, res)))
480                                         break;
481                         }
482                         if (res == *pause) {
483                                 res = 0;
484                                 continue;
485                         }
486                 }
487                 if (res == -1)
488                         break;
489
490                 /* if we get one of our stop chars, return it to the calling function */
491                 if (stop && strchr(stop, res)) {
492                         /* res = 0; */
493                         break;
494                 }
495         }
496         if (chan)
497                 ast_stopstream(chan);
498
499         return res;
500 }
501
502 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
503 {
504         int d;
505         d = ast_streamfile(chan, fn, chan->language);
506         if (d)
507                 return d;
508         d = ast_waitstream(chan, AST_DIGIT_ANY);
509         ast_stopstream(chan);
510         return d;
511 }
512
513 static int global_silence_threshold = 128;
514 static int global_maxsilence = 0;
515
516 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)
517 {
518         int d;
519         char *fmts;
520         char comment[256];
521         int x, fmtcnt=1, res=-1,outmsg=0;
522         struct ast_frame *f;
523         struct ast_filestream *others[MAX_OTHER_FORMATS];
524         char *sfmt[MAX_OTHER_FORMATS];
525         char *stringp=NULL;
526         time_t start, end;
527         struct ast_dsp *sildet=NULL;    /* silence detector dsp */
528         int totalsilence = 0;
529         int dspsilence = 0;
530         int gotsilence = 0;             /* did we timeout for silence? */
531         int rfmt=0;
532
533         if (silencethreshold < 0)
534                 silencethreshold = global_silence_threshold;
535
536         if (maxsilence < 0)
537                 maxsilence = global_maxsilence;
538
539         /* barf if no pointer passed to store duration in */
540         if (duration == NULL) {
541                 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
542                 return -1;
543         }
544
545         ast_log(LOG_DEBUG,"play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
546         snprintf(comment,sizeof(comment),"Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, chan->name);
547
548         if (playfile) {
549                 d = ast_play_and_wait(chan, playfile);
550                 if (d > -1)
551                         d = ast_streamfile(chan, "beep",chan->language);
552                 if (!d)
553                         d = ast_waitstream(chan,"");
554                 if (d < 0)
555                         return -1;
556         }
557
558         fmts = ast_strdupa(fmt);
559
560         stringp=fmts;
561         strsep(&stringp, "|");
562         ast_log(LOG_DEBUG,"Recording Formats: sfmts=%s\n", fmts);
563         sfmt[0] = ast_strdupa(fmts);
564
565         while((fmt = strsep(&stringp, "|"))) {
566                 if (fmtcnt > MAX_OTHER_FORMATS - 1) {
567                         ast_log(LOG_WARNING, "Please increase MAX_OTHER_FORMATS in app_voicemail.c\n");
568                         break;
569                 }
570                 sfmt[fmtcnt++] = ast_strdupa(fmt);
571         }
572
573         time(&start);
574         end=start;  /* pre-initialize end to be same as start in case we never get into loop */
575         for (x=0;x<fmtcnt;x++) {
576                 others[x] = ast_writefile(recordfile, sfmt[x], comment, O_TRUNC, 0, 0700);
577                 ast_verbose( VERBOSE_PREFIX_3 "x=%d, open writing:  %s format: %s, %p\n", x, recordfile, sfmt[x], others[x]);
578
579                 if (!others[x]) {
580                         break;
581                 }
582         }
583
584         if (path)
585                 ast_unlock_path(path);
586
587
588         
589         if (maxsilence > 0) {
590                 sildet = ast_dsp_new(); /* Create the silence detector */
591                 if (!sildet) {
592                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
593                         return -1;
594                 }
595                 ast_dsp_set_threshold(sildet, silencethreshold);
596                 rfmt = chan->readformat;
597                 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
598                 if (res < 0) {
599                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
600                         ast_dsp_free(sildet);
601                         return -1;
602                 }
603         }
604
605         if (x == fmtcnt) {
606         /* Loop forever, writing the packets we read to the writer(s), until
607            we read a # or get a hangup */
608                 f = NULL;
609                 for(;;) {
610                         res = ast_waitfor(chan, 2000);
611                         if (!res) {
612                                 ast_log(LOG_DEBUG, "One waitfor failed, trying another\n");
613                                 /* Try one more time in case of masq */
614                                 res = ast_waitfor(chan, 2000);
615                                 if (!res) {
616                                         ast_log(LOG_WARNING, "No audio available on %s??\n", chan->name);
617                                         res = -1;
618                                 }
619                         }
620
621                         if (res < 0) {
622                                 f = NULL;
623                                 break;
624                         }
625                         f = ast_read(chan);
626                         if (!f)
627                                 break;
628                         if (f->frametype == AST_FRAME_VOICE) {
629                                 /* write each format */
630                                 for (x=0;x<fmtcnt;x++) {
631                                         res = ast_writestream(others[x], f);
632                                 }
633
634                                 /* Silence Detection */
635                                 if (maxsilence > 0) {
636                                         dspsilence = 0;
637                                         ast_dsp_silence(sildet, f, &dspsilence);
638                                         if (dspsilence)
639                                                 totalsilence = dspsilence;
640                                         else
641                                                 totalsilence = 0;
642
643                                         if (totalsilence > maxsilence) {
644                                                 /* Ended happily with silence */
645                                                 if (option_verbose > 2)
646                                                         ast_verbose( VERBOSE_PREFIX_3 "Recording automatically stopped after a silence of %d seconds\n", totalsilence/1000);
647                                                 ast_frfree(f);
648                                                 gotsilence = 1;
649                                                 outmsg=2;
650                                                 break;
651                                         }
652                                 }
653                                 /* Exit on any error */
654                                 if (res) {
655                                         ast_log(LOG_WARNING, "Error writing frame\n");
656                                         ast_frfree(f);
657                                         break;
658                                 }
659                         } else if (f->frametype == AST_FRAME_VIDEO) {
660                                 /* Write only once */
661                                 ast_writestream(others[0], f);
662                         } else if (f->frametype == AST_FRAME_DTMF) {
663                                 if (f->subclass == '#') {
664                                         if (option_verbose > 2)
665                                                 ast_verbose( VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
666                                         res = '#';
667                                         outmsg = 2;
668                                         ast_frfree(f);
669                                         break;
670                                 }
671                         }
672                                 if (f->subclass == '0') {
673                                 /* Check for a '0' during message recording also, in case caller wants operator */
674                                         if (option_verbose > 2)
675                                                 ast_verbose(VERBOSE_PREFIX_3 "User cancelled by pressing %c\n", f->subclass);
676                                         res = '0';
677                                         outmsg = 0;
678                                         ast_frfree(f);
679                                         break;
680                                 }
681                         if (maxtime) {
682                                 time(&end);
683                                 if (maxtime < (end - start)) {
684                                         if (option_verbose > 2)
685                                                 ast_verbose( VERBOSE_PREFIX_3 "Took too long, cutting it short...\n");
686                                         outmsg = 2;
687                                         res = 't';
688                                         ast_frfree(f);
689                                         break;
690                                 }
691                         }
692                         ast_frfree(f);
693                 }
694                 if (end == start) time(&end);
695                 if (!f) {
696                         if (option_verbose > 2)
697                                 ast_verbose( VERBOSE_PREFIX_3 "User hung up\n");
698                         res = -1;
699                         outmsg=1;
700                 }
701         } else {
702                 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
703         }
704
705         *duration = end - start;
706
707         for (x=0;x<fmtcnt;x++) {
708                 if (!others[x])
709                         break;
710                 if (res > 0) {
711                         if (totalsilence)
712                                 ast_stream_rewind(others[x], totalsilence-200);
713                         else
714                                 ast_stream_rewind(others[x], 200);
715                 }
716                 ast_truncstream(others[x]);
717                 ast_closestream(others[x]);
718         }
719         if (rfmt) {
720                 if (ast_set_read_format(chan, rfmt)) {
721                         ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(rfmt), chan->name);
722                 }
723         }
724         if (outmsg > 1) {
725                 /* Let them know recording is stopped */
726                 if(!ast_streamfile(chan, "auth-thankyou", chan->language))
727                         ast_waitstream(chan, "");
728         }
729         if (sildet)
730                 ast_dsp_free(sildet);
731         return res;
732 }
733
734 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)
735 {
736         int d = 0;
737         char *fmts;
738         char comment[256];
739         int x, fmtcnt=1, res=-1,outmsg=0;
740         struct ast_frame *f;
741         struct ast_filestream *others[MAX_OTHER_FORMATS];
742         struct ast_filestream *realfiles[MAX_OTHER_FORMATS];
743         char *sfmt[MAX_OTHER_FORMATS];
744         char *stringp=NULL;
745         time_t start, end;
746         struct ast_dsp *sildet;         /* silence detector dsp */
747         int totalsilence = 0;
748         int dspsilence = 0;
749         int gotsilence = 0;             /* did we timeout for silence? */
750         int rfmt=0;     
751         char prependfile[80];
752         
753         if (silencethreshold < 0)
754                 silencethreshold = global_silence_threshold;
755
756         if (maxsilence < 0)
757                 maxsilence = global_maxsilence;
758
759         /* barf if no pointer passed to store duration in */
760         if (duration == NULL) {
761                 ast_log(LOG_WARNING, "Error play_and_prepend called without duration pointer\n");
762                 return -1;
763         }
764
765         ast_log(LOG_DEBUG,"play_and_prepend: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
766         snprintf(comment,sizeof(comment),"Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, chan->name);
767
768         if (playfile || beep) { 
769                 if (!beep)
770                         d = ast_play_and_wait(chan, playfile);
771                 if (d > -1)
772                         d = ast_streamfile(chan, "beep",chan->language);
773                 if (!d)
774                         d = ast_waitstream(chan,"");
775                 if (d < 0)
776                         return -1;
777         }
778         ast_copy_string(prependfile, recordfile, sizeof(prependfile));  
779         strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
780                         
781         fmts = ast_strdupa(fmt);
782         
783         stringp=fmts;
784         strsep(&stringp, "|");
785         ast_log(LOG_DEBUG,"Recording Formats: sfmts=%s\n", fmts);       
786         sfmt[0] = ast_strdupa(fmts);
787         
788         while((fmt = strsep(&stringp, "|"))) {
789                 if (fmtcnt > MAX_OTHER_FORMATS - 1) {
790                         ast_log(LOG_WARNING, "Please increase MAX_OTHER_FORMATS in app_voicemail.c\n");
791                         break;
792                 }
793                 sfmt[fmtcnt++] = ast_strdupa(fmt);
794         }
795
796         time(&start);
797         end=start;  /* pre-initialize end to be same as start in case we never get into loop */
798         for (x=0;x<fmtcnt;x++) {
799                 others[x] = ast_writefile(prependfile, sfmt[x], comment, O_TRUNC, 0, 0700);
800                 ast_verbose( VERBOSE_PREFIX_3 "x=%d, open writing:  %s format: %s, %p\n", x, prependfile, sfmt[x], others[x]);
801                 if (!others[x]) {
802                         break;
803                 }
804         }
805         
806         sildet = ast_dsp_new(); /* Create the silence detector */
807         if (!sildet) {
808                 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
809                 return -1;
810         }
811         ast_dsp_set_threshold(sildet, silencethreshold);
812
813         if (maxsilence > 0) {
814                 rfmt = chan->readformat;
815                 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
816                 if (res < 0) {
817                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
818                         return -1;
819                 }
820         }
821                                                 
822         if (x == fmtcnt) {
823         /* Loop forever, writing the packets we read to the writer(s), until
824            we read a # or get a hangup */
825                 f = NULL;
826                 for(;;) {
827                         res = ast_waitfor(chan, 2000);
828                         if (!res) {
829                                 ast_log(LOG_DEBUG, "One waitfor failed, trying another\n");
830                                 /* Try one more time in case of masq */
831                                 res = ast_waitfor(chan, 2000);
832                                 if (!res) {
833                                         ast_log(LOG_WARNING, "No audio available on %s??\n", chan->name);
834                                         res = -1;
835                                 }
836                         }
837                         
838                         if (res < 0) {
839                                 f = NULL;
840                                 break;
841                         }
842                         f = ast_read(chan);
843                         if (!f)
844                                 break;
845                         if (f->frametype == AST_FRAME_VOICE) {
846                                 /* write each format */
847                                 for (x=0;x<fmtcnt;x++) {
848                                         if (!others[x])
849                                                 break;
850                                         res = ast_writestream(others[x], f);
851                                 }
852                                 
853                                 /* Silence Detection */
854                                 if (maxsilence > 0) {
855                                         dspsilence = 0;
856                                         ast_dsp_silence(sildet, f, &dspsilence);
857                                         if (dspsilence)
858                                                 totalsilence = dspsilence;
859                                         else
860                                                 totalsilence = 0;
861                                         
862                                         if (totalsilence > maxsilence) {
863                                         /* Ended happily with silence */
864                                         if (option_verbose > 2) 
865                                                 ast_verbose( VERBOSE_PREFIX_3 "Recording automatically stopped after a silence of %d seconds\n", totalsilence/1000);
866                                         ast_frfree(f);
867                                         gotsilence = 1;
868                                         outmsg=2;
869                                         break;
870                                         }
871                                 }
872                                 /* Exit on any error */
873                                 if (res) {
874                                         ast_log(LOG_WARNING, "Error writing frame\n");
875                                         ast_frfree(f);
876                                         break;
877                                 }
878                         } else if (f->frametype == AST_FRAME_VIDEO) {
879                                 /* Write only once */
880                                 ast_writestream(others[0], f);
881                         } else if (f->frametype == AST_FRAME_DTMF) {
882                                 /* stop recording with any digit */
883                                 if (option_verbose > 2) 
884                                         ast_verbose( VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
885                                 res = 't';
886                                 outmsg = 2;
887                                 ast_frfree(f);
888                                 break;
889                         }
890                         if (maxtime) {
891                                 time(&end);
892                                 if (maxtime < (end - start)) {
893                                         if (option_verbose > 2)
894                                                 ast_verbose( VERBOSE_PREFIX_3 "Took too long, cutting it short...\n");
895                                         res = 't';
896                                         outmsg=2;
897                                         ast_frfree(f);
898                                         break;
899                                 }
900                         }
901                         ast_frfree(f);
902                 }
903                 if (end == start) time(&end);
904                 if (!f) {
905                         if (option_verbose > 2) 
906                                 ast_verbose( VERBOSE_PREFIX_3 "User hung up\n");
907                         res = -1;
908                         outmsg=1;
909 #if 0
910                         /* delete all the prepend files */
911                         for (x=0;x<fmtcnt;x++) {
912                                 if (!others[x])
913                                         break;
914                                 ast_closestream(others[x]);
915                                 ast_filedelete(prependfile, sfmt[x]);
916                         }
917 #endif
918                 }
919         } else {
920                 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", prependfile, sfmt[x]); 
921         }
922         *duration = end - start;
923 #if 0
924         if (outmsg > 1) {
925 #else
926         if (outmsg) {
927 #endif
928                 struct ast_frame *fr;
929                 for (x=0;x<fmtcnt;x++) {
930                         snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
931                         realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
932                         if (!others[x] || !realfiles[x])
933                                 break;
934                         if (totalsilence)
935                                 ast_stream_rewind(others[x], totalsilence-200);
936                         else
937                                 ast_stream_rewind(others[x], 200);
938                         ast_truncstream(others[x]);
939                         /* add the original file too */
940                         while ((fr = ast_readframe(realfiles[x]))) {
941                                 ast_writestream(others[x],fr);
942                         }
943                         ast_closestream(others[x]);
944                         ast_closestream(realfiles[x]);
945                         ast_filerename(prependfile, recordfile, sfmt[x]);
946 #if 0
947                         ast_verbose("Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x],prependfile,recordfile);
948 #endif
949                         ast_filedelete(prependfile, sfmt[x]);
950                 }
951         }
952         if (rfmt) {
953                 if (ast_set_read_format(chan, rfmt)) {
954                         ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(rfmt), chan->name);
955                 }
956         }
957         if (outmsg) {
958                 if (outmsg > 1) {
959                         /* Let them know it worked */
960                         ast_streamfile(chan, "auth-thankyou", chan->language);
961                         ast_waitstream(chan, "");
962                 }
963         }       
964         return res;
965 }
966
967 /* Channel group core functions */
968
969 int ast_app_group_split_group(char *data, char *group, int group_max, char *category, int category_max)
970 {
971         int res=0;
972         char tmp[256] = "";
973         char *grp=NULL, *cat=NULL;
974
975         if (data && !ast_strlen_zero(data)) {
976                 ast_copy_string(tmp, data, sizeof(tmp));
977                 grp = tmp;
978                 cat = strchr(tmp, '@');
979                 if (cat) {
980                         *cat = '\0';
981                         cat++;
982                 }
983         }
984
985         if (grp && !ast_strlen_zero(grp))
986                 ast_copy_string(group, grp, group_max);
987         else
988                 res = -1;
989
990         if (cat)
991                 snprintf(category, category_max, "%s_%s", GROUP_CATEGORY_PREFIX, cat);
992         else
993                 ast_copy_string(category, GROUP_CATEGORY_PREFIX, category_max);
994
995         return res;
996 }
997
998 int ast_app_group_set_channel(struct ast_channel *chan, char *data)
999 {
1000         int res=0;
1001         char group[80] = "";
1002         char category[80] = "";
1003
1004         if (!ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
1005                 pbx_builtin_setvar_helper(chan, category, group);
1006         } else
1007                 res = -1;
1008
1009         return res;
1010 }
1011
1012 int ast_app_group_get_count(char *group, char *category)
1013 {
1014         struct ast_channel *chan;
1015         int count = 0;
1016         char *test;
1017         char cat[80] = "";
1018         char *s;
1019
1020         if (group == NULL || ast_strlen_zero(group))
1021                 return 0;
1022
1023         s = (category && !ast_strlen_zero(category)) ? category : GROUP_CATEGORY_PREFIX;
1024         ast_copy_string(cat, s, sizeof(cat));
1025
1026         chan = NULL;
1027         while ((chan = ast_channel_walk_locked(chan)) != NULL) {
1028                 test = pbx_builtin_getvar_helper(chan, cat);
1029                 if (test && !strcasecmp(test, group))
1030                         count++;
1031                 ast_mutex_unlock(&chan->lock);
1032         }
1033
1034         return count;
1035 }
1036
1037 int ast_app_group_match_get_count(char *groupmatch, char *category)
1038 {
1039         regex_t regexbuf;
1040         struct ast_channel *chan;
1041         int count = 0;
1042         char *test;
1043         char cat[80] = "";
1044         char *s;
1045
1046         if (!groupmatch || ast_strlen_zero(groupmatch))
1047                 return 0;
1048
1049         /* if regex compilation fails, return zero matches */
1050         if (regcomp(&regexbuf, groupmatch, REG_EXTENDED | REG_NOSUB))
1051                 return 0;
1052
1053         s = (category && !ast_strlen_zero(category)) ? category : GROUP_CATEGORY_PREFIX;
1054         ast_copy_string(cat, s, sizeof(cat));
1055
1056         chan = NULL;
1057         while ((chan = ast_channel_walk_locked(chan)) != NULL) {
1058                 test = pbx_builtin_getvar_helper(chan, cat);
1059                 if (test && !regexec(&regexbuf, test, 0, NULL, 0))
1060                         count++;
1061                 ast_mutex_unlock(&chan->lock);
1062         }
1063
1064         regfree(&regexbuf);
1065
1066         return count;
1067 }
1068
1069 int ast_separate_app_args(char *buf, char delim, char **array, int arraylen)
1070 {
1071         int x;
1072         char *scan;
1073         char delims[2];
1074
1075         if (!buf || !array || !arraylen)
1076                 return 0;
1077
1078         memset(array, 0, arraylen * sizeof(*array));
1079
1080         scan = buf;
1081         delims[0] = delim;
1082         delims[1] = '\0';
1083         x = 0;
1084
1085         while (x < arraylen - 1) {
1086                 array[x] = strsep(&scan, delims);
1087                 x++;
1088                 if (!scan)
1089                         break;
1090         }
1091
1092         if (scan)
1093                 array[x++] = scan;
1094
1095         return x;
1096 }
1097
1098 int ast_lock_path(const char *path)
1099 {
1100         char *s;
1101         char *fs;
1102         int res;
1103         int fd;
1104         time_t start;
1105         s = alloca(strlen(path) + 10);
1106         fs = alloca(strlen(path) + 20);
1107         if (!fs || !s) {
1108                 ast_log(LOG_WARNING, "Out of memory!\n");
1109                 return -1;
1110         }
1111         snprintf(fs, strlen(path) + 19, "%s/%s-%08x", path, ".lock", rand());
1112         fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, 0600);
1113         if (fd < 0) {
1114                 fprintf(stderr, "Unable to create lock file: %s\n", strerror(errno));
1115                 return -1;
1116         }
1117         close(fd);
1118         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1119         time(&start);
1120         while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5))
1121                 usleep(1);
1122         if (res < 0) {
1123                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
1124         }
1125         unlink(fs);
1126         ast_log(LOG_DEBUG, "Locked path '%s'\n", path);
1127         return res;
1128 }
1129
1130 int ast_unlock_path(const char *path)
1131 {
1132         char *s;
1133         s = alloca(strlen(path) + 10);
1134         if (!s)
1135                 return -1;
1136         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1137         ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
1138         return unlink(s);
1139 }
1140
1141 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path) 
1142 {
1143         int silencethreshold = 128; 
1144         int maxsilence=0;
1145         int res = 0;
1146         int cmd = 0;
1147         int max_attempts = 3;
1148         int attempts = 0;
1149         int recorded = 0;
1150         int message_exists = 0;
1151         /* Note that urgent and private are for flagging messages as such in the future */
1152
1153         /* barf if no pointer passed to store duration in */
1154         if (duration == NULL) {
1155                 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1156                 return -1;
1157         }
1158
1159         cmd = '3';       /* Want to start by recording */
1160
1161         while ((cmd >= 0) && (cmd != 't')) {
1162                 switch (cmd) {
1163                 case '1':
1164                         if (!message_exists) {
1165                                 /* In this case, 1 is to record a message */
1166                                 cmd = '3';
1167                                 break;
1168                         } else {
1169                                 ast_streamfile(chan, "vm-msgsaved", chan->language);
1170                                 ast_waitstream(chan, "");
1171                                 cmd = 't';
1172                                 return res;
1173                         }
1174                 case '2':
1175                         /* Review */
1176                         ast_verbose(VERBOSE_PREFIX_3 "Reviewing the recording\n");
1177                         ast_streamfile(chan, recordfile, chan->language);
1178                         cmd = ast_waitstream(chan, AST_DIGIT_ANY);
1179                         break;
1180                 case '3':
1181                         message_exists = 0;
1182                         /* Record */
1183                         if (recorded == 1)
1184                                 ast_verbose(VERBOSE_PREFIX_3 "Re-recording\n");
1185                         else    
1186                                 ast_verbose(VERBOSE_PREFIX_3 "Recording\n");
1187                         recorded = 1;
1188                         cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path);
1189                         if (cmd == -1) {
1190                         /* User has hung up, no options to give */
1191                                 return cmd;
1192                         }
1193                         if (cmd == '0') {
1194                                 break;
1195                         } else if (cmd == '*') {
1196                                 break;
1197                         } 
1198                         else {
1199                                 /* If all is well, a message exists */
1200                                 message_exists = 1;
1201                                 cmd = 0;
1202                         }
1203                         break;
1204                 case '4':
1205                 case '5':
1206                 case '6':
1207                 case '7':
1208                 case '8':
1209                 case '9':
1210                 case '*':
1211                 case '#':
1212                         cmd = ast_play_and_wait(chan, "vm-sorry");
1213                         break;
1214                 default:
1215                         if (message_exists) {
1216                                 cmd = ast_play_and_wait(chan, "vm-review");
1217                         }
1218                         else {
1219                                 cmd = ast_play_and_wait(chan, "vm-torerecord");
1220                                 if (!cmd)
1221                                         cmd = ast_waitfordigit(chan, 600);
1222                         }
1223                         
1224                         if (!cmd)
1225                                 cmd = ast_waitfordigit(chan, 6000);
1226                         if (!cmd) {
1227                                 attempts++;
1228                         }
1229                         if (attempts > max_attempts) {
1230                                 cmd = 't';
1231                         }
1232                 }
1233         }
1234         if (cmd == 't')
1235                 cmd = 0;
1236         return cmd;
1237 }
1238
1239 #define RES_UPONE (1 << 16)
1240 #define RES_EXIT  (1 << 17)
1241 #define RES_REPEAT (1 << 18)
1242 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1243
1244 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1245 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1246 {
1247         int res;
1248         int (*ivr_func)(struct ast_channel *, void *);
1249         char *c;
1250         char *n;
1251         
1252         switch(option->action) {
1253         case AST_ACTION_UPONE:
1254                 return RES_UPONE;
1255         case AST_ACTION_EXIT:
1256                 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1257         case AST_ACTION_REPEAT:
1258                 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1259         case AST_ACTION_RESTART:
1260                 return RES_RESTART ;
1261         case AST_ACTION_NOOP:
1262                 return 0;
1263         case AST_ACTION_BACKGROUND:
1264                 res = ast_streamfile(chan, (char *)option->adata, chan->language);
1265                 if (!res) {
1266                         res = ast_waitstream(chan, AST_DIGIT_ANY);
1267                 } else {
1268                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1269                         res = 0;
1270                 }
1271                 return res;
1272         case AST_ACTION_PLAYBACK:
1273                 res = ast_streamfile(chan, (char *)option->adata, chan->language);
1274                 if (!res) {
1275                         res = ast_waitstream(chan, "");
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_MENU:
1282                 res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata);
1283                 /* Do not pass entry errors back up, treaat ast though ti was an "UPONE" */
1284                 if (res == -2)
1285                         res = 0;
1286                 return res;
1287         case AST_ACTION_WAITOPTION:
1288                 res = ast_waitfordigit(chan, 1000 * (chan->pbx ? chan->pbx->rtimeout : 10));
1289                 if (!res)
1290                         return 't';
1291                 return res;
1292         case AST_ACTION_CALLBACK:
1293                 ivr_func = option->adata;
1294                 res = ivr_func(chan, cbdata);
1295                 return res;
1296         case AST_ACTION_TRANSFER:
1297                 res = ast_parseable_goto(chan, option->adata);
1298                 return 0;
1299         case AST_ACTION_PLAYLIST:
1300         case AST_ACTION_BACKLIST:
1301                 res = 0;
1302                 c = ast_strdupa(option->adata);
1303                 if (c) {
1304                         while((n = strsep(&c, ";")))
1305                                 if ((res = ast_streamfile(chan, n, chan->language)) || (res = ast_waitstream(chan, (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : "")))
1306                                         break;
1307                         ast_stopstream(chan);
1308                 }
1309                 return res;
1310         default:
1311                 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1312                 return 0;
1313         };
1314         return -1;
1315 }
1316
1317 static int option_exists(struct ast_ivr_menu *menu, char *option)
1318 {
1319         int x;
1320         for (x=0;menu->options[x].option;x++)
1321                 if (!strcasecmp(menu->options[x].option, option))
1322                         return x;
1323         return -1;
1324 }
1325
1326 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1327 {
1328         int x;
1329         for (x=0;menu->options[x].option;x++)
1330                 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) && 
1331                                 (menu->options[x].option[strlen(option)]))
1332                         return x;
1333         return -1;
1334 }
1335
1336 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1337 {
1338         int res=0;
1339         int ms;
1340         while(option_matchmore(menu, exten)) {
1341                 ms = chan->pbx ? chan->pbx->dtimeout : 5000;
1342                 if (strlen(exten) >= maxexten - 1) 
1343                         break;
1344                 res = ast_waitfordigit(chan, ms);
1345                 if (res < 1)
1346                         break;
1347                 exten[strlen(exten) + 1] = '\0';
1348                 exten[strlen(exten)] = res;
1349         }
1350         return res > 0 ? 0 : res;
1351 }
1352
1353 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1354 {
1355         /* Execute an IVR menu structure */
1356         int res=0;
1357         int pos = 0;
1358         int retries = 0;
1359         char exten[AST_MAX_EXTENSION] = "s";
1360         if (option_exists(menu, "s") < 0) {
1361                 strcpy(exten, "g");
1362                 if (option_exists(menu, "g") < 0) {
1363                         ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1364                         return -1;
1365                 }
1366         }
1367         while(!res) {
1368                 while(menu->options[pos].option) {
1369                         if (!strcasecmp(menu->options[pos].option, exten)) {
1370                                 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1371                                 ast_log(LOG_DEBUG, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1372                                 if (res < 0)
1373                                         break;
1374                                 else if (res & RES_UPONE)
1375                                         return 0;
1376                                 else if (res & RES_EXIT)
1377                                         return res;
1378                                 else if (res & RES_REPEAT) {
1379                                         int maxretries = res & 0xffff;
1380                                         if ((res & RES_RESTART) == RES_RESTART) {
1381                                                 retries = 0;
1382                                         } else
1383                                                 retries++;
1384                                         if (!maxretries)
1385                                                 maxretries = 3;
1386                                         if ((maxretries > 0) && (retries >= maxretries)) {
1387                                                 ast_log(LOG_DEBUG, "Max retries %d exceeded\n", maxretries);
1388                                                 return -2;
1389                                         } else {
1390                                                 if (option_exists(menu, "g") > -1) 
1391                                                         strcpy(exten, "g");
1392                                                 else if (option_exists(menu, "s") > -1)
1393                                                         strcpy(exten, "s");
1394                                         }
1395                                         pos=0;
1396                                         continue;
1397                                 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1398                                         ast_log(LOG_DEBUG, "Got start of extension, %c\n", res);
1399                                         exten[1] = '\0';
1400                                         exten[0] = res;
1401                                         if ((res = read_newoption(chan, menu, exten, sizeof(exten))))
1402                                                 break;
1403                                         if (option_exists(menu, exten) < 0) {
1404                                                 if (option_exists(menu, "i")) {
1405                                                         ast_log(LOG_DEBUG, "Invalid extension entered, going to 'i'!\n");
1406                                                         strcpy(exten, "i");
1407                                                         pos = 0;
1408                                                         continue;
1409                                                 } else {
1410                                                         ast_log(LOG_DEBUG, "Aborting on invalid entry, with no 'i' option!\n");
1411                                                         res = -2;
1412                                                         break;
1413                                                 }
1414                                         } else {
1415                                                 ast_log(LOG_DEBUG, "New existing extension: %s\n", exten);
1416                                                 pos = 0;
1417                                                 continue;
1418                                         }
1419                                 }
1420                         }
1421                         pos++;
1422                 }
1423                 ast_log(LOG_DEBUG, "Stopping option '%s', res is %d\n", exten, res);
1424                 pos = 0;
1425                 if (!strcasecmp(exten, "s"))
1426                         strcpy(exten, "g");
1427                 else
1428                         break;
1429         }
1430         return res;
1431 }
1432
1433 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1434 {
1435         int res;
1436         res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1437         /* Hide internal coding */
1438         if (res > 0)
1439                 res = 0;
1440         return res;
1441 }
1442         
1443 char *ast_read_textfile(const char *filename)
1444 {
1445         int fd;
1446         char *output=NULL;
1447         struct stat filesize;
1448         int count=0;
1449         int res;
1450         if(stat(filename,&filesize)== -1){
1451                 ast_log(LOG_WARNING,"Error can't stat %s\n", filename);
1452                 return NULL;
1453         }
1454         count=filesize.st_size + 1;
1455         fd = open(filename, O_RDONLY);
1456         if (fd < 0) {
1457                 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1458                 return NULL;
1459         }
1460         output=(char *)malloc(count);
1461         if (output) {
1462                 res = read(fd, output, count - 1);
1463                 if (res == count - 1) {
1464                         output[res] = '\0';
1465                 } else {
1466                         ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count -  1, strerror(errno));
1467                         free(output);
1468                         output = NULL;
1469                 }
1470         } else 
1471                 ast_log(LOG_WARNING, "Out of memory!\n");
1472         close(fd);
1473         return output;
1474 }
1475
1476 int ast_parseoptions(const struct ast_option *options, struct ast_flags *flags, char **args, char *optstr)
1477 {
1478         char *s;
1479         int curarg;
1480         int argloc;
1481         char *arg;
1482         int res = 0;
1483         flags->flags = 0;
1484         if (!optstr)
1485                 return 0;
1486         s = optstr;
1487         while(*s) {
1488                 curarg = *s & 0x7f;
1489                 flags->flags |= options[curarg].flag;
1490                 argloc = options[curarg].argoption;
1491                 s++;
1492                 if (*s == '(') {
1493                         /* Has argument */
1494                         s++;
1495                         arg = s;
1496                         while(*s && (*s != ')')) s++;
1497                         if (*s) {
1498                                 if (argloc)
1499                                         args[argloc - 1] = arg;
1500                                 *s = '\0';
1501                                 s++;
1502                         } else {
1503                                 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c'\n", curarg);
1504                                 res = -1;
1505                         }
1506                 } else if (argloc)
1507                         args[argloc - 1] = NULL;
1508         }
1509         return res;
1510 }
1511