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