fix various other problems found by gcc 4.3
[asterisk-bristuff.git] / main / app.c
bloba71f46adc268a75a14c2c2b8afc50088d1432d62
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 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;
219 if (!between)
220 between = 100;
222 if (peer)
223 res = ast_autoservice_start(peer);
225 if (!res)
226 res = ast_waitfor(chan, 100);
228 /* ast_waitfor will return the number of remaining ms on success */
229 if (res < 0)
230 return res;
232 for (ptr = digits; *ptr; ptr++) {
233 if (*ptr == 'w') {
234 /* 'w' -- wait half a second */
235 if ((res = ast_safe_sleep(chan, 500)))
236 break;
237 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
238 /* Character represents valid DTMF */
239 if (*ptr == 'f' || *ptr == 'F') {
240 /* ignore return values if not supported by channel */
241 ast_indicate(chan, AST_CONTROL_FLASH);
242 } else
243 ast_senddigit(chan, *ptr);
244 /* pause between digits */
245 if ((res = ast_safe_sleep(chan, between)))
246 break;
247 } else
248 ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n",*ptr);
251 if (peer) {
252 /* Stop autoservice on the peer channel, but don't overwrite any error condition
253 that has occurred previously while acting on the primary channel */
254 if (ast_autoservice_stop(peer) && !res)
255 res = -1;
258 return res;
261 struct linear_state {
262 int fd;
263 int autoclose;
264 int allowoverride;
265 int origwfmt;
268 static void linear_release(struct ast_channel *chan, void *params)
270 struct linear_state *ls = params;
271 if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt)) {
272 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", chan->name, ls->origwfmt);
274 if (ls->autoclose)
275 close(ls->fd);
276 free(params);
279 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
281 struct ast_frame f;
282 short buf[2048 + AST_FRIENDLY_OFFSET / 2];
283 struct linear_state *ls = data;
284 int res;
285 len = samples * 2;
286 if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
287 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" ,len);
288 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
290 memset(&f, 0, sizeof(f));
291 res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
292 if (res > 0) {
293 f.frametype = AST_FRAME_VOICE;
294 f.subclass = AST_FORMAT_SLINEAR;
295 f.data = buf + AST_FRIENDLY_OFFSET/2;
296 f.datalen = res;
297 f.samples = res / 2;
298 f.offset = AST_FRIENDLY_OFFSET;
299 ast_write(chan, &f);
300 if (res == len)
301 return 0;
303 return -1;
306 static void *linear_alloc(struct ast_channel *chan, void *params)
308 struct linear_state *ls;
309 /* In this case, params is already malloc'd */
310 if (params) {
311 ls = params;
312 if (ls->allowoverride)
313 ast_set_flag(chan, AST_FLAG_WRITE_INT);
314 else
315 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
316 ls->origwfmt = chan->writeformat;
317 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
318 ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", chan->name);
319 free(ls);
320 ls = params = NULL;
323 return params;
326 static struct ast_generator linearstream =
328 alloc: linear_alloc,
329 release: linear_release,
330 generate: linear_generator,
333 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
335 struct linear_state *lin;
336 char tmpf[256];
337 int res = -1;
338 int autoclose = 0;
339 if (fd < 0) {
340 if (ast_strlen_zero(filename))
341 return -1;
342 autoclose = 1;
343 if (filename[0] == '/')
344 ast_copy_string(tmpf, filename, sizeof(tmpf));
345 else
346 snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", (char *)ast_config_AST_DATA_DIR, "sounds", filename);
347 fd = open(tmpf, O_RDONLY);
348 if (fd < 0){
349 ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
350 return -1;
353 if ((lin = ast_calloc(1, sizeof(*lin)))) {
354 lin->fd = fd;
355 lin->allowoverride = allowoverride;
356 lin->autoclose = autoclose;
357 res = ast_activate_generator(chan, &linearstream, lin);
359 return res;
362 int ast_control_streamfile(struct ast_channel *chan, const char *file,
363 const char *fwd, const char *rev,
364 const char *stop, const char *pause,
365 const char *restart, int skipms)
367 char *breaks = NULL;
368 char *end = NULL;
369 int blen = 2;
370 int res;
371 long pause_restart_point = 0;
373 if (stop)
374 blen += strlen(stop);
375 if (pause)
376 blen += strlen(pause);
377 if (restart)
378 blen += strlen(restart);
380 if (blen > 2) {
381 breaks = alloca(blen + 1);
382 breaks[0] = '\0';
383 if (stop)
384 strcat(breaks, stop);
385 if (pause)
386 strcat(breaks, pause);
387 if (restart)
388 strcat(breaks, restart);
390 if (chan->_state != AST_STATE_UP)
391 res = ast_answer(chan);
393 if (file) {
394 if ((end = strchr(file,':'))) {
395 if (!strcasecmp(end, ":end")) {
396 *end = '\0';
397 end++;
402 for (;;) {
403 ast_stopstream(chan);
404 res = ast_streamfile(chan, file, chan->language);
405 if (!res) {
406 if (pause_restart_point) {
407 ast_seekstream(chan->stream, pause_restart_point, SEEK_SET);
408 pause_restart_point = 0;
410 else if (end) {
411 ast_seekstream(chan->stream, 0, SEEK_END);
412 end = NULL;
414 res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
417 if (res < 1)
418 break;
420 /* We go at next loop if we got the restart char */
421 if (restart && strchr(restart, res)) {
422 if (option_debug)
423 ast_log(LOG_DEBUG, "we'll restart the stream here at next loop\n");
424 pause_restart_point = 0;
425 continue;
428 if (pause && strchr(pause, res)) {
429 pause_restart_point = ast_tellstream(chan->stream);
430 for (;;) {
431 ast_stopstream(chan);
432 res = ast_waitfordigit(chan, 1000);
433 if (!res)
434 continue;
435 else if (res == -1 || strchr(pause, res) || (stop && strchr(stop, res)))
436 break;
438 if (res == *pause) {
439 res = 0;
440 continue;
444 if (res == -1)
445 break;
447 /* if we get one of our stop chars, return it to the calling function */
448 if (stop && strchr(stop, res))
449 break;
452 /* If we are returning a digit cast it as char */
453 if (res > 0 || chan->stream)
454 res = (char)res;
456 ast_stopstream(chan);
458 return res;
461 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
463 int d;
464 d = ast_streamfile(chan, fn, chan->language);
465 if (d)
466 return d;
467 d = ast_waitstream(chan, AST_DIGIT_ANY);
468 ast_stopstream(chan);
469 return d;
472 static int global_silence_threshold = 128;
473 static int global_maxsilence = 0;
475 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
476 * @param chan Channel to playback to/record from.
477 * @param playfile Filename of sound to play before recording begins.
478 * @param recordfile Filename to record to.
479 * @param maxtime Maximum length of recording (in milliseconds).
480 * @param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
481 * @param duration Where to store actual length of the recorded message (in milliseconds).
482 * @param beep Whether to play a beep before starting to record.
483 * @param silencethreshold
484 * @param maxsilence Length of silence that will end a recording (in milliseconds).
485 * @param path Optional filesystem path to unlock.
486 * @param prepend If true, prepend the recorded audio to an existing file.
487 * @param acceptdtmf DTMF digits that will end the recording.
488 * @param canceldtmf DTMF digits that will cancel the recording.
491 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)
493 int d = 0;
494 char *fmts;
495 char comment[256];
496 int x, fmtcnt = 1, res = -1, outmsg = 0;
497 struct ast_filestream *others[MAX_OTHER_FORMATS];
498 char *sfmt[MAX_OTHER_FORMATS];
499 char *stringp = NULL;
500 time_t start, end;
501 struct ast_dsp *sildet = NULL; /* silence detector dsp */
502 int totalsilence = 0;
503 int rfmt = 0;
504 struct ast_silence_generator *silgen = NULL;
505 char prependfile[80];
507 if (silencethreshold < 0)
508 silencethreshold = global_silence_threshold;
510 if (maxsilence < 0)
511 maxsilence = global_maxsilence;
513 /* barf if no pointer passed to store duration in */
514 if (duration == NULL) {
515 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
516 return -1;
519 if (option_debug)
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 if (option_debug)
542 ast_log(LOG_DEBUG, "Recording Formats: sfmts=%s\n", fmts);
543 sfmt[0] = ast_strdupa(fmts);
545 while ((fmt = strsep(&stringp, "|"))) {
546 if (fmtcnt > MAX_OTHER_FORMATS - 1) {
547 ast_log(LOG_WARNING, "Please increase MAX_OTHER_FORMATS in app.c\n");
548 break;
550 sfmt[fmtcnt++] = ast_strdupa(fmt);
553 end = start = time(NULL); /* pre-initialize end to be same as start in case we never get into loop */
554 for (x = 0; x < fmtcnt; x++) {
555 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, 0777);
556 if (option_verbose > 2)
557 ast_verbose(VERBOSE_PREFIX_3 "x=%d, open writing: %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
559 if (!others[x])
560 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 if (option_debug)
598 ast_log(LOG_DEBUG, "One waitfor failed, trying another\n");
599 /* Try one more time in case of masq */
600 res = ast_waitfor(chan, 2000);
601 if (!res) {
602 ast_log(LOG_WARNING, "No audio available on %s??\n", chan->name);
603 res = -1;
607 if (res < 0) {
608 f = NULL;
609 break;
611 f = ast_read(chan);
612 if (!f)
613 break;
614 if (f->frametype == AST_FRAME_VOICE) {
615 /* write each format */
616 for (x = 0; x < fmtcnt; x++) {
617 if (prepend && !others[x])
618 break;
619 res = ast_writestream(others[x], f);
622 /* Silence Detection */
623 if (maxsilence > 0) {
624 int dspsilence = 0;
625 ast_dsp_silence(sildet, f, &dspsilence);
626 if (dspsilence)
627 totalsilence = dspsilence;
628 else
629 totalsilence = 0;
631 if (totalsilence > maxsilence) {
632 /* Ended happily with silence */
633 if (option_verbose > 2)
634 ast_verbose( VERBOSE_PREFIX_3 "Recording automatically stopped after a silence of %d seconds\n", totalsilence/1000);
635 res = 'S';
636 outmsg = 2;
637 break;
640 /* Exit on any error */
641 if (res) {
642 ast_log(LOG_WARNING, "Error writing frame\n");
643 break;
645 } else if (f->frametype == AST_FRAME_VIDEO) {
646 /* Write only once */
647 ast_writestream(others[0], f);
648 } else if (f->frametype == AST_FRAME_DTMF) {
649 if (prepend) {
650 /* stop recording with any digit */
651 if (option_verbose > 2)
652 ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
653 res = 't';
654 outmsg = 2;
655 break;
657 if (strchr(acceptdtmf, f->subclass)) {
658 if (option_verbose > 2)
659 ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
660 res = f->subclass;
661 outmsg = 2;
662 break;
664 if (strchr(canceldtmf, f->subclass)) {
665 if (option_verbose > 2)
666 ast_verbose(VERBOSE_PREFIX_3 "User cancelled message by pressing %c\n", f->subclass);
667 res = f->subclass;
668 outmsg = 0;
669 break;
672 if (maxtime) {
673 end = time(NULL);
674 if (maxtime < (end - start)) {
675 if (option_verbose > 2)
676 ast_verbose(VERBOSE_PREFIX_3 "Took too long, cutting it short...\n");
677 res = 't';
678 outmsg = 2;
679 break;
682 ast_frfree(f);
684 if (!f) {
685 if (option_verbose > 2)
686 ast_verbose(VERBOSE_PREFIX_3 "User hung up\n");
687 res = -1;
688 outmsg = 1;
689 } else {
690 ast_frfree(f);
692 } else {
693 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
696 if (!prepend) {
697 if (silgen)
698 ast_channel_stop_silence_generator(chan, silgen);
701 /*!\note
702 * Instead of asking how much time passed (end - start), calculate the number
703 * of seconds of audio which actually went into the file. This fixes a
704 * problem where audio is stopped up on the network and never gets to us.
706 * Note that we still want to use the number of seconds passed for the max
707 * message, otherwise we could get a situation where this stream is never
708 * closed (which would create a resource leak).
710 *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
712 if (!prepend) {
713 for (x = 0; x < fmtcnt; x++) {
714 if (!others[x])
715 break;
716 /*!\note
717 * If we ended with silence, trim all but the first 200ms of silence
718 * off the recording. However, if we ended with '#', we don't want
719 * to trim ANY part of the recording.
721 if (res > 0 && totalsilence)
722 ast_stream_rewind(others[x], totalsilence - 200);
723 ast_truncstream(others[x]);
724 ast_closestream(others[x]);
728 if (prepend && outmsg) {
729 struct ast_filestream *realfiles[MAX_OTHER_FORMATS];
730 struct ast_frame *fr;
732 for (x = 0; x < fmtcnt; x++) {
733 snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
734 realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
735 if (!others[x] || !realfiles[x])
736 break;
737 /*!\note Same logic as above. */
738 if (totalsilence)
739 ast_stream_rewind(others[x], totalsilence - 200);
740 ast_truncstream(others[x]);
741 /* add the original file too */
742 while ((fr = ast_readframe(realfiles[x]))) {
743 ast_writestream(others[x], fr);
744 ast_frfree(fr);
746 ast_closestream(others[x]);
747 ast_closestream(realfiles[x]);
748 ast_filerename(prependfile, recordfile, sfmt[x]);
749 if (option_verbose > 3)
750 ast_verbose(VERBOSE_PREFIX_4 "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
751 ast_filedelete(prependfile, sfmt[x]);
754 if (rfmt && ast_set_read_format(chan, rfmt)) {
755 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(rfmt), chan->name);
757 if (outmsg == 2) {
758 ast_stream_and_wait(chan, "auth-thankyou", chan->language, "");
760 if (sildet)
761 ast_dsp_free(sildet);
762 return res;
765 static char default_acceptdtmf[] = "#";
766 static char default_canceldtmf[] = "";
768 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)
770 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));
773 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)
775 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf);
778 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)
780 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf);
783 /* Channel group core functions */
785 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
787 int res=0;
788 char tmp[256];
789 char *grp=NULL, *cat=NULL;
791 if (!ast_strlen_zero(data)) {
792 ast_copy_string(tmp, data, sizeof(tmp));
793 grp = tmp;
794 cat = strchr(tmp, '@');
795 if (cat) {
796 *cat = '\0';
797 cat++;
801 if (!ast_strlen_zero(grp))
802 ast_copy_string(group, grp, group_max);
803 else
804 *group = '\0';
806 if (!ast_strlen_zero(cat))
807 ast_copy_string(category, cat, category_max);
809 return res;
812 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
814 int res = 0;
815 char group[80] = "", category[80] = "";
816 struct ast_group_info *gi = NULL;
817 size_t len = 0;
819 if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category)))
820 return -1;
822 /* Calculate memory we will need if this is new */
823 len = sizeof(*gi) + strlen(group) + 1;
824 if (!ast_strlen_zero(category))
825 len += strlen(category) + 1;
827 AST_LIST_LOCK(&groups);
828 AST_LIST_TRAVERSE_SAFE_BEGIN(&groups, gi, list) {
829 if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
830 AST_LIST_REMOVE_CURRENT(&groups, list);
831 free(gi);
832 break;
835 AST_LIST_TRAVERSE_SAFE_END
837 if (ast_strlen_zero(group)) {
838 /* Enable unsetting the group */
839 } else if ((gi = calloc(1, len))) {
840 gi->chan = chan;
841 gi->group = (char *) gi + sizeof(*gi);
842 strcpy(gi->group, group);
843 if (!ast_strlen_zero(category)) {
844 gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
845 strcpy(gi->category, category);
847 AST_LIST_INSERT_TAIL(&groups, gi, list);
848 } else {
849 res = -1;
852 AST_LIST_UNLOCK(&groups);
854 return res;
857 int ast_app_group_get_count(const char *group, const char *category)
859 struct ast_group_info *gi = NULL;
860 int count = 0;
862 if (ast_strlen_zero(group))
863 return 0;
865 AST_LIST_LOCK(&groups);
866 AST_LIST_TRAVERSE(&groups, gi, list) {
867 if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category))))
868 count++;
870 AST_LIST_UNLOCK(&groups);
872 return count;
875 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
877 struct ast_group_info *gi = NULL;
878 regex_t regexbuf;
879 int count = 0;
881 if (ast_strlen_zero(groupmatch))
882 return 0;
884 /* if regex compilation fails, return zero matches */
885 if (regcomp(&regexbuf, groupmatch, REG_EXTENDED | REG_NOSUB))
886 return 0;
888 AST_LIST_LOCK(&groups);
889 AST_LIST_TRAVERSE(&groups, gi, list) {
890 if (!regexec(&regexbuf, gi->group, 0, NULL, 0) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category))))
891 count++;
893 AST_LIST_UNLOCK(&groups);
895 regfree(&regexbuf);
897 return count;
900 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
902 struct ast_group_info *gi = NULL;
904 AST_LIST_LOCK(&groups);
905 AST_LIST_TRAVERSE(&groups, gi, list) {
906 if (gi->chan == old)
907 gi->chan = new;
909 AST_LIST_UNLOCK(&groups);
911 return 0;
914 int ast_app_group_discard(struct ast_channel *chan)
916 struct ast_group_info *gi = NULL;
918 AST_LIST_LOCK(&groups);
919 AST_LIST_TRAVERSE_SAFE_BEGIN(&groups, gi, list) {
920 if (gi->chan == chan) {
921 AST_LIST_REMOVE_CURRENT(&groups, list);
922 free(gi);
925 AST_LIST_TRAVERSE_SAFE_END
926 AST_LIST_UNLOCK(&groups);
928 return 0;
931 int ast_app_group_list_lock(void)
933 return AST_LIST_LOCK(&groups);
936 struct ast_group_info *ast_app_group_list_head(void)
938 return AST_LIST_FIRST(&groups);
941 int ast_app_group_list_unlock(void)
943 return AST_LIST_UNLOCK(&groups);
946 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
948 int argc;
949 char *scan;
950 int paren = 0, quote = 0;
952 if (!buf || !array || !arraylen)
953 return 0;
955 memset(array, 0, arraylen * sizeof(*array));
957 scan = buf;
959 for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
960 array[argc] = scan;
961 for (; *scan; scan++) {
962 if (*scan == '(')
963 paren++;
964 else if (*scan == ')') {
965 if (paren)
966 paren--;
967 } else if (*scan == '"' && delim != '"') {
968 quote = quote ? 0 : 1;
969 /* Remove quote character from argument */
970 memmove(scan, scan + 1, strlen(scan));
971 scan--;
972 } else if (*scan == '\\') {
973 /* Literal character, don't parse */
974 memmove(scan, scan + 1, strlen(scan));
975 } else if ((*scan == delim) && !paren && !quote) {
976 *scan++ = '\0';
977 break;
982 if (*scan)
983 array[argc++] = scan;
985 return argc;
988 enum AST_LOCK_RESULT ast_lock_path(const char *path)
990 char *s;
991 char *fs;
992 int res;
993 int fd;
994 int lp = strlen(path);
995 time_t start;
997 if (!(s = alloca(lp + 10)) || !(fs = alloca(lp + 20))) {
998 ast_log(LOG_WARNING, "Out of memory!\n");
999 return AST_LOCK_FAILURE;
1002 snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
1003 fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, 0600);
1004 if (fd < 0) {
1005 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
1006 return AST_LOCK_PATH_NOT_FOUND;
1008 close(fd);
1010 snprintf(s, strlen(path) + 9, "%s/.lock", path);
1011 start = time(NULL);
1012 while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5))
1013 usleep(1);
1015 unlink(fs);
1017 if (res) {
1018 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
1019 return AST_LOCK_TIMEOUT;
1020 } else {
1021 if (option_debug)
1022 ast_log(LOG_DEBUG, "Locked path '%s'\n", path);
1023 return AST_LOCK_SUCCESS;
1027 int ast_unlock_path(const char *path)
1029 char *s;
1030 int res;
1032 if (!(s = alloca(strlen(path) + 10))) {
1033 ast_log(LOG_WARNING, "Out of memory!\n");
1034 return -1;
1037 snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1039 if ((res = unlink(s)))
1040 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
1041 else {
1042 if (option_debug)
1043 ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
1046 return res;
1049 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
1051 int silencethreshold = 128;
1052 int maxsilence=0;
1053 int res = 0;
1054 int cmd = 0;
1055 int max_attempts = 3;
1056 int attempts = 0;
1057 int recorded = 0;
1058 int message_exists = 0;
1059 /* Note that urgent and private are for flagging messages as such in the future */
1061 /* barf if no pointer passed to store duration in */
1062 if (duration == NULL) {
1063 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1064 return -1;
1067 cmd = '3'; /* Want to start by recording */
1069 while ((cmd >= 0) && (cmd != 't')) {
1070 switch (cmd) {
1071 case '1':
1072 if (!message_exists) {
1073 /* In this case, 1 is to record a message */
1074 cmd = '3';
1075 break;
1076 } else {
1077 ast_stream_and_wait(chan, "vm-msgsaved", chan->language, "");
1078 cmd = 't';
1079 return res;
1081 case '2':
1082 /* Review */
1083 ast_verbose(VERBOSE_PREFIX_3 "Reviewing the recording\n");
1084 cmd = ast_stream_and_wait(chan, recordfile, chan->language, AST_DIGIT_ANY);
1085 break;
1086 case '3':
1087 message_exists = 0;
1088 /* Record */
1089 if (recorded == 1)
1090 ast_verbose(VERBOSE_PREFIX_3 "Re-recording\n");
1091 else
1092 ast_verbose(VERBOSE_PREFIX_3 "Recording\n");
1093 recorded = 1;
1094 cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path);
1095 if (cmd == -1) {
1096 /* User has hung up, no options to give */
1097 return cmd;
1099 if (cmd == '0') {
1100 break;
1101 } else if (cmd == '*') {
1102 break;
1104 else {
1105 /* If all is well, a message exists */
1106 message_exists = 1;
1107 cmd = 0;
1109 break;
1110 case '4':
1111 case '5':
1112 case '6':
1113 case '7':
1114 case '8':
1115 case '9':
1116 case '*':
1117 case '#':
1118 cmd = ast_play_and_wait(chan, "vm-sorry");
1119 break;
1120 default:
1121 if (message_exists) {
1122 cmd = ast_play_and_wait(chan, "vm-review");
1124 else {
1125 cmd = ast_play_and_wait(chan, "vm-torerecord");
1126 if (!cmd)
1127 cmd = ast_waitfordigit(chan, 600);
1130 if (!cmd)
1131 cmd = ast_waitfordigit(chan, 6000);
1132 if (!cmd) {
1133 attempts++;
1135 if (attempts > max_attempts) {
1136 cmd = 't';
1140 if (cmd == 't')
1141 cmd = 0;
1142 return cmd;
1145 #define RES_UPONE (1 << 16)
1146 #define RES_EXIT (1 << 17)
1147 #define RES_REPEAT (1 << 18)
1148 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1150 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1152 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1154 int res;
1155 int (*ivr_func)(struct ast_channel *, void *);
1156 char *c;
1157 char *n;
1159 switch(option->action) {
1160 case AST_ACTION_UPONE:
1161 return RES_UPONE;
1162 case AST_ACTION_EXIT:
1163 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1164 case AST_ACTION_REPEAT:
1165 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1166 case AST_ACTION_RESTART:
1167 return RES_RESTART ;
1168 case AST_ACTION_NOOP:
1169 return 0;
1170 case AST_ACTION_BACKGROUND:
1171 res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, AST_DIGIT_ANY);
1172 if (res < 0) {
1173 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1174 res = 0;
1176 return res;
1177 case AST_ACTION_PLAYBACK:
1178 res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, "");
1179 if (res < 0) {
1180 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1181 res = 0;
1183 return res;
1184 case AST_ACTION_MENU:
1185 res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata);
1186 /* Do not pass entry errors back up, treaat ast though ti was an "UPONE" */
1187 if (res == -2)
1188 res = 0;
1189 return res;
1190 case AST_ACTION_WAITOPTION:
1191 res = ast_waitfordigit(chan, 1000 * (chan->pbx ? chan->pbx->rtimeout : 10));
1192 if (!res)
1193 return 't';
1194 return res;
1195 case AST_ACTION_CALLBACK:
1196 ivr_func = option->adata;
1197 res = ivr_func(chan, cbdata);
1198 return res;
1199 case AST_ACTION_TRANSFER:
1200 res = ast_parseable_goto(chan, option->adata);
1201 return 0;
1202 case AST_ACTION_PLAYLIST:
1203 case AST_ACTION_BACKLIST:
1204 res = 0;
1205 c = ast_strdupa(option->adata);
1206 while ((n = strsep(&c, ";"))) {
1207 if ((res = ast_stream_and_wait(chan, n, chan->language,
1208 (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : "")))
1209 break;
1211 ast_stopstream(chan);
1212 return res;
1213 default:
1214 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1215 return 0;
1217 return -1;
1220 static int option_exists(struct ast_ivr_menu *menu, char *option)
1222 int x;
1223 for (x = 0; menu->options[x].option; x++)
1224 if (!strcasecmp(menu->options[x].option, option))
1225 return x;
1226 return -1;
1229 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1231 int x;
1232 for (x = 0; menu->options[x].option; x++)
1233 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
1234 (menu->options[x].option[strlen(option)]))
1235 return x;
1236 return -1;
1239 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1241 int res=0;
1242 int ms;
1243 while (option_matchmore(menu, exten)) {
1244 ms = chan->pbx ? chan->pbx->dtimeout : 5000;
1245 if (strlen(exten) >= maxexten - 1)
1246 break;
1247 res = ast_waitfordigit(chan, ms);
1248 if (res < 1)
1249 break;
1250 exten[strlen(exten) + 1] = '\0';
1251 exten[strlen(exten)] = res;
1253 return res > 0 ? 0 : res;
1256 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1258 /* Execute an IVR menu structure */
1259 int res=0;
1260 int pos = 0;
1261 int retries = 0;
1262 char exten[AST_MAX_EXTENSION] = "s";
1263 if (option_exists(menu, "s") < 0) {
1264 strcpy(exten, "g");
1265 if (option_exists(menu, "g") < 0) {
1266 ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1267 return -1;
1270 while(!res) {
1271 while(menu->options[pos].option) {
1272 if (!strcasecmp(menu->options[pos].option, exten)) {
1273 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1274 if (option_debug)
1275 ast_log(LOG_DEBUG, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1276 if (res < 0)
1277 break;
1278 else if (res & RES_UPONE)
1279 return 0;
1280 else if (res & RES_EXIT)
1281 return res;
1282 else if (res & RES_REPEAT) {
1283 int maxretries = res & 0xffff;
1284 if ((res & RES_RESTART) == RES_RESTART) {
1285 retries = 0;
1286 } else
1287 retries++;
1288 if (!maxretries)
1289 maxretries = 3;
1290 if ((maxretries > 0) && (retries >= maxretries)) {
1291 if (option_debug)
1292 ast_log(LOG_DEBUG, "Max retries %d exceeded\n", maxretries);
1293 return -2;
1294 } else {
1295 if (option_exists(menu, "g") > -1)
1296 strcpy(exten, "g");
1297 else if (option_exists(menu, "s") > -1)
1298 strcpy(exten, "s");
1300 pos = 0;
1301 continue;
1302 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1303 if (option_debug)
1304 ast_log(LOG_DEBUG, "Got start of extension, %c\n", res);
1305 exten[1] = '\0';
1306 exten[0] = res;
1307 if ((res = read_newoption(chan, menu, exten, sizeof(exten))))
1308 break;
1309 if (option_exists(menu, exten) < 0) {
1310 if (option_exists(menu, "i")) {
1311 if (option_debug)
1312 ast_log(LOG_DEBUG, "Invalid extension entered, going to 'i'!\n");
1313 strcpy(exten, "i");
1314 pos = 0;
1315 continue;
1316 } else {
1317 if (option_debug)
1318 ast_log(LOG_DEBUG, "Aborting on invalid entry, with no 'i' option!\n");
1319 res = -2;
1320 break;
1322 } else {
1323 if (option_debug)
1324 ast_log(LOG_DEBUG, "New existing extension: %s\n", exten);
1325 pos = 0;
1326 continue;
1330 pos++;
1332 if (option_debug)
1333 ast_log(LOG_DEBUG, "Stopping option '%s', res is %d\n", exten, res);
1334 pos = 0;
1335 if (!strcasecmp(exten, "s"))
1336 strcpy(exten, "g");
1337 else
1338 break;
1340 return res;
1343 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1345 int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1346 /* Hide internal coding */
1347 return res > 0 ? 0 : res;
1350 char *ast_read_textfile(const char *filename)
1352 int fd;
1353 char *output = NULL;
1354 struct stat filesize;
1355 int count = 0;
1356 int res;
1357 if (stat(filename, &filesize) == -1) {
1358 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
1359 return NULL;
1361 count = filesize.st_size + 1;
1362 fd = open(filename, O_RDONLY);
1363 if (fd < 0) {
1364 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1365 return NULL;
1367 if ((output = ast_malloc(count))) {
1368 res = read(fd, output, count - 1);
1369 if (res == count - 1) {
1370 output[res] = '\0';
1371 } else {
1372 ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
1373 free(output);
1374 output = NULL;
1377 close(fd);
1378 return output;
1381 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
1383 char *s;
1384 int curarg;
1385 unsigned int argloc;
1386 char *arg;
1387 int res = 0;
1389 ast_clear_flag(flags, AST_FLAGS_ALL);
1391 if (!optstr)
1392 return 0;
1394 s = optstr;
1395 while (*s) {
1396 curarg = *s++ & 0x7f; /* the array (in app.h) has 128 entries */
1397 argloc = options[curarg].arg_index;
1398 if (*s == '(') {
1399 /* Has argument */
1400 arg = ++s;
1401 if ((s = strchr(s, ')'))) {
1402 if (argloc)
1403 args[argloc - 1] = arg;
1404 *s++ = '\0';
1405 } else {
1406 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
1407 res = -1;
1408 break;
1410 } else if (argloc) {
1411 args[argloc - 1] = "";
1413 ast_set_flag(flags, options[curarg].flag);
1416 return res;