officially deprecate the 'roundrobin' queue strategy in favor of 'rrmemory'
[asterisk-bristuff.git] / app.c
blobe05d9d4714c56aa9f928d6827dd6dbf83a949da8
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 <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/time.h>
30 #include <signal.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <dirent.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <regex.h>
38 #include "asterisk.h"
40 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
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;
104 /*! \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for
105 "ludicrous time" (essentially never times out) */
106 int ast_app_getdata(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout)
108 int res,to,fto;
109 /* XXX Merge with full version? XXX */
110 if (maxlen)
111 s[0] = '\0';
112 if (prompt) {
113 res = ast_streamfile(c, prompt, c->language);
114 if (res < 0)
115 return res;
117 fto = c->pbx ? c->pbx->rtimeout * 1000 : 6000;
118 to = c->pbx ? c->pbx->dtimeout * 1000 : 2000;
120 if (timeout > 0)
121 fto = to = timeout;
122 if (timeout < 0)
123 fto = to = 1000000000;
124 res = ast_readstring(c, s, maxlen, to, fto, "#");
125 return res;
129 int ast_app_getdata_full(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
131 int res,to,fto;
132 if (prompt) {
133 res = ast_streamfile(c, prompt, c->language);
134 if (res < 0)
135 return res;
137 fto = 6000;
138 to = 2000;
139 if (timeout > 0)
140 fto = to = timeout;
141 if (timeout < 0)
142 fto = to = 1000000000;
143 res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
144 return res;
147 static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
148 static int (*ast_inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
149 static int (*ast_messagecount_func)(const char *context, const char *mailbox, const char *folder) = NULL;
151 void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
152 int (*inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs),
153 int (*messagecount_func)(const char *context, const char *mailbox, const char *folder))
155 ast_has_voicemail_func = has_voicemail_func;
156 ast_inboxcount_func = inboxcount_func;
157 ast_messagecount_func = messagecount_func;
160 void ast_uninstall_vm_functions(void)
162 ast_has_voicemail_func = NULL;
163 ast_inboxcount_func = NULL;
164 ast_messagecount_func = NULL;
167 int ast_app_has_voicemail(const char *mailbox, const char *folder)
169 static int warned = 0;
170 if (ast_has_voicemail_func)
171 return ast_has_voicemail_func(mailbox, folder);
173 if ((option_verbose > 2) && !warned) {
174 ast_verbose(VERBOSE_PREFIX_3 "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
175 warned++;
177 return 0;
181 int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
183 static int warned = 0;
184 if (newmsgs)
185 *newmsgs = 0;
186 if (oldmsgs)
187 *oldmsgs = 0;
188 if (ast_inboxcount_func)
189 return ast_inboxcount_func(mailbox, newmsgs, oldmsgs);
191 if (!warned && (option_verbose > 2)) {
192 warned++;
193 ast_verbose(VERBOSE_PREFIX_3 "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
196 return 0;
199 int ast_app_messagecount(const char *context, const char *mailbox, const char *folder)
201 static int warned = 0;
202 if (ast_messagecount_func)
203 return ast_messagecount_func(context, mailbox, folder);
205 if (!warned && (option_verbose > 2)) {
206 warned++;
207 ast_verbose(VERBOSE_PREFIX_3 "Message count requested for mailbox %s@%s/%s but voicemail not loaded.\n", mailbox, context, folder);
210 return 0;
213 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between)
215 const char *ptr;
216 int res = 0;
217 struct ast_frame f = {
218 .frametype = AST_FRAME_DTMF,
219 .src = "ast_dtmf_stream"
222 if (!between)
223 between = 100;
225 if (peer)
226 res = ast_autoservice_start(peer);
228 if (!res)
229 res = ast_waitfor(chan, 100);
231 /* ast_waitfor will return the number of remaining ms on success */
232 if (res < 0)
233 return res;
235 for (ptr = digits; *ptr; ptr++) {
236 if (*ptr == 'w') {
237 /* 'w' -- wait half a second */
238 if ((res = ast_safe_sleep(chan, 500)))
239 break;
240 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
241 /* Character represents valid DTMF */
242 if (*ptr == 'f' || *ptr == 'F') {
243 /* ignore return values if not supported by channel */
244 ast_indicate(chan, AST_CONTROL_FLASH);
245 } else {
246 f.subclass = *ptr;
247 if ((res = ast_write(chan, &f)))
248 break;
250 /* pause between digits */
251 if ((res = ast_safe_sleep(chan, between)))
252 break;
253 } else
254 ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n",*ptr);
257 if (peer) {
258 /* Stop autoservice on the peer channel, but don't overwrite any error condition
259 that has occurred previously while acting on the primary channel */
260 if (ast_autoservice_stop(peer) && !res)
261 res = -1;
264 return res;
267 struct linear_state {
268 int fd;
269 int autoclose;
270 int allowoverride;
271 int origwfmt;
274 static void linear_release(struct ast_channel *chan, void *params)
276 struct linear_state *ls = params;
277 if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt)) {
278 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", chan->name, ls->origwfmt);
280 if (ls->autoclose)
281 close(ls->fd);
282 free(params);
285 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
287 struct ast_frame f;
288 short buf[2048 + AST_FRIENDLY_OFFSET / 2];
289 struct linear_state *ls = data;
290 int res;
291 len = samples * 2;
292 if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
293 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" ,len);
294 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
296 memset(&f, 0, sizeof(f));
297 res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
298 if (res > 0) {
299 f.frametype = AST_FRAME_VOICE;
300 f.subclass = AST_FORMAT_SLINEAR;
301 f.data = buf + AST_FRIENDLY_OFFSET/2;
302 f.datalen = res;
303 f.samples = res / 2;
304 f.offset = AST_FRIENDLY_OFFSET;
305 ast_write(chan, &f);
306 if (res == len)
307 return 0;
309 return -1;
312 static void *linear_alloc(struct ast_channel *chan, void *params)
314 struct linear_state *ls;
315 /* In this case, params is already malloc'd */
316 if (params) {
317 ls = params;
318 if (ls->allowoverride)
319 ast_set_flag(chan, AST_FLAG_WRITE_INT);
320 else
321 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
322 ls->origwfmt = chan->writeformat;
323 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
324 ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", chan->name);
325 free(ls);
326 ls = params = NULL;
329 return params;
332 static struct ast_generator linearstream =
334 alloc: linear_alloc,
335 release: linear_release,
336 generate: linear_generator,
339 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
341 struct linear_state *lin;
342 char tmpf[256];
343 int res = -1;
344 int autoclose = 0;
345 if (fd < 0) {
346 if (ast_strlen_zero(filename))
347 return -1;
348 autoclose = 1;
349 if (filename[0] == '/')
350 ast_copy_string(tmpf, filename, sizeof(tmpf));
351 else
352 snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", (char *)ast_config_AST_DATA_DIR, "sounds", filename);
353 fd = open(tmpf, O_RDONLY);
354 if (fd < 0){
355 ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
356 return -1;
359 if ((lin = ast_calloc(1, sizeof(*lin)))) {
360 lin->fd = fd;
361 lin->allowoverride = allowoverride;
362 lin->autoclose = autoclose;
363 res = ast_activate_generator(chan, &linearstream, lin);
365 return res;
368 int ast_control_streamfile(struct ast_channel *chan, const char *file,
369 const char *fwd, const char *rev,
370 const char *stop, const char *pause,
371 const char *restart, int skipms)
373 char *breaks = NULL;
374 char *end = NULL;
375 int blen = 2;
376 int res;
377 long pause_restart_point = 0;
379 if (stop)
380 blen += strlen(stop);
381 if (pause)
382 blen += strlen(pause);
383 if (restart)
384 blen += strlen(restart);
386 if (blen > 2) {
387 breaks = alloca(blen + 1);
388 breaks[0] = '\0';
389 if (stop)
390 strcat(breaks, stop);
391 if (pause)
392 strcat(breaks, pause);
393 if (restart)
394 strcat(breaks, restart);
396 if (chan->_state != AST_STATE_UP)
397 res = ast_answer(chan);
399 if (file) {
400 if ((end = strchr(file,':'))) {
401 if (!strcasecmp(end, ":end")) {
402 *end = '\0';
403 end++;
408 for (;;) {
409 ast_stopstream(chan);
410 res = ast_streamfile(chan, file, chan->language);
411 if (!res) {
412 if (pause_restart_point) {
413 ast_seekstream(chan->stream, pause_restart_point, SEEK_SET);
414 pause_restart_point = 0;
416 else if (end) {
417 ast_seekstream(chan->stream, 0, SEEK_END);
418 end = NULL;
420 res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
423 if (res < 1)
424 break;
426 /* We go at next loop if we got the restart char */
427 if (restart && strchr(restart, res)) {
428 ast_log(LOG_DEBUG, "we'll restart the stream here at next loop\n");
429 pause_restart_point = 0;
430 continue;
433 if (pause && strchr(pause, res)) {
434 pause_restart_point = ast_tellstream(chan->stream);
435 for (;;) {
436 ast_stopstream(chan);
437 res = ast_waitfordigit(chan, 1000);
438 if (!res)
439 continue;
440 else if (res == -1 || strchr(pause, res) || (stop && strchr(stop, res)))
441 break;
443 if (res == *pause) {
444 res = 0;
445 continue;
449 if (res == -1)
450 break;
452 /* if we get one of our stop chars, return it to the calling function */
453 if (stop && strchr(stop, res))
454 break;
457 ast_stopstream(chan);
459 return res;
462 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
464 int d;
465 d = ast_streamfile(chan, fn, chan->language);
466 if (d)
467 return d;
468 d = ast_waitstream(chan, AST_DIGIT_ANY);
469 ast_stopstream(chan);
470 return d;
473 static int global_silence_threshold = 128;
474 static int global_maxsilence = 0;
476 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
477 * @param chan Channel to playback to/record from.
478 * @param playfile Filename of sound to play before recording begins.
479 * @param recordfile Filename to record to.
480 * @param maxtime Maximum length of recording (in milliseconds).
481 * @param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
482 * @param duration Where to store actual length of the recorded message (in milliseconds).
483 * @param beep Whether to play a beep before starting to record.
484 * @param silencethreshold
485 * @param maxsilence Length of silence that will end a recording (in milliseconds).
486 * @param path Optional filesystem path to unlock.
487 * @param prepend If true, prepend the recorded audio to an existing file.
488 * @param acceptdtmf DTMF digits that will end the recording.
489 * @param canceldtmf DTMF digits that will cancel the recording.
492 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)
494 int d = 0;
495 char *fmts;
496 char comment[256];
497 int x, fmtcnt = 1, res = -1, outmsg = 0;
498 struct ast_filestream *others[MAX_OTHER_FORMATS];
499 char *sfmt[MAX_OTHER_FORMATS];
500 char *stringp = NULL;
501 time_t start, end;
502 struct ast_dsp *sildet = NULL; /* silence detector dsp */
503 int totalsilence = 0;
504 int rfmt = 0;
505 struct ast_silence_generator *silgen = NULL;
506 char prependfile[80];
508 if (silencethreshold < 0)
509 silencethreshold = global_silence_threshold;
511 if (maxsilence < 0)
512 maxsilence = global_maxsilence;
514 /* barf if no pointer passed to store duration in */
515 if (duration == NULL) {
516 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
517 return -1;
520 ast_log(LOG_DEBUG,"play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
521 snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, chan->name);
523 if (playfile || beep) {
524 if (!beep)
525 d = ast_play_and_wait(chan, playfile);
526 if (d > -1)
527 d = ast_stream_and_wait(chan, "beep", chan->language, "");
528 if (d < 0)
529 return -1;
532 if (prepend) {
533 ast_copy_string(prependfile, recordfile, sizeof(prependfile));
534 strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
537 fmts = ast_strdupa(fmt);
539 stringp = fmts;
540 strsep(&stringp, "|");
541 ast_log(LOG_DEBUG,"Recording Formats: sfmts=%s\n", fmts);
542 sfmt[0] = ast_strdupa(fmts);
544 while ((fmt = strsep(&stringp, "|"))) {
545 if (fmtcnt > MAX_OTHER_FORMATS - 1) {
546 ast_log(LOG_WARNING, "Please increase MAX_OTHER_FORMATS in app.c\n");
547 break;
549 sfmt[fmtcnt++] = ast_strdupa(fmt);
552 end = start = time(NULL); /* pre-initialize end to be same as start in case we never get into loop */
553 for (x = 0; x < fmtcnt; x++) {
554 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, 0700);
555 if (option_verbose > 2)
556 ast_verbose(VERBOSE_PREFIX_3 "x=%d, open writing: %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
558 if (!others[x]) {
559 break;
563 if (path)
564 ast_unlock_path(path);
566 if (maxsilence > 0) {
567 sildet = ast_dsp_new(); /* Create the silence detector */
568 if (!sildet) {
569 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
570 return -1;
572 ast_dsp_set_threshold(sildet, silencethreshold);
573 rfmt = chan->readformat;
574 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
575 if (res < 0) {
576 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
577 ast_dsp_free(sildet);
578 return -1;
582 if (!prepend) {
583 /* Request a video update */
584 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
586 if (ast_opt_transmit_silence)
587 silgen = ast_channel_start_silence_generator(chan);
590 if (x == fmtcnt) {
591 /* Loop forever, writing the packets we read to the writer(s), until
592 we read a digit or get a hangup */
593 struct ast_frame *f;
594 for (;;) {
595 res = ast_waitfor(chan, 2000);
596 if (!res) {
597 ast_log(LOG_DEBUG, "One waitfor failed, trying another\n");
598 /* Try one more time in case of masq */
599 res = ast_waitfor(chan, 2000);
600 if (!res) {
601 ast_log(LOG_WARNING, "No audio available on %s??\n", chan->name);
602 res = -1;
606 if (res < 0) {
607 f = NULL;
608 break;
610 f = ast_read(chan);
611 if (!f)
612 break;
613 if (f->frametype == AST_FRAME_VOICE) {
614 /* write each format */
615 for (x = 0; x < fmtcnt; x++) {
616 if (prepend && !others[x])
617 break;
618 res = ast_writestream(others[x], f);
621 /* Silence Detection */
622 if (maxsilence > 0) {
623 int dspsilence = 0;
624 ast_dsp_silence(sildet, f, &dspsilence);
625 if (dspsilence)
626 totalsilence = dspsilence;
627 else
628 totalsilence = 0;
630 if (totalsilence > maxsilence) {
631 /* Ended happily with silence */
632 if (option_verbose > 2)
633 ast_verbose( VERBOSE_PREFIX_3 "Recording automatically stopped after a silence of %d seconds\n", totalsilence/1000);
634 res = 'S';
635 outmsg = 2;
636 break;
639 /* Exit on any error */
640 if (res) {
641 ast_log(LOG_WARNING, "Error writing frame\n");
642 break;
644 } else if (f->frametype == AST_FRAME_VIDEO) {
645 /* Write only once */
646 ast_writestream(others[0], f);
647 } else if (f->frametype == AST_FRAME_DTMF) {
648 if (prepend) {
649 /* stop recording with any digit */
650 if (option_verbose > 2)
651 ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
652 res = 't';
653 outmsg = 2;
654 break;
656 if (strchr(acceptdtmf, f->subclass)) {
657 if (option_verbose > 2)
658 ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
659 res = f->subclass;
660 outmsg = 2;
661 break;
663 if (strchr(canceldtmf, f->subclass)) {
664 if (option_verbose > 2)
665 ast_verbose(VERBOSE_PREFIX_3 "User cancelled message by pressing %c\n", f->subclass);
666 res = f->subclass;
667 outmsg = 0;
668 break;
671 if (maxtime) {
672 end = time(NULL);
673 if (maxtime < (end - start)) {
674 if (option_verbose > 2)
675 ast_verbose(VERBOSE_PREFIX_3 "Took too long, cutting it short...\n");
676 res = 't';
677 outmsg = 2;
678 break;
681 ast_frfree(f);
683 if (!f) {
684 if (option_verbose > 2)
685 ast_verbose(VERBOSE_PREFIX_3 "User hung up\n");
686 res = -1;
687 outmsg = 1;
688 } else {
689 ast_frfree(f);
691 if (end == start)
692 end = time(NULL);
693 } else {
694 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
697 if (!prepend) {
698 if (silgen)
699 ast_channel_stop_silence_generator(chan, silgen);
701 *duration = end - start;
703 if (!prepend) {
704 for (x = 0; x < fmtcnt; x++) {
705 if (!others[x])
706 break;
707 if (res > 0)
708 ast_stream_rewind(others[x], totalsilence ? totalsilence-200 : 200);
709 ast_truncstream(others[x]);
710 ast_closestream(others[x]);
714 if (prepend && outmsg) {
715 struct ast_filestream *realfiles[MAX_OTHER_FORMATS];
716 struct ast_frame *fr;
718 for (x = 0; x < fmtcnt; x++) {
719 snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
720 realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
721 if (!others[x] || !realfiles[x])
722 break;
723 ast_stream_rewind(others[x], totalsilence ? totalsilence-200 : 200);
724 ast_truncstream(others[x]);
725 /* add the original file too */
726 while ((fr = ast_readframe(realfiles[x]))) {
727 ast_writestream(others[x], fr);
728 ast_frfree(fr);
730 ast_closestream(others[x]);
731 ast_closestream(realfiles[x]);
732 ast_filerename(prependfile, recordfile, sfmt[x]);
733 if (option_verbose > 3)
734 ast_verbose(VERBOSE_PREFIX_4 "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
735 ast_filedelete(prependfile, sfmt[x]);
738 if (rfmt && ast_set_read_format(chan, rfmt)) {
739 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(rfmt), chan->name);
741 if (outmsg == 2) {
742 ast_stream_and_wait(chan, "auth-thankyou", chan->language, "");
744 if (sildet)
745 ast_dsp_free(sildet);
746 return res;
749 static char default_acceptdtmf[] = "#";
750 static char default_canceldtmf[] = "";
752 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)
754 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));
757 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)
759 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf);
762 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)
764 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf);
767 /* Channel group core functions */
769 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
771 int res=0;
772 char tmp[256];
773 char *grp=NULL, *cat=NULL;
775 if (!ast_strlen_zero(data)) {
776 ast_copy_string(tmp, data, sizeof(tmp));
777 grp = tmp;
778 cat = strchr(tmp, '@');
779 if (cat) {
780 *cat = '\0';
781 cat++;
785 if (!ast_strlen_zero(grp))
786 ast_copy_string(group, grp, group_max);
787 else
788 res = -1;
790 if (cat)
791 snprintf(category, category_max, "%s_%s", GROUP_CATEGORY_PREFIX, cat);
792 else
793 ast_copy_string(category, GROUP_CATEGORY_PREFIX, category_max);
795 return res;
798 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
800 int res=0;
801 char group[80] = "";
802 char category[80] = "";
804 if (!ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
805 pbx_builtin_setvar_helper(chan, category, group);
806 } else
807 res = -1;
809 return res;
812 int ast_app_group_get_count(const char *group, const char *category)
814 struct ast_channel *chan;
815 int count = 0;
816 const char *test;
817 char cat[80];
818 const char *s;
820 if (ast_strlen_zero(group))
821 return 0;
823 s = S_OR(category, GROUP_CATEGORY_PREFIX);
824 ast_copy_string(cat, s, sizeof(cat));
826 chan = NULL;
827 while ((chan = ast_channel_walk_locked(chan)) != NULL) {
828 test = pbx_builtin_getvar_helper(chan, cat);
829 if (test && !strcasecmp(test, group))
830 count++;
831 ast_channel_unlock(chan);
834 return count;
837 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
839 regex_t regexbuf;
840 struct ast_channel *chan;
841 int count = 0;
842 const char *test;
843 char cat[80];
844 const char *s;
846 if (ast_strlen_zero(groupmatch))
847 return 0;
849 /* if regex compilation fails, return zero matches */
850 if (regcomp(&regexbuf, groupmatch, REG_EXTENDED | REG_NOSUB))
851 return 0;
853 s = S_OR(category, GROUP_CATEGORY_PREFIX);
854 ast_copy_string(cat, s, sizeof(cat));
856 chan = NULL;
857 while ((chan = ast_channel_walk_locked(chan)) != NULL) {
858 test = pbx_builtin_getvar_helper(chan, cat);
859 if (test && !regexec(&regexbuf, test, 0, NULL, 0))
860 count++;
861 ast_channel_unlock(chan);
864 regfree(&regexbuf);
866 return count;
869 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
871 int argc;
872 char *scan;
873 int paren = 0, quote = 0;
875 if (!buf || !array || !arraylen)
876 return 0;
878 memset(array, 0, arraylen * sizeof(*array));
880 scan = buf;
882 for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
883 array[argc] = scan;
884 for (; *scan; scan++) {
885 if (*scan == '(')
886 paren++;
887 else if (*scan == ')') {
888 if (paren)
889 paren--;
890 } else if (*scan == '"') {
891 quote = quote ? 0 : 1;
892 /* Remove quote character from argument */
893 memmove(scan, scan + 1, strlen(scan));
894 scan--;
895 } else if (*scan == '\\') {
896 /* Literal character, don't parse */
897 memmove(scan, scan + 1, strlen(scan));
898 } else if ((*scan == delim) && !paren && !quote) {
899 *scan++ = '\0';
900 break;
905 if (*scan)
906 array[argc++] = scan;
908 return argc;
911 enum AST_LOCK_RESULT ast_lock_path(const char *path)
913 char *s;
914 char *fs;
915 int res;
916 int fd;
917 int lp = strlen(path);
918 time_t start;
920 if (!(s = alloca(lp + 10)) || !(fs = alloca(lp + 20))) {
921 ast_log(LOG_WARNING, "Out of memory!\n");
922 return AST_LOCK_FAILURE;
925 snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
926 fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, 0600);
927 if (fd < 0) {
928 fprintf(stderr, "Unable to create lock file '%s': %s\n", path, strerror(errno));
929 return AST_LOCK_PATH_NOT_FOUND;
931 close(fd);
933 snprintf(s, strlen(path) + 9, "%s/.lock", path);
934 start = time(NULL);
935 while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5))
936 usleep(1);
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 unlink(fs);
942 ast_log(LOG_DEBUG, "Locked path '%s'\n", path);
943 return AST_LOCK_SUCCESS;
947 int ast_unlock_path(const char *path)
949 char *s;
950 if (!(s = alloca(strlen(path) + 10)))
951 return -1;
952 snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
953 ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
954 return unlink(s);
957 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
959 int silencethreshold = 128;
960 int maxsilence=0;
961 int res = 0;
962 int cmd = 0;
963 int max_attempts = 3;
964 int attempts = 0;
965 int recorded = 0;
966 int message_exists = 0;
967 /* Note that urgent and private are for flagging messages as such in the future */
969 /* barf if no pointer passed to store duration in */
970 if (duration == NULL) {
971 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
972 return -1;
975 cmd = '3'; /* Want to start by recording */
977 while ((cmd >= 0) && (cmd != 't')) {
978 switch (cmd) {
979 case '1':
980 if (!message_exists) {
981 /* In this case, 1 is to record a message */
982 cmd = '3';
983 break;
984 } else {
985 ast_stream_and_wait(chan, "vm-msgsaved", chan->language, "");
986 cmd = 't';
987 return res;
989 case '2':
990 /* Review */
991 ast_verbose(VERBOSE_PREFIX_3 "Reviewing the recording\n");
992 cmd = ast_stream_and_wait(chan, recordfile, chan->language, AST_DIGIT_ANY);
993 break;
994 case '3':
995 message_exists = 0;
996 /* Record */
997 if (recorded == 1)
998 ast_verbose(VERBOSE_PREFIX_3 "Re-recording\n");
999 else
1000 ast_verbose(VERBOSE_PREFIX_3 "Recording\n");
1001 recorded = 1;
1002 cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path);
1003 if (cmd == -1) {
1004 /* User has hung up, no options to give */
1005 return cmd;
1007 if (cmd == '0') {
1008 break;
1009 } else if (cmd == '*') {
1010 break;
1012 else {
1013 /* If all is well, a message exists */
1014 message_exists = 1;
1015 cmd = 0;
1017 break;
1018 case '4':
1019 case '5':
1020 case '6':
1021 case '7':
1022 case '8':
1023 case '9':
1024 case '*':
1025 case '#':
1026 cmd = ast_play_and_wait(chan, "vm-sorry");
1027 break;
1028 default:
1029 if (message_exists) {
1030 cmd = ast_play_and_wait(chan, "vm-review");
1032 else {
1033 cmd = ast_play_and_wait(chan, "vm-torerecord");
1034 if (!cmd)
1035 cmd = ast_waitfordigit(chan, 600);
1038 if (!cmd)
1039 cmd = ast_waitfordigit(chan, 6000);
1040 if (!cmd) {
1041 attempts++;
1043 if (attempts > max_attempts) {
1044 cmd = 't';
1048 if (cmd == 't')
1049 cmd = 0;
1050 return cmd;
1053 #define RES_UPONE (1 << 16)
1054 #define RES_EXIT (1 << 17)
1055 #define RES_REPEAT (1 << 18)
1056 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1058 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1059 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1061 int res;
1062 int (*ivr_func)(struct ast_channel *, void *);
1063 char *c;
1064 char *n;
1066 switch(option->action) {
1067 case AST_ACTION_UPONE:
1068 return RES_UPONE;
1069 case AST_ACTION_EXIT:
1070 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1071 case AST_ACTION_REPEAT:
1072 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1073 case AST_ACTION_RESTART:
1074 return RES_RESTART ;
1075 case AST_ACTION_NOOP:
1076 return 0;
1077 case AST_ACTION_BACKGROUND:
1078 res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, AST_DIGIT_ANY);
1079 if (res < 0) {
1080 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1081 res = 0;
1083 return res;
1084 case AST_ACTION_PLAYBACK:
1085 res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, "");
1086 if (res < 0) {
1087 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1088 res = 0;
1090 return res;
1091 case AST_ACTION_MENU:
1092 res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata);
1093 /* Do not pass entry errors back up, treaat ast though ti was an "UPONE" */
1094 if (res == -2)
1095 res = 0;
1096 return res;
1097 case AST_ACTION_WAITOPTION:
1098 res = ast_waitfordigit(chan, 1000 * (chan->pbx ? chan->pbx->rtimeout : 10));
1099 if (!res)
1100 return 't';
1101 return res;
1102 case AST_ACTION_CALLBACK:
1103 ivr_func = option->adata;
1104 res = ivr_func(chan, cbdata);
1105 return res;
1106 case AST_ACTION_TRANSFER:
1107 res = ast_parseable_goto(chan, option->adata);
1108 return 0;
1109 case AST_ACTION_PLAYLIST:
1110 case AST_ACTION_BACKLIST:
1111 res = 0;
1112 c = ast_strdupa(option->adata);
1113 while ((n = strsep(&c, ";"))) {
1114 if ((res = ast_stream_and_wait(chan, n, chan->language,
1115 (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : "")))
1116 break;
1118 ast_stopstream(chan);
1119 return res;
1120 default:
1121 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1122 return 0;
1124 return -1;
1127 static int option_exists(struct ast_ivr_menu *menu, char *option)
1129 int x;
1130 for (x=0;menu->options[x].option;x++)
1131 if (!strcasecmp(menu->options[x].option, option))
1132 return x;
1133 return -1;
1136 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1138 int x;
1139 for (x=0;menu->options[x].option;x++)
1140 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
1141 (menu->options[x].option[strlen(option)]))
1142 return x;
1143 return -1;
1146 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1148 int res=0;
1149 int ms;
1150 while(option_matchmore(menu, exten)) {
1151 ms = chan->pbx ? chan->pbx->dtimeout : 5000;
1152 if (strlen(exten) >= maxexten - 1)
1153 break;
1154 res = ast_waitfordigit(chan, ms);
1155 if (res < 1)
1156 break;
1157 exten[strlen(exten) + 1] = '\0';
1158 exten[strlen(exten)] = res;
1160 return res > 0 ? 0 : res;
1163 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1165 /* Execute an IVR menu structure */
1166 int res=0;
1167 int pos = 0;
1168 int retries = 0;
1169 char exten[AST_MAX_EXTENSION] = "s";
1170 if (option_exists(menu, "s") < 0) {
1171 strcpy(exten, "g");
1172 if (option_exists(menu, "g") < 0) {
1173 ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1174 return -1;
1177 while(!res) {
1178 while(menu->options[pos].option) {
1179 if (!strcasecmp(menu->options[pos].option, exten)) {
1180 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1181 ast_log(LOG_DEBUG, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1182 if (res < 0)
1183 break;
1184 else if (res & RES_UPONE)
1185 return 0;
1186 else if (res & RES_EXIT)
1187 return res;
1188 else if (res & RES_REPEAT) {
1189 int maxretries = res & 0xffff;
1190 if ((res & RES_RESTART) == RES_RESTART) {
1191 retries = 0;
1192 } else
1193 retries++;
1194 if (!maxretries)
1195 maxretries = 3;
1196 if ((maxretries > 0) && (retries >= maxretries)) {
1197 ast_log(LOG_DEBUG, "Max retries %d exceeded\n", maxretries);
1198 return -2;
1199 } else {
1200 if (option_exists(menu, "g") > -1)
1201 strcpy(exten, "g");
1202 else if (option_exists(menu, "s") > -1)
1203 strcpy(exten, "s");
1205 pos=0;
1206 continue;
1207 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1208 ast_log(LOG_DEBUG, "Got start of extension, %c\n", res);
1209 exten[1] = '\0';
1210 exten[0] = res;
1211 if ((res = read_newoption(chan, menu, exten, sizeof(exten))))
1212 break;
1213 if (option_exists(menu, exten) < 0) {
1214 if (option_exists(menu, "i")) {
1215 ast_log(LOG_DEBUG, "Invalid extension entered, going to 'i'!\n");
1216 strcpy(exten, "i");
1217 pos = 0;
1218 continue;
1219 } else {
1220 ast_log(LOG_DEBUG, "Aborting on invalid entry, with no 'i' option!\n");
1221 res = -2;
1222 break;
1224 } else {
1225 ast_log(LOG_DEBUG, "New existing extension: %s\n", exten);
1226 pos = 0;
1227 continue;
1231 pos++;
1233 ast_log(LOG_DEBUG, "Stopping option '%s', res is %d\n", exten, res);
1234 pos = 0;
1235 if (!strcasecmp(exten, "s"))
1236 strcpy(exten, "g");
1237 else
1238 break;
1240 return res;
1243 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1245 int res;
1246 res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1247 /* Hide internal coding */
1248 if (res > 0)
1249 res = 0;
1250 return res;
1253 char *ast_read_textfile(const char *filename)
1255 int fd;
1256 char *output=NULL;
1257 struct stat filesize;
1258 int count=0;
1259 int res;
1260 if(stat(filename,&filesize)== -1){
1261 ast_log(LOG_WARNING,"Error can't stat %s\n", filename);
1262 return NULL;
1264 count=filesize.st_size + 1;
1265 fd = open(filename, O_RDONLY);
1266 if (fd < 0) {
1267 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1268 return NULL;
1270 if ((output = ast_malloc(count))) {
1271 res = read(fd, output, count - 1);
1272 if (res == count - 1) {
1273 output[res] = '\0';
1274 } else {
1275 ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
1276 free(output);
1277 output = NULL;
1280 close(fd);
1281 return output;
1284 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
1286 char *s;
1287 int curarg;
1288 unsigned int argloc;
1289 char *arg;
1290 int res = 0;
1292 ast_clear_flag(flags, AST_FLAGS_ALL);
1294 if (!optstr)
1295 return 0;
1297 s = optstr;
1298 while (*s) {
1299 curarg = *s++ & 0x7f; /* the array (in app.h) has 128 entries */
1300 ast_set_flag(flags, options[curarg].flag);
1301 argloc = options[curarg].arg_index;
1302 if (*s == '(') {
1303 /* Has argument */
1304 arg = ++s;
1305 s = strchr(s, ')');
1306 if (*s) {
1307 if (argloc)
1308 args[argloc - 1] = arg;
1309 *s++ = '\0';
1310 } else {
1311 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
1312 res = -1;
1314 } else if (argloc) {
1315 args[argloc - 1] = NULL;
1319 return res;