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