fix a flaw found while experimenting with structure alignment and padding; low-fence...
[asterisk-bristuff.git] / main / app.c
blobc9fdb4f0c7eb954809fcb5dc0171123ae3f431d9
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
19 /*! \file
21 * \brief Convenient Application Routines
23 * \author Mark Spencer <markster@digium.com>
26 #include "asterisk.h"
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/time.h>
34 #include <signal.h>
35 #include <errno.h>
36 #include <unistd.h>
37 #include <dirent.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <regex.h>
42 #include "asterisk/channel.h"
43 #include "asterisk/pbx.h"
44 #include "asterisk/file.h"
45 #include "asterisk/app.h"
46 #include "asterisk/dsp.h"
47 #include "asterisk/logger.h"
48 #include "asterisk/options.h"
49 #include "asterisk/utils.h"
50 #include "asterisk/lock.h"
51 #include "asterisk/indications.h"
52 #include "asterisk/linkedlists.h"
54 #define MAX_OTHER_FORMATS 10
56 static AST_LIST_HEAD_STATIC(groups, ast_group_info);
58 /* !
59 This function presents a dialtone and reads an extension into 'collect'
60 which must be a pointer to a **pre-initialized** array of char having a
61 size of 'size' suitable for writing to. It will collect no more than the smaller
62 of 'maxlen' or 'size' minus the original strlen() of collect digits.
63 \return 0 if extension does not exist, 1 if extension exists
65 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
67 struct ind_tone_zone_sound *ts;
68 int res=0, x=0;
70 if (maxlen > size)
71 maxlen = size;
73 if (!timeout && chan->pbx)
74 timeout = chan->pbx->dtimeout;
75 else if (!timeout)
76 timeout = 5;
78 ts = ast_get_indication_tone(chan->zone,"dial");
79 if (ts && ts->data[0])
80 res = ast_playtones_start(chan, 0, ts->data, 0);
81 else
82 ast_log(LOG_NOTICE,"Huh....? no dial for indications?\n");
84 for (x = strlen(collect); x < maxlen; ) {
85 res = ast_waitfordigit(chan, timeout);
86 if (!ast_ignore_pattern(context, collect))
87 ast_playtones_stop(chan);
88 if (res < 1)
89 break;
90 if (res == '#')
91 break;
92 collect[x++] = res;
93 if (!ast_matchmore_extension(chan, context, collect, 1, chan->cid.cid_num))
94 break;
96 if (res >= 0)
97 res = ast_exists_extension(chan, context, collect, 1, chan->cid.cid_num) ? 1 : 0;
98 return res;
101 /*! \param c The channel to read from
102 * \param prompt The file to stream to the channel
103 * \param s The string to read in to. Must be at least the size of your length
104 * \param maxlen How many digits to read (maximum)
105 * \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for
106 * "ludicrous time" (essentially never times out) */
107 int ast_app_getdata(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout)
109 int res,to,fto;
110 /* XXX Merge with full version? XXX */
111 if (maxlen)
112 s[0] = '\0';
113 if (prompt) {
114 res = ast_streamfile(c, prompt, c->language);
115 if (res < 0)
116 return res;
118 fto = c->pbx ? c->pbx->rtimeout * 1000 : 6000;
119 to = c->pbx ? c->pbx->dtimeout * 1000 : 2000;
121 if (timeout > 0)
122 fto = to = timeout;
123 if (timeout < 0)
124 fto = to = 1000000000;
125 res = ast_readstring(c, s, maxlen, to, fto, "#");
126 return res;
130 int ast_app_getdata_full(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
132 int res, to, fto;
133 if (prompt) {
134 res = ast_streamfile(c, prompt, c->language);
135 if (res < 0)
136 return res;
138 fto = 6000;
139 to = 2000;
140 if (timeout > 0)
141 fto = to = timeout;
142 if (timeout < 0)
143 fto = to = 1000000000;
144 res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
145 return res;
148 static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
149 static int (*ast_inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
150 static int (*ast_messagecount_func)(const char *context, const char *mailbox, const char *folder) = NULL;
152 void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
153 int (*inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs),
154 int (*messagecount_func)(const char *context, const char *mailbox, const char *folder))
156 ast_has_voicemail_func = has_voicemail_func;
157 ast_inboxcount_func = inboxcount_func;
158 ast_messagecount_func = messagecount_func;
161 void ast_uninstall_vm_functions(void)
163 ast_has_voicemail_func = NULL;
164 ast_inboxcount_func = NULL;
165 ast_messagecount_func = NULL;
168 int ast_app_has_voicemail(const char *mailbox, const char *folder)
170 static int warned = 0;
171 if (ast_has_voicemail_func)
172 return ast_has_voicemail_func(mailbox, folder);
174 if ((option_verbose > 2) && !warned) {
175 ast_verbose(VERBOSE_PREFIX_3 "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
176 warned++;
178 return 0;
182 int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
184 static int warned = 0;
185 if (newmsgs)
186 *newmsgs = 0;
187 if (oldmsgs)
188 *oldmsgs = 0;
189 if (ast_inboxcount_func)
190 return ast_inboxcount_func(mailbox, newmsgs, oldmsgs);
192 if (!warned && (option_verbose > 2)) {
193 warned++;
194 ast_verbose(VERBOSE_PREFIX_3 "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
197 return 0;
200 int ast_app_messagecount(const char *context, const char *mailbox, const char *folder)
202 static int warned = 0;
203 if (ast_messagecount_func)
204 return ast_messagecount_func(context, mailbox, folder);
206 if (!warned && (option_verbose > 2)) {
207 warned++;
208 ast_verbose(VERBOSE_PREFIX_3 "Message count requested for mailbox %s@%s/%s but voicemail not loaded.\n", mailbox, context, folder);
211 return 0;
214 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between)
216 const char *ptr;
217 int res = 0;
218 struct ast_silence_generator *silgen = NULL;
220 if (!between)
221 between = 100;
223 if (peer)
224 res = ast_autoservice_start(peer);
226 if (!res)
227 res = ast_waitfor(chan, 100);
229 /* ast_waitfor will return the number of remaining ms on success */
230 if (res < 0)
231 return res;
233 if (ast_opt_transmit_silence) {
234 silgen = ast_channel_start_silence_generator(chan);
237 for (ptr = digits; *ptr; ptr++) {
238 if (*ptr == 'w') {
239 /* 'w' -- wait half a second */
240 if ((res = ast_safe_sleep(chan, 500)))
241 break;
242 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
243 /* Character represents valid DTMF */
244 if (*ptr == 'f' || *ptr == 'F') {
245 /* ignore return values if not supported by channel */
246 ast_indicate(chan, AST_CONTROL_FLASH);
247 } else
248 ast_senddigit(chan, *ptr);
249 /* pause between digits */
250 if ((res = ast_safe_sleep(chan, between)))
251 break;
252 } else
253 ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n",*ptr);
256 if (peer) {
257 /* Stop autoservice on the peer channel, but don't overwrite any error condition
258 that has occurred previously while acting on the primary channel */
259 if (ast_autoservice_stop(peer) && !res)
260 res = -1;
263 if (silgen) {
264 ast_channel_stop_silence_generator(chan, silgen);
267 return res;
270 struct linear_state {
271 int fd;
272 int autoclose;
273 int allowoverride;
274 int origwfmt;
277 static void linear_release(struct ast_channel *chan, void *params)
279 struct linear_state *ls = params;
280 if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt)) {
281 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", chan->name, ls->origwfmt);
283 if (ls->autoclose)
284 close(ls->fd);
285 free(params);
288 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
290 struct ast_frame f;
291 short buf[2048 + AST_FRIENDLY_OFFSET / 2];
292 struct linear_state *ls = data;
293 int res;
294 len = samples * 2;
295 if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
296 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" ,len);
297 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
299 memset(&f, 0, sizeof(f));
300 res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
301 if (res > 0) {
302 f.frametype = AST_FRAME_VOICE;
303 f.subclass = AST_FORMAT_SLINEAR;
304 f.data = buf + AST_FRIENDLY_OFFSET/2;
305 f.datalen = res;
306 f.samples = res / 2;
307 f.offset = AST_FRIENDLY_OFFSET;
308 ast_write(chan, &f);
309 if (res == len)
310 return 0;
312 return -1;
315 static void *linear_alloc(struct ast_channel *chan, void *params)
317 struct linear_state *ls;
318 /* In this case, params is already malloc'd */
319 if (params) {
320 ls = params;
321 if (ls->allowoverride)
322 ast_set_flag(chan, AST_FLAG_WRITE_INT);
323 else
324 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
325 ls->origwfmt = chan->writeformat;
326 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
327 ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", chan->name);
328 free(ls);
329 ls = params = NULL;
332 return params;
335 static struct ast_generator linearstream =
337 alloc: linear_alloc,
338 release: linear_release,
339 generate: linear_generator,
342 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
344 struct linear_state *lin;
345 char tmpf[256];
346 int res = -1;
347 int autoclose = 0;
348 if (fd < 0) {
349 if (ast_strlen_zero(filename))
350 return -1;
351 autoclose = 1;
352 if (filename[0] == '/')
353 ast_copy_string(tmpf, filename, sizeof(tmpf));
354 else
355 snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", (char *)ast_config_AST_DATA_DIR, "sounds", filename);
356 fd = open(tmpf, O_RDONLY);
357 if (fd < 0){
358 ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
359 return -1;
362 if ((lin = ast_calloc(1, sizeof(*lin)))) {
363 lin->fd = fd;
364 lin->allowoverride = allowoverride;
365 lin->autoclose = autoclose;
366 res = ast_activate_generator(chan, &linearstream, lin);
368 return res;
371 int ast_control_streamfile(struct ast_channel *chan, const char *file,
372 const char *fwd, const char *rev,
373 const char *stop, const char *pause,
374 const char *restart, int skipms)
376 char *breaks = NULL;
377 char *end = NULL;
378 int blen = 2;
379 int res;
380 long pause_restart_point = 0;
382 if (stop)
383 blen += strlen(stop);
384 if (pause)
385 blen += strlen(pause);
386 if (restart)
387 blen += strlen(restart);
389 if (blen > 2) {
390 breaks = alloca(blen + 1);
391 breaks[0] = '\0';
392 if (stop)
393 strcat(breaks, stop);
394 if (pause)
395 strcat(breaks, pause);
396 if (restart)
397 strcat(breaks, restart);
399 if (chan->_state != AST_STATE_UP)
400 res = ast_answer(chan);
402 if (file) {
403 if ((end = strchr(file,':'))) {
404 if (!strcasecmp(end, ":end")) {
405 *end = '\0';
406 end++;
411 for (;;) {
412 ast_stopstream(chan);
413 res = ast_streamfile(chan, file, chan->language);
414 if (!res) {
415 if (pause_restart_point) {
416 ast_seekstream(chan->stream, pause_restart_point, SEEK_SET);
417 pause_restart_point = 0;
419 else if (end) {
420 ast_seekstream(chan->stream, 0, SEEK_END);
421 end = NULL;
423 res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
426 if (res < 1)
427 break;
429 /* We go at next loop if we got the restart char */
430 if (restart && strchr(restart, res)) {
431 if (option_debug)
432 ast_log(LOG_DEBUG, "we'll restart the stream here at next loop\n");
433 pause_restart_point = 0;
434 continue;
437 if (pause && strchr(pause, res)) {
438 pause_restart_point = ast_tellstream(chan->stream);
439 for (;;) {
440 ast_stopstream(chan);
441 res = ast_waitfordigit(chan, 1000);
442 if (!res)
443 continue;
444 else if (res == -1 || strchr(pause, res) || (stop && strchr(stop, res)))
445 break;
447 if (res == *pause) {
448 res = 0;
449 continue;
453 if (res == -1)
454 break;
456 /* if we get one of our stop chars, return it to the calling function */
457 if (stop && strchr(stop, res))
458 break;
461 /* If we are returning a digit cast it as char */
462 if (res > 0 || chan->stream)
463 res = (char)res;
465 ast_stopstream(chan);
467 return res;
470 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
472 int d;
473 d = ast_streamfile(chan, fn, chan->language);
474 if (d)
475 return d;
476 d = ast_waitstream(chan, AST_DIGIT_ANY);
477 ast_stopstream(chan);
478 return d;
481 static int global_silence_threshold = 128;
482 static int global_maxsilence = 0;
484 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
485 * @param chan Channel to playback to/record from.
486 * @param playfile Filename of sound to play before recording begins.
487 * @param recordfile Filename to record to.
488 * @param maxtime Maximum length of recording (in milliseconds).
489 * @param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
490 * @param duration Where to store actual length of the recorded message (in milliseconds).
491 * @param beep Whether to play a beep before starting to record.
492 * @param silencethreshold
493 * @param maxsilence Length of silence that will end a recording (in milliseconds).
494 * @param path Optional filesystem path to unlock.
495 * @param prepend If true, prepend the recorded audio to an existing file.
496 * @param acceptdtmf DTMF digits that will end the recording.
497 * @param canceldtmf DTMF digits that will cancel the recording.
500 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)
502 int d = 0;
503 char *fmts;
504 char comment[256];
505 int x, fmtcnt = 1, res = -1, outmsg = 0;
506 struct ast_filestream *others[MAX_OTHER_FORMATS];
507 char *sfmt[MAX_OTHER_FORMATS];
508 char *stringp = NULL;
509 time_t start, end;
510 struct ast_dsp *sildet = NULL; /* silence detector dsp */
511 int totalsilence = 0;
512 int rfmt = 0;
513 struct ast_silence_generator *silgen = NULL;
514 char prependfile[80];
516 if (silencethreshold < 0)
517 silencethreshold = global_silence_threshold;
519 if (maxsilence < 0)
520 maxsilence = global_maxsilence;
522 /* barf if no pointer passed to store duration in */
523 if (duration == NULL) {
524 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
525 return -1;
528 if (option_debug)
529 ast_log(LOG_DEBUG,"play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
530 snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, chan->name);
532 if (playfile || beep) {
533 if (!beep)
534 d = ast_play_and_wait(chan, playfile);
535 if (d > -1)
536 d = ast_stream_and_wait(chan, "beep", chan->language, "");
537 if (d < 0)
538 return -1;
541 if (prepend) {
542 ast_copy_string(prependfile, recordfile, sizeof(prependfile));
543 strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
546 fmts = ast_strdupa(fmt);
548 stringp = fmts;
549 strsep(&stringp, "|");
550 if (option_debug)
551 ast_log(LOG_DEBUG, "Recording Formats: sfmts=%s\n", fmts);
552 sfmt[0] = ast_strdupa(fmts);
554 while ((fmt = strsep(&stringp, "|"))) {
555 if (fmtcnt > MAX_OTHER_FORMATS - 1) {
556 ast_log(LOG_WARNING, "Please increase MAX_OTHER_FORMATS in app.c\n");
557 break;
559 sfmt[fmtcnt++] = ast_strdupa(fmt);
562 end = start = time(NULL); /* pre-initialize end to be same as start in case we never get into loop */
563 for (x = 0; x < fmtcnt; x++) {
564 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, 0777);
565 if (option_verbose > 2)
566 ast_verbose(VERBOSE_PREFIX_3 "x=%d, open writing: %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
568 if (!others[x])
569 break;
572 if (path)
573 ast_unlock_path(path);
575 if (maxsilence > 0) {
576 sildet = ast_dsp_new(); /* Create the silence detector */
577 if (!sildet) {
578 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
579 return -1;
581 ast_dsp_set_threshold(sildet, silencethreshold);
582 rfmt = chan->readformat;
583 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
584 if (res < 0) {
585 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
586 ast_dsp_free(sildet);
587 return -1;
591 if (!prepend) {
592 /* Request a video update */
593 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
595 if (ast_opt_transmit_silence)
596 silgen = ast_channel_start_silence_generator(chan);
599 if (x == fmtcnt) {
600 /* Loop forever, writing the packets we read to the writer(s), until
601 we read a digit or get a hangup */
602 struct ast_frame *f;
603 for (;;) {
604 res = ast_waitfor(chan, 2000);
605 if (!res) {
606 if (option_debug)
607 ast_log(LOG_DEBUG, "One waitfor failed, trying another\n");
608 /* Try one more time in case of masq */
609 res = ast_waitfor(chan, 2000);
610 if (!res) {
611 ast_log(LOG_WARNING, "No audio available on %s??\n", chan->name);
612 res = -1;
616 if (res < 0) {
617 f = NULL;
618 break;
620 f = ast_read(chan);
621 if (!f)
622 break;
623 if (f->frametype == AST_FRAME_VOICE) {
624 /* write each format */
625 for (x = 0; x < fmtcnt; x++) {
626 if (prepend && !others[x])
627 break;
628 res = ast_writestream(others[x], f);
631 /* Silence Detection */
632 if (maxsilence > 0) {
633 int dspsilence = 0;
634 ast_dsp_silence(sildet, f, &dspsilence);
635 if (dspsilence)
636 totalsilence = dspsilence;
637 else
638 totalsilence = 0;
640 if (totalsilence > maxsilence) {
641 /* Ended happily with silence */
642 if (option_verbose > 2)
643 ast_verbose( VERBOSE_PREFIX_3 "Recording automatically stopped after a silence of %d seconds\n", totalsilence/1000);
644 res = 'S';
645 outmsg = 2;
646 break;
649 /* Exit on any error */
650 if (res) {
651 ast_log(LOG_WARNING, "Error writing frame\n");
652 break;
654 } else if (f->frametype == AST_FRAME_VIDEO) {
655 /* Write only once */
656 ast_writestream(others[0], f);
657 } else if (f->frametype == AST_FRAME_DTMF) {
658 if (prepend) {
659 /* stop recording with any digit */
660 if (option_verbose > 2)
661 ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
662 res = 't';
663 outmsg = 2;
664 break;
666 if (strchr(acceptdtmf, f->subclass)) {
667 if (option_verbose > 2)
668 ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
669 res = f->subclass;
670 outmsg = 2;
671 break;
673 if (strchr(canceldtmf, f->subclass)) {
674 if (option_verbose > 2)
675 ast_verbose(VERBOSE_PREFIX_3 "User cancelled message by pressing %c\n", f->subclass);
676 res = f->subclass;
677 outmsg = 0;
678 break;
681 if (maxtime) {
682 end = time(NULL);
683 if (maxtime < (end - start)) {
684 if (option_verbose > 2)
685 ast_verbose(VERBOSE_PREFIX_3 "Took too long, cutting it short...\n");
686 res = 't';
687 outmsg = 2;
688 break;
691 ast_frfree(f);
693 if (!f) {
694 if (option_verbose > 2)
695 ast_verbose(VERBOSE_PREFIX_3 "User hung up\n");
696 res = -1;
697 outmsg = 1;
698 } else {
699 ast_frfree(f);
701 } else {
702 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
705 if (!prepend) {
706 if (silgen)
707 ast_channel_stop_silence_generator(chan, silgen);
710 /*!\note
711 * Instead of asking how much time passed (end - start), calculate the number
712 * of seconds of audio which actually went into the file. This fixes a
713 * problem where audio is stopped up on the network and never gets to us.
715 * Note that we still want to use the number of seconds passed for the max
716 * message, otherwise we could get a situation where this stream is never
717 * closed (which would create a resource leak).
719 *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
721 if (!prepend) {
722 for (x = 0; x < fmtcnt; x++) {
723 if (!others[x])
724 break;
725 /*!\note
726 * If we ended with silence, trim all but the first 200ms of silence
727 * off the recording. However, if we ended with '#', we don't want
728 * to trim ANY part of the recording.
730 if (res > 0 && totalsilence)
731 ast_stream_rewind(others[x], totalsilence - 200);
732 ast_truncstream(others[x]);
733 ast_closestream(others[x]);
737 if (prepend && outmsg) {
738 struct ast_filestream *realfiles[MAX_OTHER_FORMATS];
739 struct ast_frame *fr;
741 for (x = 0; x < fmtcnt; x++) {
742 snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
743 realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
744 if (!others[x] || !realfiles[x])
745 break;
746 /*!\note Same logic as above. */
747 if (totalsilence)
748 ast_stream_rewind(others[x], totalsilence - 200);
749 ast_truncstream(others[x]);
750 /* add the original file too */
751 while ((fr = ast_readframe(realfiles[x]))) {
752 ast_writestream(others[x], fr);
753 ast_frfree(fr);
755 ast_closestream(others[x]);
756 ast_closestream(realfiles[x]);
757 ast_filerename(prependfile, recordfile, sfmt[x]);
758 if (option_verbose > 3)
759 ast_verbose(VERBOSE_PREFIX_4 "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
760 ast_filedelete(prependfile, sfmt[x]);
763 if (rfmt && ast_set_read_format(chan, rfmt)) {
764 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(rfmt), chan->name);
766 if (outmsg == 2) {
767 ast_stream_and_wait(chan, "auth-thankyou", chan->language, "");
769 if (sildet)
770 ast_dsp_free(sildet);
771 return res;
774 static char default_acceptdtmf[] = "#";
775 static char default_canceldtmf[] = "";
777 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)
779 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));
782 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)
784 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf);
787 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)
789 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf);
792 /* Channel group core functions */
794 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
796 int res=0;
797 char tmp[256];
798 char *grp=NULL, *cat=NULL;
800 if (!ast_strlen_zero(data)) {
801 ast_copy_string(tmp, data, sizeof(tmp));
802 grp = tmp;
803 cat = strchr(tmp, '@');
804 if (cat) {
805 *cat = '\0';
806 cat++;
810 if (!ast_strlen_zero(grp))
811 ast_copy_string(group, grp, group_max);
812 else
813 *group = '\0';
815 if (!ast_strlen_zero(cat))
816 ast_copy_string(category, cat, category_max);
818 return res;
821 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
823 int res = 0;
824 char group[80] = "", category[80] = "";
825 struct ast_group_info *gi = NULL;
826 size_t len = 0;
828 if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category)))
829 return -1;
831 /* Calculate memory we will need if this is new */
832 len = sizeof(*gi) + strlen(group) + 1;
833 if (!ast_strlen_zero(category))
834 len += strlen(category) + 1;
836 AST_LIST_LOCK(&groups);
837 AST_LIST_TRAVERSE_SAFE_BEGIN(&groups, gi, list) {
838 if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
839 AST_LIST_REMOVE_CURRENT(&groups, list);
840 free(gi);
841 break;
844 AST_LIST_TRAVERSE_SAFE_END
846 if (ast_strlen_zero(group)) {
847 /* Enable unsetting the group */
848 } else if ((gi = calloc(1, len))) {
849 gi->chan = chan;
850 gi->group = (char *) gi + sizeof(*gi);
851 strcpy(gi->group, group);
852 if (!ast_strlen_zero(category)) {
853 gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
854 strcpy(gi->category, category);
856 AST_LIST_INSERT_TAIL(&groups, gi, list);
857 } else {
858 res = -1;
861 AST_LIST_UNLOCK(&groups);
863 return res;
866 int ast_app_group_get_count(const char *group, const char *category)
868 struct ast_group_info *gi = NULL;
869 int count = 0;
871 if (ast_strlen_zero(group))
872 return 0;
874 AST_LIST_LOCK(&groups);
875 AST_LIST_TRAVERSE(&groups, gi, list) {
876 if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category))))
877 count++;
879 AST_LIST_UNLOCK(&groups);
881 return count;
884 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
886 struct ast_group_info *gi = NULL;
887 regex_t regexbuf;
888 int count = 0;
890 if (ast_strlen_zero(groupmatch))
891 return 0;
893 /* if regex compilation fails, return zero matches */
894 if (regcomp(&regexbuf, groupmatch, REG_EXTENDED | REG_NOSUB))
895 return 0;
897 AST_LIST_LOCK(&groups);
898 AST_LIST_TRAVERSE(&groups, gi, list) {
899 if (!regexec(&regexbuf, gi->group, 0, NULL, 0) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category))))
900 count++;
902 AST_LIST_UNLOCK(&groups);
904 regfree(&regexbuf);
906 return count;
909 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
911 struct ast_group_info *gi = NULL;
913 AST_LIST_LOCK(&groups);
914 AST_LIST_TRAVERSE(&groups, gi, list) {
915 if (gi->chan == old)
916 gi->chan = new;
918 AST_LIST_UNLOCK(&groups);
920 return 0;
923 int ast_app_group_discard(struct ast_channel *chan)
925 struct ast_group_info *gi = NULL;
927 AST_LIST_LOCK(&groups);
928 AST_LIST_TRAVERSE_SAFE_BEGIN(&groups, gi, list) {
929 if (gi->chan == chan) {
930 AST_LIST_REMOVE_CURRENT(&groups, list);
931 free(gi);
934 AST_LIST_TRAVERSE_SAFE_END
935 AST_LIST_UNLOCK(&groups);
937 return 0;
940 int ast_app_group_list_lock(void)
942 return AST_LIST_LOCK(&groups);
945 struct ast_group_info *ast_app_group_list_head(void)
947 return AST_LIST_FIRST(&groups);
950 int ast_app_group_list_unlock(void)
952 return AST_LIST_UNLOCK(&groups);
955 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
957 int argc;
958 char *scan, *wasdelim = NULL;
959 int paren = 0, quote = 0;
961 if (!buf || !array || !arraylen)
962 return 0;
964 memset(array, 0, arraylen * sizeof(*array));
966 scan = buf;
968 for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
969 array[argc] = scan;
970 for (; *scan; scan++) {
971 if (*scan == '(')
972 paren++;
973 else if (*scan == ')') {
974 if (paren)
975 paren--;
976 } else if (*scan == '"' && delim != '"') {
977 quote = quote ? 0 : 1;
978 /* Remove quote character from argument */
979 memmove(scan, scan + 1, strlen(scan));
980 scan--;
981 } else if (*scan == '\\') {
982 /* Literal character, don't parse */
983 memmove(scan, scan + 1, strlen(scan));
984 } else if ((*scan == delim) && !paren && !quote) {
985 wasdelim = scan;
986 *scan++ = '\0';
987 break;
992 /* If the last character in the original string was the delimiter, then
993 * there is one additional argument. */
994 if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
995 array[argc++] = scan;
998 return argc;
1001 enum AST_LOCK_RESULT ast_lock_path(const char *path)
1003 char *s;
1004 char *fs;
1005 int res;
1006 int fd;
1007 int lp = strlen(path);
1008 time_t start;
1010 if (!(s = alloca(lp + 10)) || !(fs = alloca(lp + 20))) {
1011 ast_log(LOG_WARNING, "Out of memory!\n");
1012 return AST_LOCK_FAILURE;
1015 snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
1016 fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, 0600);
1017 if (fd < 0) {
1018 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
1019 return AST_LOCK_PATH_NOT_FOUND;
1021 close(fd);
1023 snprintf(s, strlen(path) + 9, "%s/.lock", path);
1024 start = time(NULL);
1025 while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5))
1026 usleep(1);
1028 unlink(fs);
1030 if (res) {
1031 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
1032 return AST_LOCK_TIMEOUT;
1033 } else {
1034 if (option_debug)
1035 ast_log(LOG_DEBUG, "Locked path '%s'\n", path);
1036 return AST_LOCK_SUCCESS;
1040 int ast_unlock_path(const char *path)
1042 char *s;
1043 int res;
1045 if (!(s = alloca(strlen(path) + 10))) {
1046 ast_log(LOG_WARNING, "Out of memory!\n");
1047 return -1;
1050 snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1052 if ((res = unlink(s)))
1053 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
1054 else {
1055 if (option_debug)
1056 ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
1059 return res;
1062 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
1064 int silencethreshold = 128;
1065 int maxsilence=0;
1066 int res = 0;
1067 int cmd = 0;
1068 int max_attempts = 3;
1069 int attempts = 0;
1070 int recorded = 0;
1071 int message_exists = 0;
1072 /* Note that urgent and private are for flagging messages as such in the future */
1074 /* barf if no pointer passed to store duration in */
1075 if (duration == NULL) {
1076 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1077 return -1;
1080 cmd = '3'; /* Want to start by recording */
1082 while ((cmd >= 0) && (cmd != 't')) {
1083 switch (cmd) {
1084 case '1':
1085 if (!message_exists) {
1086 /* In this case, 1 is to record a message */
1087 cmd = '3';
1088 break;
1089 } else {
1090 ast_stream_and_wait(chan, "vm-msgsaved", chan->language, "");
1091 cmd = 't';
1092 return res;
1094 case '2':
1095 /* Review */
1096 ast_verbose(VERBOSE_PREFIX_3 "Reviewing the recording\n");
1097 cmd = ast_stream_and_wait(chan, recordfile, chan->language, AST_DIGIT_ANY);
1098 break;
1099 case '3':
1100 message_exists = 0;
1101 /* Record */
1102 if (recorded == 1)
1103 ast_verbose(VERBOSE_PREFIX_3 "Re-recording\n");
1104 else
1105 ast_verbose(VERBOSE_PREFIX_3 "Recording\n");
1106 recorded = 1;
1107 cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path);
1108 if (cmd == -1) {
1109 /* User has hung up, no options to give */
1110 return cmd;
1112 if (cmd == '0') {
1113 break;
1114 } else if (cmd == '*') {
1115 break;
1117 else {
1118 /* If all is well, a message exists */
1119 message_exists = 1;
1120 cmd = 0;
1122 break;
1123 case '4':
1124 case '5':
1125 case '6':
1126 case '7':
1127 case '8':
1128 case '9':
1129 case '*':
1130 case '#':
1131 cmd = ast_play_and_wait(chan, "vm-sorry");
1132 break;
1133 default:
1134 if (message_exists) {
1135 cmd = ast_play_and_wait(chan, "vm-review");
1137 else {
1138 cmd = ast_play_and_wait(chan, "vm-torerecord");
1139 if (!cmd)
1140 cmd = ast_waitfordigit(chan, 600);
1143 if (!cmd)
1144 cmd = ast_waitfordigit(chan, 6000);
1145 if (!cmd) {
1146 attempts++;
1148 if (attempts > max_attempts) {
1149 cmd = 't';
1153 if (cmd == 't')
1154 cmd = 0;
1155 return cmd;
1158 #define RES_UPONE (1 << 16)
1159 #define RES_EXIT (1 << 17)
1160 #define RES_REPEAT (1 << 18)
1161 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1163 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1165 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1167 int res;
1168 int (*ivr_func)(struct ast_channel *, void *);
1169 char *c;
1170 char *n;
1172 switch(option->action) {
1173 case AST_ACTION_UPONE:
1174 return RES_UPONE;
1175 case AST_ACTION_EXIT:
1176 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1177 case AST_ACTION_REPEAT:
1178 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1179 case AST_ACTION_RESTART:
1180 return RES_RESTART ;
1181 case AST_ACTION_NOOP:
1182 return 0;
1183 case AST_ACTION_BACKGROUND:
1184 res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, AST_DIGIT_ANY);
1185 if (res < 0) {
1186 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1187 res = 0;
1189 return res;
1190 case AST_ACTION_PLAYBACK:
1191 res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, "");
1192 if (res < 0) {
1193 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1194 res = 0;
1196 return res;
1197 case AST_ACTION_MENU:
1198 res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata);
1199 /* Do not pass entry errors back up, treaat ast though ti was an "UPONE" */
1200 if (res == -2)
1201 res = 0;
1202 return res;
1203 case AST_ACTION_WAITOPTION:
1204 res = ast_waitfordigit(chan, 1000 * (chan->pbx ? chan->pbx->rtimeout : 10));
1205 if (!res)
1206 return 't';
1207 return res;
1208 case AST_ACTION_CALLBACK:
1209 ivr_func = option->adata;
1210 res = ivr_func(chan, cbdata);
1211 return res;
1212 case AST_ACTION_TRANSFER:
1213 res = ast_parseable_goto(chan, option->adata);
1214 return 0;
1215 case AST_ACTION_PLAYLIST:
1216 case AST_ACTION_BACKLIST:
1217 res = 0;
1218 c = ast_strdupa(option->adata);
1219 while ((n = strsep(&c, ";"))) {
1220 if ((res = ast_stream_and_wait(chan, n, chan->language,
1221 (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : "")))
1222 break;
1224 ast_stopstream(chan);
1225 return res;
1226 default:
1227 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1228 return 0;
1230 return -1;
1233 static int option_exists(struct ast_ivr_menu *menu, char *option)
1235 int x;
1236 for (x = 0; menu->options[x].option; x++)
1237 if (!strcasecmp(menu->options[x].option, option))
1238 return x;
1239 return -1;
1242 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1244 int x;
1245 for (x = 0; menu->options[x].option; x++)
1246 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
1247 (menu->options[x].option[strlen(option)]))
1248 return x;
1249 return -1;
1252 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1254 int res=0;
1255 int ms;
1256 while (option_matchmore(menu, exten)) {
1257 ms = chan->pbx ? chan->pbx->dtimeout : 5000;
1258 if (strlen(exten) >= maxexten - 1)
1259 break;
1260 res = ast_waitfordigit(chan, ms);
1261 if (res < 1)
1262 break;
1263 exten[strlen(exten) + 1] = '\0';
1264 exten[strlen(exten)] = res;
1266 return res > 0 ? 0 : res;
1269 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1271 /* Execute an IVR menu structure */
1272 int res=0;
1273 int pos = 0;
1274 int retries = 0;
1275 char exten[AST_MAX_EXTENSION] = "s";
1276 if (option_exists(menu, "s") < 0) {
1277 strcpy(exten, "g");
1278 if (option_exists(menu, "g") < 0) {
1279 ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1280 return -1;
1283 while(!res) {
1284 while(menu->options[pos].option) {
1285 if (!strcasecmp(menu->options[pos].option, exten)) {
1286 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1287 if (option_debug)
1288 ast_log(LOG_DEBUG, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1289 if (res < 0)
1290 break;
1291 else if (res & RES_UPONE)
1292 return 0;
1293 else if (res & RES_EXIT)
1294 return res;
1295 else if (res & RES_REPEAT) {
1296 int maxretries = res & 0xffff;
1297 if ((res & RES_RESTART) == RES_RESTART) {
1298 retries = 0;
1299 } else
1300 retries++;
1301 if (!maxretries)
1302 maxretries = 3;
1303 if ((maxretries > 0) && (retries >= maxretries)) {
1304 if (option_debug)
1305 ast_log(LOG_DEBUG, "Max retries %d exceeded\n", maxretries);
1306 return -2;
1307 } else {
1308 if (option_exists(menu, "g") > -1)
1309 strcpy(exten, "g");
1310 else if (option_exists(menu, "s") > -1)
1311 strcpy(exten, "s");
1313 pos = 0;
1314 continue;
1315 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1316 if (option_debug)
1317 ast_log(LOG_DEBUG, "Got start of extension, %c\n", res);
1318 exten[1] = '\0';
1319 exten[0] = res;
1320 if ((res = read_newoption(chan, menu, exten, sizeof(exten))))
1321 break;
1322 if (option_exists(menu, exten) < 0) {
1323 if (option_exists(menu, "i")) {
1324 if (option_debug)
1325 ast_log(LOG_DEBUG, "Invalid extension entered, going to 'i'!\n");
1326 strcpy(exten, "i");
1327 pos = 0;
1328 continue;
1329 } else {
1330 if (option_debug)
1331 ast_log(LOG_DEBUG, "Aborting on invalid entry, with no 'i' option!\n");
1332 res = -2;
1333 break;
1335 } else {
1336 if (option_debug)
1337 ast_log(LOG_DEBUG, "New existing extension: %s\n", exten);
1338 pos = 0;
1339 continue;
1343 pos++;
1345 if (option_debug)
1346 ast_log(LOG_DEBUG, "Stopping option '%s', res is %d\n", exten, res);
1347 pos = 0;
1348 if (!strcasecmp(exten, "s"))
1349 strcpy(exten, "g");
1350 else
1351 break;
1353 return res;
1356 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1358 int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1359 /* Hide internal coding */
1360 return res > 0 ? 0 : res;
1363 char *ast_read_textfile(const char *filename)
1365 int fd;
1366 char *output = NULL;
1367 struct stat filesize;
1368 int count = 0;
1369 int res;
1370 if (stat(filename, &filesize) == -1) {
1371 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
1372 return NULL;
1374 count = filesize.st_size + 1;
1375 fd = open(filename, O_RDONLY);
1376 if (fd < 0) {
1377 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1378 return NULL;
1380 if ((output = ast_malloc(count))) {
1381 res = read(fd, output, count - 1);
1382 if (res == count - 1) {
1383 output[res] = '\0';
1384 } else {
1385 ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
1386 free(output);
1387 output = NULL;
1390 close(fd);
1391 return output;
1394 void ast_app_options2str(const struct ast_app_option *options, struct ast_flags *flags, char *buf, size_t len)
1396 unsigned int i, found = 0;
1398 for (i = 32; i < 128 && found < len;i++) {
1399 if (ast_test_flag(flags, options[i].flag)) {
1400 buf[found++] = i;
1403 buf[found] = '\0';
1406 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
1408 char *s;
1409 int curarg;
1410 unsigned int argloc;
1411 char *arg;
1412 int res = 0;
1414 ast_clear_flag(flags, AST_FLAGS_ALL);
1416 if (!optstr)
1417 return 0;
1419 s = optstr;
1420 while (*s) {
1421 curarg = *s++ & 0x7f; /* the array (in app.h) has 128 entries */
1422 argloc = options[curarg].arg_index;
1423 if (*s == '(') {
1424 /* Has argument */
1425 arg = ++s;
1426 if ((s = strchr(s, ')'))) {
1427 if (argloc)
1428 args[argloc - 1] = arg;
1429 *s++ = '\0';
1430 } else {
1431 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
1432 res = -1;
1433 break;
1435 } else if (argloc) {
1436 args[argloc - 1] = "";
1438 ast_set_flag(flags, options[curarg].flag);
1441 return res;