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