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