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