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