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