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