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