update cleancount because the channel structure changed today
[asterisk-bristuff.git] / app.c
blobdb1567dfc160da64f3a536c76d6bf46e3771f267
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"
53 #define MAX_OTHER_FORMATS 10
56 /* !
57 This function presents a dialtone and reads an extension into 'collect'
58 which must be a pointer to a **pre-initialized** array of char having a
59 size of 'size' suitable for writing to. It will collect no more than the smaller
60 of 'maxlen' or 'size' minus the original strlen() of collect digits.
61 \return 0 if extension does not exist, 1 if extension exists
63 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
65 struct tone_zone_sound *ts;
66 int res=0, x=0;
68 if (maxlen > size)
69 maxlen = size;
71 if (!timeout && chan->pbx)
72 timeout = chan->pbx->dtimeout;
73 else if (!timeout)
74 timeout = 5;
76 ts = ast_get_indication_tone(chan->zone,"dial");
77 if (ts && ts->data[0])
78 res = ast_playtones_start(chan, 0, ts->data, 0);
79 else
80 ast_log(LOG_NOTICE,"Huh....? no dial for indications?\n");
82 for (x = strlen(collect); x < maxlen; ) {
83 res = ast_waitfordigit(chan, timeout);
84 if (!ast_ignore_pattern(context, collect))
85 ast_playtones_stop(chan);
86 if (res < 1)
87 break;
88 collect[x++] = res;
89 if (!ast_matchmore_extension(chan, context, collect, 1, chan->cid.cid_num)) {
90 if (collect[x-1] == '#') {
91 /* Not a valid extension, ending in #, assume the # was to finish dialing */
92 collect[x-1] = '\0';
94 break;
97 if (res >= 0)
98 res = ast_exists_extension(chan, context, collect, 1, chan->cid.cid_num) ? 1 : 0;
99 return res;
102 /*! \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for
103 "ludicrous time" (essentially never times out) */
104 int ast_app_getdata(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout)
106 int res,to,fto;
107 /* XXX Merge with full version? XXX */
108 if (maxlen)
109 s[0] = '\0';
110 if (prompt) {
111 res = ast_streamfile(c, prompt, c->language);
112 if (res < 0)
113 return res;
115 fto = c->pbx ? c->pbx->rtimeout * 1000 : 6000;
116 to = c->pbx ? c->pbx->dtimeout * 1000 : 2000;
118 if (timeout > 0)
119 fto = to = timeout;
120 if (timeout < 0)
121 fto = to = 1000000000;
122 res = ast_readstring(c, s, maxlen, to, fto, "#");
123 return res;
127 int ast_app_getdata_full(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
129 int res, to, fto;
130 if (prompt) {
131 res = ast_streamfile(c, prompt, c->language);
132 if (res < 0)
133 return res;
135 fto = 6000;
136 to = 2000;
137 if (timeout > 0)
138 fto = to = timeout;
139 if (timeout < 0)
140 fto = to = 1000000000;
141 res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
142 return res;
145 static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
146 static int (*ast_inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
147 static int (*ast_messagecount_func)(const char *context, const char *mailbox, const char *folder) = NULL;
149 void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
150 int (*inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs),
151 int (*messagecount_func)(const char *context, const char *mailbox, const char *folder))
153 ast_has_voicemail_func = has_voicemail_func;
154 ast_inboxcount_func = inboxcount_func;
155 ast_messagecount_func = messagecount_func;
158 void ast_uninstall_vm_functions(void)
160 ast_has_voicemail_func = NULL;
161 ast_inboxcount_func = NULL;
162 ast_messagecount_func = NULL;
165 int ast_app_has_voicemail(const char *mailbox, const char *folder)
167 static int warned = 0;
168 if (ast_has_voicemail_func)
169 return ast_has_voicemail_func(mailbox, folder);
171 if ((option_verbose > 2) && !warned) {
172 ast_verbose(VERBOSE_PREFIX_3 "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
173 warned++;
175 return 0;
179 int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
181 static int warned = 0;
182 if (newmsgs)
183 *newmsgs = 0;
184 if (oldmsgs)
185 *oldmsgs = 0;
186 if (ast_inboxcount_func)
187 return ast_inboxcount_func(mailbox, newmsgs, oldmsgs);
189 if (!warned && (option_verbose > 2)) {
190 warned++;
191 ast_verbose(VERBOSE_PREFIX_3 "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
194 return 0;
197 int ast_app_messagecount(const char *context, const char *mailbox, const char *folder)
199 static int warned = 0;
200 if (ast_messagecount_func)
201 return ast_messagecount_func(context, mailbox, folder);
203 if (!warned && (option_verbose > 2)) {
204 warned++;
205 ast_verbose(VERBOSE_PREFIX_3 "Message count requested for mailbox %s@%s/%s but voicemail not loaded.\n", mailbox, context, folder);
208 return 0;
211 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between)
213 const char *ptr;
214 int res = 0;
215 struct ast_frame f = {
216 .frametype = AST_FRAME_DTMF,
217 .src = "ast_dtmf_stream"
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 for (ptr = digits; *ptr; ptr++) {
234 if (*ptr == 'w') {
235 /* 'w' -- wait half a second */
236 if ((res = ast_safe_sleep(chan, 500)))
237 break;
238 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
239 /* Character represents valid DTMF */
240 if (*ptr == 'f' || *ptr == 'F') {
241 /* ignore return values if not supported by channel */
242 ast_indicate(chan, AST_CONTROL_FLASH);
243 } else {
244 f.subclass = *ptr;
245 if ((res = ast_write(chan, &f)))
246 break;
248 /* pause between digits */
249 if ((res = ast_safe_sleep(chan, between)))
250 break;
251 } else
252 ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n",*ptr);
255 if (peer) {
256 /* Stop autoservice on the peer channel, but don't overwrite any error condition
257 that has occurred previously while acting on the primary channel */
258 if (ast_autoservice_stop(peer) && !res)
259 res = -1;
262 return res;
265 struct linear_state {
266 int fd;
267 int autoclose;
268 int allowoverride;
269 int origwfmt;
272 static void linear_release(struct ast_channel *chan, void *params)
274 struct linear_state *ls = params;
275 if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt)) {
276 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", chan->name, ls->origwfmt);
278 if (ls->autoclose)
279 close(ls->fd);
280 free(params);
283 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
285 struct ast_frame f;
286 short buf[2048 + AST_FRIENDLY_OFFSET / 2];
287 struct linear_state *ls = data;
288 int res;
289 len = samples * 2;
290 if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
291 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" ,len);
292 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
294 memset(&f, 0, sizeof(f));
295 res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
296 if (res > 0) {
297 f.frametype = AST_FRAME_VOICE;
298 f.subclass = AST_FORMAT_SLINEAR;
299 f.data = buf + AST_FRIENDLY_OFFSET/2;
300 f.datalen = res;
301 f.samples = res / 2;
302 f.offset = AST_FRIENDLY_OFFSET;
303 ast_write(chan, &f);
304 if (res == len)
305 return 0;
307 return -1;
310 static void *linear_alloc(struct ast_channel *chan, void *params)
312 struct linear_state *ls;
313 /* In this case, params is already malloc'd */
314 if (params) {
315 ls = params;
316 if (ls->allowoverride)
317 ast_set_flag(chan, AST_FLAG_WRITE_INT);
318 else
319 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
320 ls->origwfmt = chan->writeformat;
321 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
322 ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", chan->name);
323 free(ls);
324 ls = params = NULL;
327 return params;
330 static struct ast_generator linearstream =
332 alloc: linear_alloc,
333 release: linear_release,
334 generate: linear_generator,
337 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
339 struct linear_state *lin;
340 char tmpf[256];
341 int res = -1;
342 int autoclose = 0;
343 if (fd < 0) {
344 if (ast_strlen_zero(filename))
345 return -1;
346 autoclose = 1;
347 if (filename[0] == '/')
348 ast_copy_string(tmpf, filename, sizeof(tmpf));
349 else
350 snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", (char *)ast_config_AST_DATA_DIR, "sounds", filename);
351 fd = open(tmpf, O_RDONLY);
352 if (fd < 0){
353 ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
354 return -1;
357 if ((lin = ast_calloc(1, sizeof(*lin)))) {
358 lin->fd = fd;
359 lin->allowoverride = allowoverride;
360 lin->autoclose = autoclose;
361 res = ast_activate_generator(chan, &linearstream, lin);
363 return res;
366 int ast_control_streamfile(struct ast_channel *chan, const char *file,
367 const char *fwd, const char *rev,
368 const char *stop, const char *pause,
369 const char *restart, int skipms)
371 char *breaks = NULL;
372 char *end = NULL;
373 int blen = 2;
374 int res;
375 long pause_restart_point = 0;
377 if (stop)
378 blen += strlen(stop);
379 if (pause)
380 blen += strlen(pause);
381 if (restart)
382 blen += strlen(restart);
384 if (blen > 2) {
385 breaks = alloca(blen + 1);
386 breaks[0] = '\0';
387 if (stop)
388 strcat(breaks, stop);
389 if (pause)
390 strcat(breaks, pause);
391 if (restart)
392 strcat(breaks, restart);
394 if (chan->_state != AST_STATE_UP)
395 res = ast_answer(chan);
397 if (file) {
398 if ((end = strchr(file,':'))) {
399 if (!strcasecmp(end, ":end")) {
400 *end = '\0';
401 end++;
406 for (;;) {
407 ast_stopstream(chan);
408 res = ast_streamfile(chan, file, chan->language);
409 if (!res) {
410 if (pause_restart_point) {
411 ast_seekstream(chan->stream, pause_restart_point, SEEK_SET);
412 pause_restart_point = 0;
414 else if (end) {
415 ast_seekstream(chan->stream, 0, SEEK_END);
416 end = NULL;
418 res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
421 if (res < 1)
422 break;
424 /* We go at next loop if we got the restart char */
425 if (restart && strchr(restart, res)) {
426 ast_log(LOG_DEBUG, "we'll restart the stream here at next loop\n");
427 pause_restart_point = 0;
428 continue;
431 if (pause && strchr(pause, res)) {
432 pause_restart_point = ast_tellstream(chan->stream);
433 for (;;) {
434 ast_stopstream(chan);
435 res = ast_waitfordigit(chan, 1000);
436 if (!res)
437 continue;
438 else if (res == -1 || strchr(pause, res) || (stop && strchr(stop, res)))
439 break;
441 if (res == *pause) {
442 res = 0;
443 continue;
447 if (res == -1)
448 break;
450 /* if we get one of our stop chars, return it to the calling function */
451 if (stop && strchr(stop, res))
452 break;
455 ast_stopstream(chan);
457 return res;
460 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
462 int d;
463 d = ast_streamfile(chan, fn, chan->language);
464 if (d)
465 return d;
466 d = ast_waitstream(chan, AST_DIGIT_ANY);
467 ast_stopstream(chan);
468 return d;
471 static int global_silence_threshold = 128;
472 static int global_maxsilence = 0;
474 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
475 * @param chan Channel to playback to/record from.
476 * @param playfile Filename of sound to play before recording begins.
477 * @param recordfile Filename to record to.
478 * @param maxtime Maximum length of recording (in milliseconds).
479 * @param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
480 * @param duration Where to store actual length of the recorded message (in milliseconds).
481 * @param beep Whether to play a beep before starting to record.
482 * @param silencethreshold
483 * @param maxsilence Length of silence that will end a recording (in milliseconds).
484 * @param path Optional filesystem path to unlock.
485 * @param prepend If true, prepend the recorded audio to an existing file.
486 * @param acceptdtmf DTMF digits that will end the recording.
487 * @param canceldtmf DTMF digits that will cancel the recording.
490 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)
492 int d = 0;
493 char *fmts;
494 char comment[256];
495 int x, fmtcnt = 1, res = -1, outmsg = 0;
496 struct ast_filestream *others[MAX_OTHER_FORMATS];
497 char *sfmt[MAX_OTHER_FORMATS];
498 char *stringp = NULL;
499 time_t start, end;
500 struct ast_dsp *sildet = NULL; /* silence detector dsp */
501 int totalsilence = 0;
502 int rfmt = 0;
503 struct ast_silence_generator *silgen = NULL;
504 char prependfile[80];
506 if (silencethreshold < 0)
507 silencethreshold = global_silence_threshold;
509 if (maxsilence < 0)
510 maxsilence = global_maxsilence;
512 /* barf if no pointer passed to store duration in */
513 if (duration == NULL) {
514 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
515 return -1;
518 ast_log(LOG_DEBUG,"play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
519 snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, chan->name);
521 if (playfile || beep) {
522 if (!beep)
523 d = ast_play_and_wait(chan, playfile);
524 if (d > -1)
525 d = ast_stream_and_wait(chan, "beep", chan->language, "");
526 if (d < 0)
527 return -1;
530 if (prepend) {
531 ast_copy_string(prependfile, recordfile, sizeof(prependfile));
532 strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
535 fmts = ast_strdupa(fmt);
537 stringp = fmts;
538 strsep(&stringp, "|");
539 ast_log(LOG_DEBUG, "Recording Formats: sfmts=%s\n", fmts);
540 sfmt[0] = ast_strdupa(fmts);
542 while ((fmt = strsep(&stringp, "|"))) {
543 if (fmtcnt > MAX_OTHER_FORMATS - 1) {
544 ast_log(LOG_WARNING, "Please increase MAX_OTHER_FORMATS in app.c\n");
545 break;
547 sfmt[fmtcnt++] = ast_strdupa(fmt);
550 end = start = time(NULL); /* pre-initialize end to be same as start in case we never get into loop */
551 for (x = 0; x < fmtcnt; x++) {
552 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, 0700);
553 if (option_verbose > 2)
554 ast_verbose(VERBOSE_PREFIX_3 "x=%d, open writing: %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
556 if (!others[x])
557 break;
560 if (path)
561 ast_unlock_path(path);
563 if (maxsilence > 0) {
564 sildet = ast_dsp_new(); /* Create the silence detector */
565 if (!sildet) {
566 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
567 return -1;
569 ast_dsp_set_threshold(sildet, silencethreshold);
570 rfmt = chan->readformat;
571 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
572 if (res < 0) {
573 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
574 ast_dsp_free(sildet);
575 return -1;
579 if (!prepend) {
580 /* Request a video update */
581 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
583 if (ast_opt_transmit_silence)
584 silgen = ast_channel_start_silence_generator(chan);
587 if (x == fmtcnt) {
588 /* Loop forever, writing the packets we read to the writer(s), until
589 we read a digit or get a hangup */
590 struct ast_frame *f;
591 for (;;) {
592 res = ast_waitfor(chan, 2000);
593 if (!res) {
594 ast_log(LOG_DEBUG, "One waitfor failed, trying another\n");
595 /* Try one more time in case of masq */
596 res = ast_waitfor(chan, 2000);
597 if (!res) {
598 ast_log(LOG_WARNING, "No audio available on %s??\n", chan->name);
599 res = -1;
603 if (res < 0) {
604 f = NULL;
605 break;
607 f = ast_read(chan);
608 if (!f)
609 break;
610 if (f->frametype == AST_FRAME_VOICE) {
611 /* write each format */
612 for (x = 0; x < fmtcnt; x++) {
613 if (prepend && !others[x])
614 break;
615 res = ast_writestream(others[x], f);
618 /* Silence Detection */
619 if (maxsilence > 0) {
620 int dspsilence = 0;
621 ast_dsp_silence(sildet, f, &dspsilence);
622 if (dspsilence)
623 totalsilence = dspsilence;
624 else
625 totalsilence = 0;
627 if (totalsilence > maxsilence) {
628 /* Ended happily with silence */
629 if (option_verbose > 2)
630 ast_verbose( VERBOSE_PREFIX_3 "Recording automatically stopped after a silence of %d seconds\n", totalsilence/1000);
631 res = 'S';
632 outmsg = 2;
633 break;
636 /* Exit on any error */
637 if (res) {
638 ast_log(LOG_WARNING, "Error writing frame\n");
639 break;
641 } else if (f->frametype == AST_FRAME_VIDEO) {
642 /* Write only once */
643 ast_writestream(others[0], f);
644 } else if (f->frametype == AST_FRAME_DTMF) {
645 if (prepend) {
646 /* stop recording with any digit */
647 if (option_verbose > 2)
648 ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
649 res = 't';
650 outmsg = 2;
651 break;
653 if (strchr(acceptdtmf, f->subclass)) {
654 if (option_verbose > 2)
655 ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
656 res = f->subclass;
657 outmsg = 2;
658 break;
660 if (strchr(canceldtmf, f->subclass)) {
661 if (option_verbose > 2)
662 ast_verbose(VERBOSE_PREFIX_3 "User cancelled message by pressing %c\n", f->subclass);
663 res = f->subclass;
664 outmsg = 0;
665 break;
668 if (maxtime) {
669 end = time(NULL);
670 if (maxtime < (end - start)) {
671 if (option_verbose > 2)
672 ast_verbose(VERBOSE_PREFIX_3 "Took too long, cutting it short...\n");
673 res = 't';
674 outmsg = 2;
675 break;
678 ast_frfree(f);
680 if (!f) {
681 if (option_verbose > 2)
682 ast_verbose(VERBOSE_PREFIX_3 "User hung up\n");
683 res = -1;
684 outmsg = 1;
685 } else {
686 ast_frfree(f);
688 if (end == start)
689 end = time(NULL);
690 } else {
691 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
694 if (!prepend) {
695 if (silgen)
696 ast_channel_stop_silence_generator(chan, silgen);
698 *duration = end - start;
700 if (!prepend) {
701 for (x = 0; x < fmtcnt; x++) {
702 if (!others[x])
703 break;
704 if (res > 0)
705 ast_stream_rewind(others[x], totalsilence ? totalsilence - 200 : 200);
706 ast_truncstream(others[x]);
707 ast_closestream(others[x]);
711 if (prepend && outmsg) {
712 struct ast_filestream *realfiles[MAX_OTHER_FORMATS];
713 struct ast_frame *fr;
715 for (x = 0; x < fmtcnt; x++) {
716 snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
717 realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
718 if (!others[x] || !realfiles[x])
719 break;
720 ast_stream_rewind(others[x], totalsilence ? totalsilence - 200 : 200);
721 ast_truncstream(others[x]);
722 /* add the original file too */
723 while ((fr = ast_readframe(realfiles[x]))) {
724 ast_writestream(others[x], fr);
725 ast_frfree(fr);
727 ast_closestream(others[x]);
728 ast_closestream(realfiles[x]);
729 ast_filerename(prependfile, recordfile, sfmt[x]);
730 if (option_verbose > 3)
731 ast_verbose(VERBOSE_PREFIX_4 "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
732 ast_filedelete(prependfile, sfmt[x]);
735 if (rfmt && ast_set_read_format(chan, rfmt)) {
736 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(rfmt), chan->name);
738 if (outmsg == 2) {
739 ast_stream_and_wait(chan, "auth-thankyou", chan->language, "");
741 if (sildet)
742 ast_dsp_free(sildet);
743 return res;
746 static char default_acceptdtmf[] = "#";
747 static char default_canceldtmf[] = "";
749 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)
751 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));
754 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)
756 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf);
759 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)
761 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf);
764 /* Channel group core functions */
766 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
768 int res=0;
769 char tmp[256];
770 char *grp=NULL, *cat=NULL;
772 if (!ast_strlen_zero(data)) {
773 ast_copy_string(tmp, data, sizeof(tmp));
774 grp = tmp;
775 cat = strchr(tmp, '@');
776 if (cat) {
777 *cat = '\0';
778 cat++;
782 if (!ast_strlen_zero(grp))
783 ast_copy_string(group, grp, group_max);
784 else
785 res = -1;
787 if (cat)
788 snprintf(category, category_max, "%s_%s", GROUP_CATEGORY_PREFIX, cat);
789 else
790 ast_copy_string(category, GROUP_CATEGORY_PREFIX, category_max);
792 return res;
795 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
797 int res=0;
798 char group[80] = "";
799 char category[80] = "";
801 if (!ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
802 pbx_builtin_setvar_helper(chan, category, group);
803 } else
804 res = -1;
806 return res;
809 int ast_app_group_get_count(const char *group, const char *category)
811 struct ast_channel *chan;
812 int count = 0;
813 const char *test;
814 char cat[80];
815 const char *s;
817 if (ast_strlen_zero(group))
818 return 0;
820 s = S_OR(category, GROUP_CATEGORY_PREFIX);
821 ast_copy_string(cat, s, sizeof(cat));
823 chan = NULL;
824 while ((chan = ast_channel_walk_locked(chan)) != NULL) {
825 test = pbx_builtin_getvar_helper(chan, cat);
826 if (test && !strcasecmp(test, group))
827 count++;
828 ast_channel_unlock(chan);
831 return count;
834 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
836 regex_t regexbuf;
837 struct ast_channel *chan;
838 int count = 0;
839 const char *test;
840 char cat[80];
841 const char *s;
843 if (ast_strlen_zero(groupmatch))
844 return 0;
846 /* if regex compilation fails, return zero matches */
847 if (regcomp(&regexbuf, groupmatch, REG_EXTENDED | REG_NOSUB))
848 return 0;
850 s = S_OR(category, GROUP_CATEGORY_PREFIX);
851 ast_copy_string(cat, s, sizeof(cat));
853 chan = NULL;
854 while ((chan = ast_channel_walk_locked(chan)) != NULL) {
855 test = pbx_builtin_getvar_helper(chan, cat);
856 if (test && !regexec(&regexbuf, test, 0, NULL, 0))
857 count++;
858 ast_channel_unlock(chan);
861 regfree(&regexbuf);
863 return count;
866 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
868 int argc;
869 char *scan;
870 int paren = 0, quote = 0;
872 if (!buf || !array || !arraylen)
873 return 0;
875 memset(array, 0, arraylen * sizeof(*array));
877 scan = buf;
879 for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
880 array[argc] = scan;
881 for (; *scan; scan++) {
882 if (*scan == '(')
883 paren++;
884 else if (*scan == ')') {
885 if (paren)
886 paren--;
887 } else if (*scan == '"') {
888 quote = quote ? 0 : 1;
889 /* Remove quote character from argument */
890 memmove(scan, scan + 1, strlen(scan));
891 scan--;
892 } else if (*scan == '\\') {
893 /* Literal character, don't parse */
894 memmove(scan, scan + 1, strlen(scan));
895 } else if ((*scan == delim) && !paren && !quote) {
896 *scan++ = '\0';
897 break;
902 if (*scan)
903 array[argc++] = scan;
905 return argc;
908 enum AST_LOCK_RESULT ast_lock_path(const char *path)
910 char *s;
911 char *fs;
912 int res;
913 int fd;
914 int lp = strlen(path);
915 time_t start;
917 if (!(s = alloca(lp + 10)) || !(fs = alloca(lp + 20))) {
918 ast_log(LOG_WARNING, "Out of memory!\n");
919 return AST_LOCK_FAILURE;
922 snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
923 fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, 0600);
924 if (fd < 0) {
925 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
926 return AST_LOCK_PATH_NOT_FOUND;
928 close(fd);
930 snprintf(s, strlen(path) + 9, "%s/.lock", path);
931 start = time(NULL);
932 while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5))
933 usleep(1);
935 unlink(fs);
937 if (res) {
938 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
939 return AST_LOCK_TIMEOUT;
940 } else {
941 ast_log(LOG_DEBUG, "Locked path '%s'\n", path);
942 return AST_LOCK_SUCCESS;
946 int ast_unlock_path(const char *path)
948 char *s;
949 int res;
951 if (!(s = alloca(strlen(path) + 10))) {
952 ast_log(LOG_WARNING, "Out of memory!\n");
953 return -1;
956 snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
958 if ((res = unlink(s)))
959 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
960 else
961 ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
963 return res;
966 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
968 int silencethreshold = 128;
969 int maxsilence=0;
970 int res = 0;
971 int cmd = 0;
972 int max_attempts = 3;
973 int attempts = 0;
974 int recorded = 0;
975 int message_exists = 0;
976 /* Note that urgent and private are for flagging messages as such in the future */
978 /* barf if no pointer passed to store duration in */
979 if (duration == NULL) {
980 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
981 return -1;
984 cmd = '3'; /* Want to start by recording */
986 while ((cmd >= 0) && (cmd != 't')) {
987 switch (cmd) {
988 case '1':
989 if (!message_exists) {
990 /* In this case, 1 is to record a message */
991 cmd = '3';
992 break;
993 } else {
994 ast_stream_and_wait(chan, "vm-msgsaved", chan->language, "");
995 cmd = 't';
996 return res;
998 case '2':
999 /* Review */
1000 ast_verbose(VERBOSE_PREFIX_3 "Reviewing the recording\n");
1001 cmd = ast_stream_and_wait(chan, recordfile, chan->language, AST_DIGIT_ANY);
1002 break;
1003 case '3':
1004 message_exists = 0;
1005 /* Record */
1006 if (recorded == 1)
1007 ast_verbose(VERBOSE_PREFIX_3 "Re-recording\n");
1008 else
1009 ast_verbose(VERBOSE_PREFIX_3 "Recording\n");
1010 recorded = 1;
1011 cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path);
1012 if (cmd == -1) {
1013 /* User has hung up, no options to give */
1014 return cmd;
1016 if (cmd == '0') {
1017 break;
1018 } else if (cmd == '*') {
1019 break;
1021 else {
1022 /* If all is well, a message exists */
1023 message_exists = 1;
1024 cmd = 0;
1026 break;
1027 case '4':
1028 case '5':
1029 case '6':
1030 case '7':
1031 case '8':
1032 case '9':
1033 case '*':
1034 case '#':
1035 cmd = ast_play_and_wait(chan, "vm-sorry");
1036 break;
1037 default:
1038 if (message_exists) {
1039 cmd = ast_play_and_wait(chan, "vm-review");
1041 else {
1042 cmd = ast_play_and_wait(chan, "vm-torerecord");
1043 if (!cmd)
1044 cmd = ast_waitfordigit(chan, 600);
1047 if (!cmd)
1048 cmd = ast_waitfordigit(chan, 6000);
1049 if (!cmd) {
1050 attempts++;
1052 if (attempts > max_attempts) {
1053 cmd = 't';
1057 if (cmd == 't')
1058 cmd = 0;
1059 return cmd;
1062 #define RES_UPONE (1 << 16)
1063 #define RES_EXIT (1 << 17)
1064 #define RES_REPEAT (1 << 18)
1065 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1067 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1069 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1071 int res;
1072 int (*ivr_func)(struct ast_channel *, void *);
1073 char *c;
1074 char *n;
1076 switch(option->action) {
1077 case AST_ACTION_UPONE:
1078 return RES_UPONE;
1079 case AST_ACTION_EXIT:
1080 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1081 case AST_ACTION_REPEAT:
1082 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1083 case AST_ACTION_RESTART:
1084 return RES_RESTART ;
1085 case AST_ACTION_NOOP:
1086 return 0;
1087 case AST_ACTION_BACKGROUND:
1088 res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, AST_DIGIT_ANY);
1089 if (res < 0) {
1090 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1091 res = 0;
1093 return res;
1094 case AST_ACTION_PLAYBACK:
1095 res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, "");
1096 if (res < 0) {
1097 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1098 res = 0;
1100 return res;
1101 case AST_ACTION_MENU:
1102 res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata);
1103 /* Do not pass entry errors back up, treaat ast though ti was an "UPONE" */
1104 if (res == -2)
1105 res = 0;
1106 return res;
1107 case AST_ACTION_WAITOPTION:
1108 res = ast_waitfordigit(chan, 1000 * (chan->pbx ? chan->pbx->rtimeout : 10));
1109 if (!res)
1110 return 't';
1111 return res;
1112 case AST_ACTION_CALLBACK:
1113 ivr_func = option->adata;
1114 res = ivr_func(chan, cbdata);
1115 return res;
1116 case AST_ACTION_TRANSFER:
1117 res = ast_parseable_goto(chan, option->adata);
1118 return 0;
1119 case AST_ACTION_PLAYLIST:
1120 case AST_ACTION_BACKLIST:
1121 res = 0;
1122 c = ast_strdupa(option->adata);
1123 while ((n = strsep(&c, ";"))) {
1124 if ((res = ast_stream_and_wait(chan, n, chan->language,
1125 (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : "")))
1126 break;
1128 ast_stopstream(chan);
1129 return res;
1130 default:
1131 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1132 return 0;
1134 return -1;
1137 static int option_exists(struct ast_ivr_menu *menu, char *option)
1139 int x;
1140 for (x = 0; menu->options[x].option; x++)
1141 if (!strcasecmp(menu->options[x].option, option))
1142 return x;
1143 return -1;
1146 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1148 int x;
1149 for (x = 0; menu->options[x].option; x++)
1150 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
1151 (menu->options[x].option[strlen(option)]))
1152 return x;
1153 return -1;
1156 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1158 int res=0;
1159 int ms;
1160 while (option_matchmore(menu, exten)) {
1161 ms = chan->pbx ? chan->pbx->dtimeout : 5000;
1162 if (strlen(exten) >= maxexten - 1)
1163 break;
1164 res = ast_waitfordigit(chan, ms);
1165 if (res < 1)
1166 break;
1167 exten[strlen(exten) + 1] = '\0';
1168 exten[strlen(exten)] = res;
1170 return res > 0 ? 0 : res;
1173 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1175 /* Execute an IVR menu structure */
1176 int res=0;
1177 int pos = 0;
1178 int retries = 0;
1179 char exten[AST_MAX_EXTENSION] = "s";
1180 if (option_exists(menu, "s") < 0) {
1181 strcpy(exten, "g");
1182 if (option_exists(menu, "g") < 0) {
1183 ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1184 return -1;
1187 while(!res) {
1188 while(menu->options[pos].option) {
1189 if (!strcasecmp(menu->options[pos].option, exten)) {
1190 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1191 ast_log(LOG_DEBUG, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1192 if (res < 0)
1193 break;
1194 else if (res & RES_UPONE)
1195 return 0;
1196 else if (res & RES_EXIT)
1197 return res;
1198 else if (res & RES_REPEAT) {
1199 int maxretries = res & 0xffff;
1200 if ((res & RES_RESTART) == RES_RESTART) {
1201 retries = 0;
1202 } else
1203 retries++;
1204 if (!maxretries)
1205 maxretries = 3;
1206 if ((maxretries > 0) && (retries >= maxretries)) {
1207 ast_log(LOG_DEBUG, "Max retries %d exceeded\n", maxretries);
1208 return -2;
1209 } else {
1210 if (option_exists(menu, "g") > -1)
1211 strcpy(exten, "g");
1212 else if (option_exists(menu, "s") > -1)
1213 strcpy(exten, "s");
1215 pos = 0;
1216 continue;
1217 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1218 ast_log(LOG_DEBUG, "Got start of extension, %c\n", res);
1219 exten[1] = '\0';
1220 exten[0] = res;
1221 if ((res = read_newoption(chan, menu, exten, sizeof(exten))))
1222 break;
1223 if (option_exists(menu, exten) < 0) {
1224 if (option_exists(menu, "i")) {
1225 ast_log(LOG_DEBUG, "Invalid extension entered, going to 'i'!\n");
1226 strcpy(exten, "i");
1227 pos = 0;
1228 continue;
1229 } else {
1230 ast_log(LOG_DEBUG, "Aborting on invalid entry, with no 'i' option!\n");
1231 res = -2;
1232 break;
1234 } else {
1235 ast_log(LOG_DEBUG, "New existing extension: %s\n", exten);
1236 pos = 0;
1237 continue;
1241 pos++;
1243 ast_log(LOG_DEBUG, "Stopping option '%s', res is %d\n", exten, res);
1244 pos = 0;
1245 if (!strcasecmp(exten, "s"))
1246 strcpy(exten, "g");
1247 else
1248 break;
1250 return res;
1253 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1255 int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1256 /* Hide internal coding */
1257 return res > 0 ? 0 : res;
1260 char *ast_read_textfile(const char *filename)
1262 int fd;
1263 char *output = NULL;
1264 struct stat filesize;
1265 int count = 0;
1266 int res;
1267 if (stat(filename, &filesize) == -1) {
1268 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
1269 return NULL;
1271 count = filesize.st_size + 1;
1272 fd = open(filename, O_RDONLY);
1273 if (fd < 0) {
1274 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1275 return NULL;
1277 if ((output = ast_malloc(count))) {
1278 res = read(fd, output, count - 1);
1279 if (res == count - 1) {
1280 output[res] = '\0';
1281 } else {
1282 ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
1283 free(output);
1284 output = NULL;
1287 close(fd);
1288 return output;
1291 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
1293 char *s;
1294 int curarg;
1295 unsigned int argloc;
1296 char *arg;
1297 int res = 0;
1299 ast_clear_flag(flags, AST_FLAGS_ALL);
1301 if (!optstr)
1302 return 0;
1304 s = optstr;
1305 while (*s) {
1306 curarg = *s++ & 0x7f; /* the array (in app.h) has 128 entries */
1307 ast_set_flag(flags, options[curarg].flag);
1308 argloc = options[curarg].arg_index;
1309 if (*s == '(') {
1310 /* Has argument */
1311 arg = ++s;
1312 s = strchr(s, ')');
1313 if (*s) {
1314 if (argloc)
1315 args[argloc - 1] = arg;
1316 *s++ = '\0';
1317 } else {
1318 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
1319 res = -1;
1321 } else if (argloc) {
1322 args[argloc - 1] = NULL;
1326 return res;