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