07799f87c90432a810eec5f711afb4518cb44193
[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/channel.h"
27 #include "asterisk/pbx.h"
28 #include "asterisk/file.h"
29 #include "asterisk/app.h"
30 #include "asterisk/dsp.h"
31 #include "asterisk/logger.h"
32 #include "asterisk/options.h"
33 #include "asterisk/utils.h"
34 #include "asterisk/lock.h"
35 #include "asterisk/indications.h"
36 #include "asterisk.h"
37 #include "astconf.h"
38
39 #define MAX_OTHER_FORMATS 10
40
41
42 /* 
43 This function presents a dialtone and reads an extension into 'collect' 
44 which must be a pointer to a **pre-initilized** array of char having a 
45 size of 'size' suitable for writing to.  It will collect no more than the smaller 
46 of 'maxlen' or 'size' minus the original strlen() of collect digits.
47 */
48 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout) 
49 {
50         struct tone_zone_sound *ts;
51         int res=0, x=0;
52
53         if(maxlen > size)
54                 maxlen = size;
55         
56         if(!timeout && chan->pbx)
57                 timeout = chan->pbx->dtimeout;
58         else if(!timeout)
59                 timeout = 5;
60         
61         ts = ast_get_indication_tone(chan->zone,"dial");
62         if (ts && ts->data[0])
63                 res = ast_playtones_start(chan, 0, ts->data, 0);
64         else 
65                 ast_log(LOG_NOTICE,"Huh....? no dial for indications?\n");
66         
67         for (x = strlen(collect); strlen(collect) < maxlen; ) {
68                 res = ast_waitfordigit(chan, timeout);
69                 if (!ast_ignore_pattern(context, collect))
70                         ast_playtones_stop(chan);
71                 if (res < 1)
72                         break;
73                 collect[x++] = res;
74                 if (!ast_matchmore_extension(chan, context, collect, 1, chan->cid.cid_num)) {
75                         if (collect[x-1] == '#') {
76                                 /* Not a valid extension, ending in #, assume the # was to finish dialing */
77                                 collect[x-1] = '\0';
78                         }
79                         break;
80                 }
81         }
82         if (res >= 0) {
83                 if (ast_exists_extension(chan, context, collect, 1, chan->cid.cid_num))
84                         res = 1;
85                 else
86                         res = 0;
87         }
88         return res;
89 }
90
91
92
93 /* set timeout to 0 for "standard" timeouts. Set timeout to -1 for 
94    "ludicrous time" (essentially never times out) */
95 int ast_app_getdata(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout)
96 {
97         int res,to,fto;
98         /* XXX Merge with full version? XXX */
99         if (maxlen)
100                 s[0] = '\0';
101         if (prompt) {
102                 res = ast_streamfile(c, prompt, c->language);
103                 if (res < 0)
104                         return res;
105         }
106         fto = c->pbx ? c->pbx->rtimeout * 1000 : 6000;
107         to = c->pbx ? c->pbx->dtimeout * 1000 : 2000;
108
109         if (timeout > 0) 
110                 fto = to = timeout;
111         if (timeout < 0) 
112                 fto = to = 1000000000;
113         res = ast_readstring(c, s, maxlen, to, fto, "#");
114         return res;
115 }
116
117
118 int ast_app_getdata_full(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
119 {
120         int res,to,fto;
121         if (prompt) {
122                 res = ast_streamfile(c, prompt, c->language);
123                 if (res < 0)
124                         return res;
125         }
126         fto = 6000;
127         to = 2000;
128         if (timeout > 0) 
129                 fto = to = timeout;
130         if (timeout < 0) 
131                 fto = to = 1000000000;
132         res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
133         return res;
134 }
135
136 int ast_app_getvoice(struct ast_channel *c, char *dest, char *dstfmt, char *prompt, int silence, int maxsec)
137 {
138         int res;
139         struct ast_filestream *writer;
140         int rfmt;
141         int totalms=0, total;
142         
143         struct ast_frame *f;
144         struct ast_dsp *sildet;
145         /* Play prompt if requested */
146         if (prompt) {
147                 res = ast_streamfile(c, prompt, c->language);
148                 if (res < 0)
149                         return res;
150                 res = ast_waitstream(c,"");
151                 if (res < 0)
152                         return res;
153         }
154         rfmt = c->readformat;
155         res = ast_set_read_format(c, AST_FORMAT_SLINEAR);
156         if (res < 0) {
157                 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
158                 return -1;
159         }
160         sildet = ast_dsp_new();
161         if (!sildet) {
162                 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
163                 return -1;
164         }
165         writer = ast_writefile(dest, dstfmt, "Voice file", 0, 0, 0666);
166         if (!writer) {
167                 ast_log(LOG_WARNING, "Unable to open file '%s' in format '%s' for writing\n", dest, dstfmt);
168                 ast_dsp_free(sildet);
169                 return -1;
170         }
171         for(;;) {
172                 if ((res = ast_waitfor(c, 2000)) < 0) {
173                         ast_log(LOG_NOTICE, "Waitfor failed while recording file '%s' format '%s'\n", dest, dstfmt);
174                         break;
175                 }
176                 if (res) {
177                         f = ast_read(c);
178                         if (!f) {
179                                 ast_log(LOG_NOTICE, "Hungup while recording file '%s' format '%s'\n", dest, dstfmt);
180                                 break;
181                         }
182                         if ((f->frametype == AST_FRAME_DTMF) && (f->subclass == '#')) {
183                                 /* Ended happily with DTMF */
184                                 ast_frfree(f);
185                                 break;
186                         } else if (f->frametype == AST_FRAME_VOICE) {
187                                 ast_dsp_silence(sildet, f, &total); 
188                                 if (total > silence) {
189                                         /* Ended happily with silence */
190                                         ast_frfree(f);
191                                         break;
192                                 }
193                                 totalms += f->samples / 8;
194                                 if (totalms > maxsec * 1000) {
195                                         /* Ended happily with too much stuff */
196                                         ast_log(LOG_NOTICE, "Constraining voice on '%s' to %d seconds\n", c->name, maxsec);
197                                         ast_frfree(f);
198                                         break;
199                                 }
200                         }
201                         ast_frfree(f);
202                 }
203         }
204         res = ast_set_read_format(c, rfmt);
205         if (res)
206                 ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", c->name);
207         ast_dsp_free(sildet);
208         ast_closestream(writer);
209         return 0;
210 }
211
212 static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
213 static int (*ast_messagecount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
214
215 void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
216                               int (*messagecount_func)(const char *mailbox, int *newmsgs, int *oldmsgs))
217 {
218         ast_has_voicemail_func = has_voicemail_func;
219         ast_messagecount_func = messagecount_func;
220 }
221
222 void ast_uninstall_vm_functions(void)
223 {
224         ast_has_voicemail_func = NULL;
225         ast_messagecount_func = NULL;
226 }
227
228 int ast_app_has_voicemail(const char *mailbox, const char *folder)
229 {
230         static int warned = 0;
231         if (ast_has_voicemail_func)
232                 return ast_has_voicemail_func(mailbox, folder);
233
234         if ((option_verbose > 2) && !warned) {
235                 ast_verbose(VERBOSE_PREFIX_3 "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
236                 warned++;
237         }
238         return 0;
239 }
240
241
242 int ast_app_messagecount(const char *mailbox, int *newmsgs, int *oldmsgs)
243 {
244         static int warned = 0;
245         if (newmsgs)
246                 *newmsgs = 0;
247         if (oldmsgs)
248                 *oldmsgs = 0;
249         if (ast_messagecount_func)
250                 return ast_messagecount_func(mailbox, newmsgs, oldmsgs);
251
252         if (!warned && (option_verbose > 2)) {
253                 warned++;
254                 ast_verbose(VERBOSE_PREFIX_3 "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
255         }
256
257         return 0;
258 }
259
260 int ast_dtmf_stream(struct ast_channel *chan,struct ast_channel *peer,char *digits,int between) 
261 {
262         char *ptr=NULL;
263         int res=0;
264         struct ast_frame f;
265         if (!between)
266                 between = 100;
267
268         if (peer)
269                 res = ast_autoservice_start(peer);
270
271         if (!res) {
272                 res = ast_waitfor(chan,100);
273                 if (res > -1) {
274                         for (ptr=digits; *ptr; ptr++) {
275                                 if (*ptr == 'w') {
276                                         res = ast_safe_sleep(chan, 500);
277                                         if (res) 
278                                                 break;
279                                         continue;
280                                 }
281                                 memset(&f, 0, sizeof(f));
282                                 f.frametype = AST_FRAME_DTMF;
283                                 f.subclass = *ptr;
284                                 f.src = "ast_dtmf_stream";
285                                 if (strchr("0123456789*#abcdABCD",*ptr)==NULL) {
286                                         ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n",*ptr);
287                                 } else {
288                                         res = ast_write(chan, &f);
289                                         if (res) 
290                                                 break;
291                                         /* pause between digits */
292                                         res = ast_safe_sleep(chan,between);
293                                         if (res) 
294                                                 break;
295                                 }
296                         }
297                 }
298                 if (peer)
299                         res = ast_autoservice_stop(peer);
300         }
301         return res;
302 }
303
304 struct linear_state {
305         int fd;
306         int autoclose;
307         int allowoverride;
308         int origwfmt;
309 };
310
311 static void linear_release(struct ast_channel *chan, void *params)
312 {
313         struct linear_state *ls = params;
314         if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt)) {
315                 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", chan->name, ls->origwfmt);
316         }
317         if (ls->autoclose)
318                 close(ls->fd);
319         free(params);
320 }
321
322 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
323 {
324         struct ast_frame f;
325         short buf[2048 + AST_FRIENDLY_OFFSET / 2];
326         struct linear_state *ls = data;
327         int res;
328         len = samples * 2;
329         if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
330                 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" ,len);
331                 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
332         }
333         memset(&f, 0, sizeof(f));
334         res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
335         if (res > 0) {
336                 f.frametype = AST_FRAME_VOICE;
337                 f.subclass = AST_FORMAT_SLINEAR;
338                 f.data = buf + AST_FRIENDLY_OFFSET/2;
339                 f.datalen = res;
340                 f.samples = res / 2;
341                 f.offset = AST_FRIENDLY_OFFSET;
342                 ast_write(chan, &f);
343                 if (res == len)
344                         return 0;
345         }
346         return -1;
347 }
348
349 static void *linear_alloc(struct ast_channel *chan, void *params)
350 {
351         struct linear_state *ls;
352         /* In this case, params is already malloc'd */
353         if (params) {
354                 ls = params;
355                 if (ls->allowoverride)
356                         ast_set_flag(chan, AST_FLAG_WRITE_INT);
357                 else
358                         ast_clear_flag(chan, AST_FLAG_WRITE_INT);
359                 ls->origwfmt = chan->writeformat;
360                 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
361                         ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", chan->name);
362                         free(ls);
363                         ls = params = NULL;
364                 }
365         }
366         return params;
367 }
368
369 static struct ast_generator linearstream = 
370 {
371         alloc: linear_alloc,
372         release: linear_release,
373         generate: linear_generator,
374 };
375
376 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
377 {
378         struct linear_state *lin;
379         char tmpf[256] = "";
380         int res = -1;
381         int autoclose = 0;
382         if (fd < 0) {
383                 if (!filename || ast_strlen_zero(filename))
384                         return -1;
385                 autoclose = 1;
386                 if (filename[0] == '/') 
387                         strncpy(tmpf, filename, sizeof(tmpf) - 1);
388                 else
389                         snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", (char *)ast_config_AST_VAR_DIR, "sounds", filename);
390                 fd = open(tmpf, O_RDONLY);
391                 if (fd < 0){
392                         ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
393                         return -1;
394                 }
395         }
396         lin = malloc(sizeof(struct linear_state));
397         if (lin) {
398                 memset(lin, 0, sizeof(lin));
399                 lin->fd = fd;
400                 lin->allowoverride = allowoverride;
401                 lin->autoclose = autoclose;
402                 res = ast_activate_generator(chan, &linearstream, lin);
403         }
404         return res;
405 }
406
407 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) 
408 {
409         struct timeval started, ended;
410         long elapsed = 0,last_elapsed =0;
411         char *breaks=NULL;
412         char *end=NULL;
413         int blen=2;
414         int res=0;
415
416         if (stop)
417                 blen += strlen(stop);
418         if (pause)
419                 blen += strlen(pause);
420
421         if (blen > 2) {
422                 breaks = alloca(blen + 1);
423                 breaks[0] = '\0';
424                 strcat(breaks, stop);
425                 strcat(breaks, pause);
426         }
427         if (chan->_state != AST_STATE_UP)
428                 res = ast_answer(chan);
429
430         if (chan)
431                 ast_stopstream(chan);
432
433
434         if (file) {
435                 if ((end = strchr(file,':'))) {
436                         if (!strcasecmp(end, ":end")) {
437                                 *end = '\0';
438                                 end++;
439                         }
440                 }
441         }
442
443         for (;;) {
444                 gettimeofday(&started,NULL);
445
446                 if (chan)
447                         ast_stopstream(chan);
448                 res = ast_streamfile(chan, file, chan->language);
449                 if (!res) {
450                         if (end) {
451                                 ast_seekstream(chan->stream, 0, SEEK_END);
452                                 end=NULL;
453                         }
454                         res = 1;
455                         if (elapsed) {
456                                 ast_stream_fastforward(chan->stream, elapsed);
457                                 last_elapsed = elapsed - 200;
458                         }
459                         if (res)
460                                 res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
461                         else
462                                 break;
463                 }
464
465                 if (res < 1)
466                         break;
467
468                 if (pause != NULL && strchr(pause, res)) {
469                         gettimeofday(&ended, NULL);
470                         elapsed = (((ended.tv_sec * 1000) + ended.tv_usec / 1000) - ((started.tv_sec * 1000) + started.tv_usec / 1000) + 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         strncpy(prependfile, recordfile, sizeof(prependfile) -1);       
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                 strncpy(tmp, data, sizeof(tmp) - 1);
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                 strncpy(group, grp, group_max -1);
985         else
986                 res = -1;
987
988         if (cat)
989                 snprintf(category, category_max, "%s_%s", GROUP_CATEGORY_PREFIX, cat);
990         else
991                 strncpy(category, GROUP_CATEGORY_PREFIX, category_max - 1);
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
1017         if (category && !ast_strlen_zero(category)) {
1018                 strncpy(cat, category, sizeof(cat) - 1);
1019         } else {
1020                 strncpy(cat, GROUP_CATEGORY_PREFIX, sizeof(cat) - 1);
1021         }
1022
1023         if (group && !ast_strlen_zero(group)) {
1024                 chan = ast_channel_walk_locked(NULL);
1025                 while(chan) {
1026                         test = pbx_builtin_getvar_helper(chan, cat);
1027                         if (test && !strcasecmp(test, group))
1028                                 count++;
1029                         ast_mutex_unlock(&chan->lock);
1030                         chan = ast_channel_walk_locked(chan);
1031                 }
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
1045         if (!groupmatch || ast_strlen_zero(groupmatch))
1046                 return 0;
1047
1048         /* if regex compilation fails, return zero matches */
1049         if (regcomp(&regexbuf, groupmatch, REG_EXTENDED | REG_NOSUB))
1050                 return 0;
1051
1052         if (category && !ast_strlen_zero(category)) {
1053                 strncpy(cat, category, sizeof(cat) - 1);
1054         } else {
1055                 strncpy(cat, GROUP_CATEGORY_PREFIX, sizeof(cat) - 1);
1056         }
1057
1058         chan = ast_channel_walk_locked(NULL);
1059         while(chan) {
1060                 test = pbx_builtin_getvar_helper(chan, cat);
1061                 if (test && !regexec(&regexbuf, test, 0, NULL, 0))
1062                         count++;
1063                 ast_mutex_unlock(&chan->lock);
1064                 chan = ast_channel_walk_locked(chan);
1065         }
1066
1067         regfree(&regexbuf);
1068
1069         return count;
1070 }
1071
1072 int ast_separate_app_args(char *buf, char delim, char **array, int arraylen)
1073 {
1074         int x;
1075         char *scan;
1076         char delims[2];
1077
1078         if (!buf || !array || !arraylen)
1079                 return 0;
1080
1081         memset(array, 0, arraylen * sizeof(*array));
1082
1083         scan = buf;
1084         delims[0] = delim;
1085         delims[1] = '\0';
1086         x = 0;
1087
1088         while (x < arraylen - 1) {
1089                 array[x] = strsep(&scan, delims);
1090                 x++;
1091                 if (!scan)
1092                         break;
1093         }
1094
1095         if (scan)
1096                 array[x++] = scan;
1097
1098         return x;
1099 }
1100
1101 int ast_lock_path(const char *path)
1102 {
1103         char *s;
1104         char *fs;
1105         int res;
1106         int fd;
1107         time_t start;
1108         s = alloca(strlen(path) + 10);
1109         fs = alloca(strlen(path) + 20);
1110         if (!fs || !s) {
1111                 ast_log(LOG_WARNING, "Out of memory!\n");
1112                 return -1;
1113         }
1114         snprintf(fs, strlen(path) + 19, "%s/%s-%08x", path, ".lock", rand());
1115         fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, 0600);
1116         if (fd < 0) {
1117                 fprintf(stderr, "Unable to create lock file: %s\n", strerror(errno));
1118                 return -1;
1119         }
1120         close(fd);
1121         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1122         time(&start);
1123         while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5))
1124                 usleep(1);
1125         if (res < 0) {
1126                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
1127         }
1128         unlink(fs);
1129         ast_log(LOG_DEBUG, "Locked path '%s'\n", path);
1130         return res;
1131 }
1132
1133 int ast_unlock_path(const char *path)
1134 {
1135         char *s;
1136         s = alloca(strlen(path) + 10);
1137         if (!s)
1138                 return -1;
1139         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1140         ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
1141         return unlink(s);
1142 }
1143
1144 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path) 
1145 {
1146         int silencethreshold = 128; 
1147         int maxsilence=0;
1148         int res = 0;
1149         int cmd = 0;
1150         int max_attempts = 3;
1151         int attempts = 0;
1152         int recorded = 0;
1153         int message_exists = 0;
1154         /* Note that urgent and private are for flagging messages as such in the future */
1155
1156         /* barf if no pointer passed to store duration in */
1157         if (duration == NULL) {
1158                 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1159                 return -1;
1160         }
1161
1162         cmd = '3';       /* Want to start by recording */
1163
1164         while ((cmd >= 0) && (cmd != 't')) {
1165                 switch (cmd) {
1166                 case '1':
1167                         if (!message_exists) {
1168                                 /* In this case, 1 is to record a message */
1169                                 cmd = '3';
1170                                 break;
1171                         } else {
1172                                 ast_streamfile(chan, "vm-msgsaved", chan->language);
1173                                 ast_waitstream(chan, "");
1174                                 cmd = 't';
1175                                 return res;
1176                         }
1177                 case '2':
1178                         /* Review */
1179                         ast_verbose(VERBOSE_PREFIX_3 "Reviewing the recording\n");
1180                         ast_streamfile(chan, recordfile, chan->language);
1181                         cmd = ast_waitstream(chan, AST_DIGIT_ANY);
1182                         break;
1183                 case '3':
1184                         message_exists = 0;
1185                         /* Record */
1186                         if (recorded == 1)
1187                                 ast_verbose(VERBOSE_PREFIX_3 "Re-recording\n");
1188                         else    
1189                                 ast_verbose(VERBOSE_PREFIX_3 "Recording\n");
1190                         recorded = 1;
1191                         cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path);
1192                         if (cmd == -1) {
1193                         /* User has hung up, no options to give */
1194                                 return cmd;
1195                         }
1196                         if (cmd == '0') {
1197                                 break;
1198                         } else if (cmd == '*') {
1199                                 break;
1200                         } 
1201                         else {
1202                                 /* If all is well, a message exists */
1203                                 message_exists = 1;
1204                                 cmd = 0;
1205                         }
1206                         break;
1207                 case '4':
1208                 case '5':
1209                 case '6':
1210                 case '7':
1211                 case '8':
1212                 case '9':
1213                 case '*':
1214                 case '#':
1215                         cmd = ast_play_and_wait(chan, "vm-sorry");
1216                         break;
1217                 default:
1218                         if (message_exists) {
1219                                 cmd = ast_play_and_wait(chan, "vm-review");
1220                         }
1221                         else {
1222                                 cmd = ast_play_and_wait(chan, "vm-torerecord");
1223                                 if (!cmd)
1224                                         cmd = ast_waitfordigit(chan, 600);
1225                         }
1226                         
1227                         if (!cmd)
1228                                 cmd = ast_waitfordigit(chan, 6000);
1229                         if (!cmd) {
1230                                 attempts++;
1231                         }
1232                         if (attempts > max_attempts) {
1233                                 cmd = 't';
1234                         }
1235                 }
1236         }
1237         if (cmd == 't')
1238                 cmd = 0;
1239         return cmd;
1240 }
1241
1242 #define RES_UPONE (1 << 16)
1243 #define RES_EXIT  (1 << 17)
1244 #define RES_REPEAT (1 << 18)
1245 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1246
1247 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1248 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1249 {
1250         int res;
1251         int (*ivr_func)(struct ast_channel *, void *);
1252         char *c;
1253         char *n;
1254         
1255         switch(option->action) {
1256         case AST_ACTION_UPONE:
1257                 return RES_UPONE;
1258         case AST_ACTION_EXIT:
1259                 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1260         case AST_ACTION_REPEAT:
1261                 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1262         case AST_ACTION_RESTART:
1263                 return RES_RESTART ;
1264         case AST_ACTION_NOOP:
1265                 return 0;
1266         case AST_ACTION_BACKGROUND:
1267                 res = ast_streamfile(chan, (char *)option->adata, chan->language);
1268                 if (!res) {
1269                         res = ast_waitstream(chan, AST_DIGIT_ANY);
1270                 } else {
1271                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1272                         res = 0;
1273                 }
1274                 return res;
1275         case AST_ACTION_PLAYBACK:
1276                 res = ast_streamfile(chan, (char *)option->adata, chan->language);
1277                 if (!res) {
1278                         res = ast_waitstream(chan, "");
1279                 } else {
1280                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1281                         res = 0;
1282                 }
1283                 return res;
1284         case AST_ACTION_MENU:
1285                 res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata);
1286                 /* Do not pass entry errors back up, treaat ast though ti was an "UPONE" */
1287                 if (res == -2)
1288                         res = 0;
1289                 return res;
1290         case AST_ACTION_WAITOPTION:
1291                 res = ast_waitfordigit(chan, 1000 * (chan->pbx ? chan->pbx->rtimeout : 10));
1292                 if (!res)
1293                         return 't';
1294                 return res;
1295         case AST_ACTION_CALLBACK:
1296                 ivr_func = option->adata;
1297                 res = ivr_func(chan, cbdata);
1298                 return res;
1299         case AST_ACTION_TRANSFER:
1300                 res = ast_parseable_goto(chan, option->adata);
1301                 return 0;
1302         case AST_ACTION_PLAYLIST:
1303         case AST_ACTION_BACKLIST:
1304                 res = 0;
1305                 c = ast_strdupa(option->adata);
1306                 if (c) {
1307                         while((n = strsep(&c, ";")))
1308                                 if ((res = ast_streamfile(chan, n, chan->language)) || (res = ast_waitstream(chan, (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : "")))
1309                                         break;
1310                         ast_stopstream(chan);
1311                 }
1312                 return res;
1313         default:
1314                 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1315                 return 0;
1316         };
1317         return -1;
1318 }
1319
1320 static int option_exists(struct ast_ivr_menu *menu, char *option)
1321 {
1322         int x;
1323         for (x=0;menu->options[x].option;x++)
1324                 if (!strcasecmp(menu->options[x].option, option))
1325                         return x;
1326         return -1;
1327 }
1328
1329 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1330 {
1331         int x;
1332         for (x=0;menu->options[x].option;x++)
1333                 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) && 
1334                                 (menu->options[x].option[strlen(option)]))
1335                         return x;
1336         return -1;
1337 }
1338
1339 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1340 {
1341         int res=0;
1342         int ms;
1343         while(option_matchmore(menu, exten)) {
1344                 ms = chan->pbx ? chan->pbx->dtimeout : 5000;
1345                 if (strlen(exten) >= maxexten - 1) 
1346                         break;
1347                 res = ast_waitfordigit(chan, ms);
1348                 if (res < 1)
1349                         break;
1350                 exten[strlen(exten) + 1] = '\0';
1351                 exten[strlen(exten)] = res;
1352         }
1353         return res > 0 ? 0 : res;
1354 }
1355
1356 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1357 {
1358         /* Execute an IVR menu structure */
1359         int res=0;
1360         int pos = 0;
1361         int retries = 0;
1362         char exten[AST_MAX_EXTENSION] = "s";
1363         if (option_exists(menu, "s") < 0) {
1364                 strcpy(exten, "g");
1365                 if (option_exists(menu, "g") < 0) {
1366                         ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1367                         return -1;
1368                 }
1369         }
1370         while(!res) {
1371                 while(menu->options[pos].option) {
1372                         if (!strcasecmp(menu->options[pos].option, exten)) {
1373                                 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1374                                 ast_log(LOG_DEBUG, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1375                                 if (res < 0)
1376                                         break;
1377                                 else if (res & RES_UPONE)
1378                                         return 0;
1379                                 else if (res & RES_EXIT)
1380                                         return res;
1381                                 else if (res & RES_REPEAT) {
1382                                         int maxretries = res & 0xffff;
1383                                         if ((res & RES_RESTART) == RES_RESTART) {
1384                                                 retries = 0;
1385                                         } else
1386                                                 retries++;
1387                                         if (!maxretries)
1388                                                 maxretries = 3;
1389                                         if ((maxretries > 0) && (retries >= maxretries)) {
1390                                                 ast_log(LOG_DEBUG, "Max retries %d exceeded\n", maxretries);
1391                                                 return -2;
1392                                         } else {
1393                                                 if (option_exists(menu, "g") > -1) 
1394                                                         strcpy(exten, "g");
1395                                                 else if (option_exists(menu, "s") > -1)
1396                                                         strcpy(exten, "s");
1397                                         }
1398                                         pos=0;
1399                                         continue;
1400                                 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1401                                         ast_log(LOG_DEBUG, "Got start of extension, %c\n", res);
1402                                         exten[1] = '\0';
1403                                         exten[0] = res;
1404                                         if ((res = read_newoption(chan, menu, exten, sizeof(exten))))
1405                                                 break;
1406                                         if (option_exists(menu, exten) < 0) {
1407                                                 if (option_exists(menu, "i")) {
1408                                                         ast_log(LOG_DEBUG, "Invalid extension entered, going to 'i'!\n");
1409                                                         strcpy(exten, "i");
1410                                                         pos = 0;
1411                                                         continue;
1412                                                 } else {
1413                                                         ast_log(LOG_DEBUG, "Aborting on invalid entry, with no 'i' option!\n");
1414                                                         res = -2;
1415                                                         break;
1416                                                 }
1417                                         } else {
1418                                                 ast_log(LOG_DEBUG, "New existing extension: %s\n", exten);
1419                                                 pos = 0;
1420                                                 continue;
1421                                         }
1422                                 }
1423                         }
1424                         pos++;
1425                 }
1426                 ast_log(LOG_DEBUG, "Stopping option '%s', res is %d\n", exten, res);
1427                 pos = 0;
1428                 if (!strcasecmp(exten, "s"))
1429                         strcpy(exten, "g");
1430                 else
1431                         break;
1432         }
1433         return res;
1434 }
1435
1436 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1437 {
1438         int res;
1439         res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1440         /* Hide internal coding */
1441         if (res > 0)
1442                 res = 0;
1443         return res;
1444 }
1445         
1446 char *ast_read_textfile(const char *filename)
1447 {
1448         int fd;
1449         char *output=NULL;
1450         struct stat filesize;
1451         int count=0;
1452         int res;
1453         if(stat(filename,&filesize)== -1){
1454                 ast_log(LOG_WARNING,"Error can't stat %s\n", filename);
1455                 return NULL;
1456         }
1457         count=filesize.st_size + 1;
1458         fd = open(filename, O_RDONLY);
1459         if (fd < 0) {
1460                 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1461                 return NULL;
1462         }
1463         output=(char *)malloc(count);
1464         if (output) {
1465                 res = read(fd, output, count - 1);
1466                 if (res == count - 1) {
1467                         output[res] = '\0';
1468                 } else {
1469                         ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count -  1, strerror(errno));
1470                         free(output);
1471                         output = NULL;
1472                 }
1473         } else 
1474                 ast_log(LOG_WARNING, "Out of memory!\n");
1475         close(fd);
1476         return output;
1477 }
1478
1479 int ast_parseoptions(const struct ast_option *options, struct ast_flags *flags, char **args, char *optstr)
1480 {
1481         char *s;
1482         int curarg;
1483         int argloc;
1484         char *arg;
1485         int res = 0;
1486         flags->flags = 0;
1487         if (!optstr)
1488                 return 0;
1489         s = optstr;
1490         while(*s) {
1491                 curarg = *s & 0x7f;
1492                 flags->flags |= options[curarg].flag;
1493                 argloc = options[curarg].argoption;
1494                 s++;
1495                 if (*s == '(') {
1496                         /* Has argument */
1497                         s++;
1498                         arg = s;
1499                         while(*s && (*s != ')')) s++;
1500                         if (*s) {
1501                                 if (argloc)
1502                                         args[argloc - 1] = arg;
1503                                 *s = '\0';
1504                                 s++;
1505                         } else {
1506                                 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c'\n", curarg);
1507                                 res = -1;
1508                         }
1509                 } else if (argloc)
1510                         args[argloc - 1] = NULL;
1511         }
1512         return res;
1513 }
1514