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