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