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.
21 * \brief Convenient Application Routines
23 * \author Mark Spencer <markster@digium.com>
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #ifdef HAVE_SYS_STAT_H
34 #include <sys/file.h> /* added this to allow to compile, sorry! */
36 #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
37 #include "asterisk/channel.h"
38 #include "asterisk/pbx.h"
39 #include "asterisk/file.h"
40 #include "asterisk/app.h"
41 #include "asterisk/dsp.h"
42 #include "asterisk/utils.h"
43 #include "asterisk/lock.h"
44 #include "asterisk/indications.h"
45 #include "asterisk/linkedlists.h"
47 #define MAX_OTHER_FORMATS 10
49 static AST_RWLIST_HEAD_STATIC(groups, ast_group_info);
52 * \brief This function presents a dialtone and reads an extension into 'collect'
53 * which must be a pointer to a **pre-initialized** array of char having a
54 * size of 'size' suitable for writing to. It will collect no more than the smaller
55 * of 'maxlen' or 'size' minus the original strlen() of collect digits.
61 * \param timeout timeout in seconds
63 * \return 0 if extension does not exist, 1 if extension exists
65 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
67 struct ind_tone_zone_sound *ts;
73 if (!timeout && chan->pbx)
74 timeout = chan->pbx->dtimeout;
78 if ((ts = ast_get_indication_tone(chan->zone, "dial")) && ts->data[0])
79 res = ast_playtones_start(chan, 0, ts->data, 0);
81 ast_log(LOG_NOTICE,"Huh....? no dial for indications?\n");
83 for (x = strlen(collect); x < maxlen; ) {
84 res = ast_waitfordigit(chan, timeout);
85 if (!ast_ignore_pattern(context, collect))
86 ast_playtones_stop(chan);
92 if (!ast_matchmore_extension(chan, context, collect, 1, chan->cid.cid_num))
97 res = ast_exists_extension(chan, context, collect, 1, chan->cid.cid_num) ? 1 : 0;
103 * \brief ast_app_getdata
104 * \param c The channel to read from
105 * \param prompt The file to stream to the channel
106 * \param s The string to read in to. Must be at least the size of your length
107 * \param maxlen How many digits to read (maximum)
108 * \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for
109 * "ludicrous time" (essentially never times out) */
110 int ast_app_getdata(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout)
112 int res = 0, to, fto;
113 char *front, *filename;
115 /* XXX Merge with full version? XXX */
123 filename = ast_strdupa(prompt);
124 while ((front = strsep(&filename, "&"))) {
125 if (!ast_strlen_zero(front)) {
126 res = ast_streamfile(c, front, c->language);
130 if (ast_strlen_zero(filename)) {
131 /* set timeouts for the last prompt */
132 fto = c->pbx ? c->pbx->rtimeout * 1000 : 6000;
133 to = c->pbx ? c->pbx->dtimeout * 1000 : 2000;
138 fto = to = 1000000000;
140 /* there is more than one prompt, so
141 get rid of the long timeout between
142 prompts, and make it 50ms */
144 to = c->pbx ? c->pbx->dtimeout * 1000 : 2000;
146 res = ast_readstring(c, s, maxlen, to, fto, "#");
147 if (!ast_strlen_zero(s))
154 /* The lock type used by ast_lock_path() / ast_unlock_path() */
155 static enum AST_LOCK_TYPE ast_lock_type = AST_LOCK_TYPE_LOCKFILE;
157 int ast_app_getdata_full(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
159 int res, to = 2000, fto = 6000;
161 if (!ast_strlen_zero(prompt)) {
162 res = ast_streamfile(c, prompt, c->language);
170 fto = to = 1000000000;
172 res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
177 static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
178 static int (*ast_inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
179 static int (*ast_messagecount_func)(const char *context, const char *mailbox, const char *folder) = NULL;
181 void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
182 int (*inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs),
183 int (*messagecount_func)(const char *context, const char *mailbox, const char *folder))
185 ast_has_voicemail_func = has_voicemail_func;
186 ast_inboxcount_func = inboxcount_func;
187 ast_messagecount_func = messagecount_func;
190 void ast_uninstall_vm_functions(void)
192 ast_has_voicemail_func = NULL;
193 ast_inboxcount_func = NULL;
194 ast_messagecount_func = NULL;
197 int ast_app_has_voicemail(const char *mailbox, const char *folder)
199 static int warned = 0;
200 if (ast_has_voicemail_func)
201 return ast_has_voicemail_func(mailbox, folder);
204 ast_verb(3, "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
211 int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
213 static int warned = 0;
218 if (ast_inboxcount_func)
219 return ast_inboxcount_func(mailbox, newmsgs, oldmsgs);
223 ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
229 int ast_app_messagecount(const char *context, const char *mailbox, const char *folder)
231 static int warned = 0;
232 if (ast_messagecount_func)
233 return ast_messagecount_func(context, mailbox, folder);
237 ast_verb(3, "Message count requested for mailbox %s@%s/%s but voicemail not loaded.\n", mailbox, context, folder);
243 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between, unsigned int duration)
252 res = ast_autoservice_start(peer);
255 res = ast_waitfor(chan, 100);
257 /* ast_waitfor will return the number of remaining ms on success */
261 for (ptr = digits; *ptr; ptr++) {
263 /* 'w' -- wait half a second */
264 if ((res = ast_safe_sleep(chan, 500)))
266 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
267 /* Character represents valid DTMF */
268 if (*ptr == 'f' || *ptr == 'F') {
269 /* ignore return values if not supported by channel */
270 ast_indicate(chan, AST_CONTROL_FLASH);
272 ast_senddigit(chan, *ptr, duration);
273 /* pause between digits */
274 if ((res = ast_safe_sleep(chan, between)))
277 ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n",*ptr);
281 /* Stop autoservice on the peer channel, but don't overwrite any error condition
282 that has occurred previously while acting on the primary channel */
283 if (ast_autoservice_stop(peer) && !res)
290 struct linear_state {
297 static void linear_release(struct ast_channel *chan, void *params)
299 struct linear_state *ls = params;
301 if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt))
302 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", chan->name, ls->origwfmt);
310 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
312 short buf[2048 + AST_FRIENDLY_OFFSET / 2];
313 struct linear_state *ls = data;
314 struct ast_frame f = {
315 .frametype = AST_FRAME_VOICE,
316 .subclass = AST_FORMAT_SLINEAR,
317 .data = buf + AST_FRIENDLY_OFFSET / 2,
318 .offset = AST_FRIENDLY_OFFSET,
323 if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
324 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" ,len);
325 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
327 res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
338 static void *linear_alloc(struct ast_channel *chan, void *params)
340 struct linear_state *ls = params;
345 /* In this case, params is already malloc'd */
346 if (ls->allowoverride)
347 ast_set_flag(chan, AST_FLAG_WRITE_INT);
349 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
351 ls->origwfmt = chan->writeformat;
353 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
354 ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", chan->name);
362 static struct ast_generator linearstream =
365 release: linear_release,
366 generate: linear_generator,
369 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
371 struct linear_state *lin;
376 if (ast_strlen_zero(filename))
379 if (filename[0] == '/')
380 ast_copy_string(tmpf, filename, sizeof(tmpf));
382 snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", ast_config_AST_DATA_DIR, "sounds", filename);
383 if ((fd = open(tmpf, O_RDONLY)) < 0) {
384 ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
388 if ((lin = ast_calloc(1, sizeof(*lin)))) {
390 lin->allowoverride = allowoverride;
391 lin->autoclose = autoclose;
392 res = ast_activate_generator(chan, &linearstream, lin);
397 int ast_control_streamfile(struct ast_channel *chan, const char *file,
398 const char *fwd, const char *rev,
399 const char *stop, const char *pause,
400 const char *restart, int skipms, long *offsetms)
406 long pause_restart_point = 0;
410 offset = *offsetms * 8; /* XXX Assumes 8kHz */
413 blen += strlen(stop);
415 blen += strlen(pause);
417 blen += strlen(restart);
420 breaks = alloca(blen + 1);
423 strcat(breaks, stop);
425 strcat(breaks, pause);
427 strcat(breaks, restart);
429 if (chan->_state != AST_STATE_UP)
430 res = ast_answer(chan);
433 if ((end = strchr(file,':'))) {
434 if (!strcasecmp(end, ":end")) {
442 ast_stopstream(chan);
443 res = ast_streamfile(chan, file, chan->language);
445 if (pause_restart_point) {
446 ast_seekstream(chan->stream, pause_restart_point, SEEK_SET);
447 pause_restart_point = 0;
449 else if (end || offset < 0) {
452 ast_verb(3, "ControlPlayback seek to offset %ld from end\n", offset);
454 ast_seekstream(chan->stream, offset, SEEK_END);
458 ast_verb(3, "ControlPlayback seek to offset %ld\n", offset);
459 ast_seekstream(chan->stream, offset, SEEK_SET);
462 res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
468 /* We go at next loop if we got the restart char */
469 if (restart && strchr(restart, res)) {
470 ast_debug(1, "we'll restart the stream here at next loop\n");
471 pause_restart_point = 0;
475 if (pause && strchr(pause, res)) {
476 pause_restart_point = ast_tellstream(chan->stream);
478 ast_stopstream(chan);
479 res = ast_waitfordigit(chan, 1000);
482 else if (res == -1 || strchr(pause, res) || (stop && strchr(stop, res)))
494 /* if we get one of our stop chars, return it to the calling function */
495 if (stop && strchr(stop, res))
499 if (pause_restart_point) {
500 offset = pause_restart_point;
503 offset = ast_tellstream(chan->stream);
505 offset = -8; /* indicate end of file */
510 *offsetms = offset / 8; /* samples --> ms ... XXX Assumes 8 kHz */
512 /* If we are returning a digit cast it as char */
513 if (res > 0 || chan->stream)
516 ast_stopstream(chan);
521 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
525 if ((d = ast_streamfile(chan, fn, chan->language)))
528 d = ast_waitstream(chan, AST_DIGIT_ANY);
530 ast_stopstream(chan);
535 static int global_silence_threshold = 128;
536 static int global_maxsilence = 0;
538 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
539 * \param chan Channel to playback to/record from.
540 * \param playfile Filename of sound to play before recording begins.
541 * \param recordfile Filename to record to.
542 * \param maxtime Maximum length of recording (in milliseconds).
543 * \param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
544 * \param duration Where to store actual length of the recorded message (in milliseconds).
545 * \param beep Whether to play a beep before starting to record.
546 * \param silencethreshold
547 * \param maxsilence Length of silence that will end a recording (in milliseconds).
548 * \param path Optional filesystem path to unlock.
549 * \param prepend If true, prepend the recorded audio to an existing file.
550 * \param acceptdtmf DTMF digits that will end the recording.
551 * \param canceldtmf DTMF digits that will cancel the recording.
554 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)
559 int x, fmtcnt = 1, res = -1, outmsg = 0;
560 struct ast_filestream *others[MAX_OTHER_FORMATS];
561 char *sfmt[MAX_OTHER_FORMATS];
562 char *stringp = NULL;
564 struct ast_dsp *sildet = NULL; /* silence detector dsp */
565 int totalsilence = 0;
567 struct ast_silence_generator *silgen = NULL;
568 char prependfile[80];
570 if (silencethreshold < 0)
571 silencethreshold = global_silence_threshold;
574 maxsilence = global_maxsilence;
576 /* barf if no pointer passed to store duration in */
578 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
582 ast_debug(1, "play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
583 snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, chan->name);
585 if (playfile || beep) {
587 d = ast_play_and_wait(chan, playfile);
589 d = ast_stream_and_wait(chan, "beep", "");
595 ast_copy_string(prependfile, recordfile, sizeof(prependfile));
596 strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
599 fmts = ast_strdupa(fmt);
602 strsep(&stringp, "|");
603 ast_debug(1, "Recording Formats: sfmts=%s\n", fmts);
604 sfmt[0] = ast_strdupa(fmts);
606 while ((fmt = strsep(&stringp, "|"))) {
607 if (fmtcnt > MAX_OTHER_FORMATS - 1) {
608 ast_log(LOG_WARNING, "Please increase MAX_OTHER_FORMATS in app.c\n");
611 sfmt[fmtcnt++] = ast_strdupa(fmt);
614 end = start = time(NULL); /* pre-initialize end to be same as start in case we never get into loop */
615 for (x = 0; x < fmtcnt; x++) {
616 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, AST_FILE_MODE);
617 ast_verb(3, "x=%d, open writing: %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
624 ast_unlock_path(path);
626 if (maxsilence > 0) {
627 sildet = ast_dsp_new(); /* Create the silence detector */
629 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
632 ast_dsp_set_threshold(sildet, silencethreshold);
633 rfmt = chan->readformat;
634 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
636 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
637 ast_dsp_free(sildet);
643 /* Request a video update */
644 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
646 if (ast_opt_transmit_silence)
647 silgen = ast_channel_start_silence_generator(chan);
651 /* Loop forever, writing the packets we read to the writer(s), until
652 we read a digit or get a hangup */
655 res = ast_waitfor(chan, 2000);
657 ast_debug(1, "One waitfor failed, trying another\n");
658 /* Try one more time in case of masq */
659 res = ast_waitfor(chan, 2000);
661 ast_log(LOG_WARNING, "No audio available on %s??\n", chan->name);
673 if (f->frametype == AST_FRAME_VOICE) {
674 /* write each format */
675 for (x = 0; x < fmtcnt; x++) {
676 if (prepend && !others[x])
678 res = ast_writestream(others[x], f);
681 /* Silence Detection */
682 if (maxsilence > 0) {
684 ast_dsp_silence(sildet, f, &dspsilence);
686 totalsilence = dspsilence;
690 if (totalsilence > maxsilence) {
691 /* Ended happily with silence */
692 ast_verb(3, "Recording automatically stopped after a silence of %d seconds\n", totalsilence/1000);
698 /* Exit on any error */
700 ast_log(LOG_WARNING, "Error writing frame\n");
703 } else if (f->frametype == AST_FRAME_VIDEO) {
704 /* Write only once */
705 ast_writestream(others[0], f);
706 } else if (f->frametype == AST_FRAME_DTMF) {
708 /* stop recording with any digit */
709 ast_verb(3, "User ended message by pressing %c\n", f->subclass);
714 if (strchr(acceptdtmf, f->subclass)) {
715 ast_verb(3, "User ended message by pressing %c\n", f->subclass);
720 if (strchr(canceldtmf, f->subclass)) {
721 ast_verb(3, "User cancelled message by pressing %c\n", f->subclass);
729 if (maxtime < (end - start)) {
730 ast_verb(3, "Took too long, cutting it short...\n");
739 ast_verb(3, "User hung up\n");
746 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
751 ast_channel_stop_silence_generator(chan, silgen);
755 * Instead of asking how much time passed (end - start), calculate the number
756 * of seconds of audio which actually went into the file. This fixes a
757 * problem where audio is stopped up on the network and never gets to us.
759 * Note that we still want to use the number of seconds passed for the max
760 * message, otherwise we could get a situation where this stream is never
761 * closed (which would create a resource leak).
763 *duration = ast_tellstream(others[0]) / 8000;
766 for (x = 0; x < fmtcnt; x++) {
770 * If we ended with silence, trim all but the first 200ms of silence
771 * off the recording. However, if we ended with '#', we don't want
772 * to trim ANY part of the recording.
774 if (res > 0 && totalsilence)
775 ast_stream_rewind(others[x], totalsilence - 200);
776 ast_truncstream(others[x]);
777 ast_closestream(others[x]);
781 if (prepend && outmsg) {
782 struct ast_filestream *realfiles[MAX_OTHER_FORMATS];
783 struct ast_frame *fr;
785 for (x = 0; x < fmtcnt; x++) {
786 snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
787 realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
788 if (!others[x] || !realfiles[x])
790 /*!\note Same logic as above. */
792 ast_stream_rewind(others[x], totalsilence - 200);
793 ast_truncstream(others[x]);
794 /* add the original file too */
795 while ((fr = ast_readframe(realfiles[x]))) {
796 ast_writestream(others[x], fr);
799 ast_closestream(others[x]);
800 ast_closestream(realfiles[x]);
801 ast_filerename(prependfile, recordfile, sfmt[x]);
802 ast_verb(4, "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
803 ast_filedelete(prependfile, sfmt[x]);
806 if (rfmt && ast_set_read_format(chan, rfmt)) {
807 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(rfmt), chan->name);
810 ast_stream_and_wait(chan, "auth-thankyou", "");
813 ast_dsp_free(sildet);
817 static char default_acceptdtmf[] = "#";
818 static char default_canceldtmf[] = "";
820 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)
822 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));
825 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)
827 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf);
830 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)
832 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf);
835 /* Channel group core functions */
837 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
841 char *grp = NULL, *cat = NULL;
843 if (!ast_strlen_zero(data)) {
844 ast_copy_string(tmp, data, sizeof(tmp));
846 cat = strchr(tmp, '@');
853 if (!ast_strlen_zero(grp))
854 ast_copy_string(group, grp, group_max);
858 if (!ast_strlen_zero(cat))
859 ast_copy_string(category, cat, category_max);
864 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
867 char group[80] = "", category[80] = "";
868 struct ast_group_info *gi = NULL;
871 if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category)))
874 /* Calculate memory we will need if this is new */
875 len = sizeof(*gi) + strlen(group) + 1;
876 if (!ast_strlen_zero(category))
877 len += strlen(category) + 1;
879 AST_RWLIST_WRLOCK(&groups);
880 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, list) {
881 if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
882 AST_RWLIST_REMOVE_CURRENT(list);
887 AST_RWLIST_TRAVERSE_SAFE_END;
889 if (ast_strlen_zero(group)) {
890 /* Enable unsetting the group */
891 } else if ((gi = calloc(1, len))) {
893 gi->group = (char *) gi + sizeof(*gi);
894 strcpy(gi->group, group);
895 if (!ast_strlen_zero(category)) {
896 gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
897 strcpy(gi->category, category);
899 AST_RWLIST_INSERT_TAIL(&groups, gi, list);
904 AST_RWLIST_UNLOCK(&groups);
909 int ast_app_group_get_count(const char *group, const char *category)
911 struct ast_group_info *gi = NULL;
914 if (ast_strlen_zero(group))
917 AST_RWLIST_RDLOCK(&groups);
918 AST_RWLIST_TRAVERSE(&groups, gi, list) {
919 if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category))))
922 AST_RWLIST_UNLOCK(&groups);
927 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
929 struct ast_group_info *gi = NULL;
933 if (ast_strlen_zero(groupmatch))
936 /* if regex compilation fails, return zero matches */
937 if (regcomp(®exbuf, groupmatch, REG_EXTENDED | REG_NOSUB))
940 AST_RWLIST_RDLOCK(&groups);
941 AST_RWLIST_TRAVERSE(&groups, gi, list) {
942 if (!regexec(®exbuf, gi->group, 0, NULL, 0) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category))))
945 AST_RWLIST_UNLOCK(&groups);
952 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
954 struct ast_group_info *gi = NULL;
956 AST_RWLIST_WRLOCK(&groups);
957 AST_RWLIST_TRAVERSE(&groups, gi, list) {
961 AST_RWLIST_UNLOCK(&groups);
966 int ast_app_group_discard(struct ast_channel *chan)
968 struct ast_group_info *gi = NULL;
970 AST_RWLIST_WRLOCK(&groups);
971 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, list) {
972 if (gi->chan == chan) {
973 AST_RWLIST_REMOVE_CURRENT(list);
977 AST_RWLIST_TRAVERSE_SAFE_END;
978 AST_RWLIST_UNLOCK(&groups);
983 int ast_app_group_list_wrlock(void)
985 return AST_RWLIST_WRLOCK(&groups);
988 int ast_app_group_list_rdlock(void)
990 return AST_RWLIST_RDLOCK(&groups);
993 struct ast_group_info *ast_app_group_list_head(void)
995 return AST_RWLIST_FIRST(&groups);
998 int ast_app_group_list_unlock(void)
1000 return AST_RWLIST_UNLOCK(&groups);
1003 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
1007 int paren = 0, quote = 0;
1009 if (!buf || !array || !arraylen)
1012 memset(array, 0, arraylen * sizeof(*array));
1016 for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
1018 for (; *scan; scan++) {
1021 else if (*scan == ')') {
1024 } else if (*scan == '"' && delim != '"') {
1025 quote = quote ? 0 : 1;
1026 /* Remove quote character from argument */
1027 memmove(scan, scan + 1, strlen(scan));
1029 } else if (*scan == '\\') {
1030 /* Literal character, don't parse */
1031 memmove(scan, scan + 1, strlen(scan));
1032 } else if ((*scan == delim) && !paren && !quote) {
1040 array[argc++] = scan;
1045 static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
1051 int lp = strlen(path);
1054 s = alloca(lp + 10);
1055 fs = alloca(lp + 20);
1057 snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
1058 fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
1060 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
1061 return AST_LOCK_PATH_NOT_FOUND;
1065 snprintf(s, strlen(path) + 9, "%s/.lock", path);
1067 while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5))
1073 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
1074 return AST_LOCK_TIMEOUT;
1076 ast_debug(1, "Locked path '%s'\n", path);
1077 return AST_LOCK_SUCCESS;
1081 static int ast_unlock_path_lockfile(const char *path)
1086 s = alloca(strlen(path) + 10);
1088 snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1090 if ((res = unlink(s)))
1091 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
1093 ast_debug(1, "Unlocked path '%s'\n", path);
1100 AST_LIST_ENTRY(path_lock) le;
1105 static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
1107 static void path_lock_destroy(struct path_lock *obj)
1116 static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
1122 struct path_lock *pl;
1123 struct stat st, ost;
1125 fs = alloca(strlen(path) + 20);
1127 snprintf(fs, strlen(path) + 19, "%s/lock", path);
1128 if (lstat(fs, &st) == 0) {
1129 if ((st.st_mode & S_IFMT) == S_IFLNK) {
1130 ast_log(LOG_WARNING, "Unable to create lock file "
1131 "'%s': it's already a symbolic link\n",
1133 return AST_LOCK_FAILURE;
1135 if (st.st_nlink > 1) {
1136 ast_log(LOG_WARNING, "Unable to create lock file "
1137 "'%s': %u hard links exist\n",
1138 fs, (unsigned int) st.st_nlink);
1139 return AST_LOCK_FAILURE;
1142 fd = open(fs, O_WRONLY | O_CREAT, 0600);
1144 ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
1145 fs, strerror(errno));
1146 return AST_LOCK_PATH_NOT_FOUND;
1148 pl = ast_calloc(1, sizeof(*pl));
1150 /* We don't unlink the lock file here, on the possibility that
1151 * someone else created it - better to leave a little mess
1152 * than create a big one by destroying someone else's lock
1153 * and causing something to be corrupted.
1156 return AST_LOCK_FAILURE;
1159 pl->path = strdup(path);
1164 (res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd,F_GETFL)|O_NONBLOCK)) < 0) &&
1166 (res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
1168 (errno == EWOULDBLOCK) &&
1169 (time(NULL) - start < 5))
1172 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
1173 path, strerror(errno));
1174 /* No unlinking of lock done, since we tried and failed to
1177 path_lock_destroy(pl);
1178 return AST_LOCK_TIMEOUT;
1181 /* Check for the race where the file is recreated or deleted out from
1184 if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
1185 st.st_dev != ost.st_dev &&
1186 st.st_ino != ost.st_ino) {
1187 ast_log(LOG_WARNING, "Unable to create lock file '%s': "
1188 "file changed underneath us\n", fs);
1189 path_lock_destroy(pl);
1190 return AST_LOCK_FAILURE;
1193 /* Success: file created, flocked, and is the one we started with */
1194 AST_LIST_LOCK(&path_lock_list);
1195 AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
1196 AST_LIST_UNLOCK(&path_lock_list);
1198 ast_debug(1, "Locked path '%s'\n", path);
1200 return AST_LOCK_SUCCESS;
1203 static int ast_unlock_path_flock(const char *path)
1206 struct path_lock *p;
1208 s = alloca(strlen(path) + 20);
1210 AST_LIST_LOCK(&path_lock_list);
1211 AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
1212 if (!strcmp(p->path, path)) {
1213 AST_LIST_REMOVE_CURRENT(le);
1217 AST_LIST_TRAVERSE_SAFE_END;
1218 AST_LIST_UNLOCK(&path_lock_list);
1221 snprintf(s, strlen(path) + 19, "%s/lock", path);
1223 path_lock_destroy(p);
1224 ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
1226 ast_log(LOG_DEBUG, "Failed to unlock path '%s': "
1227 "lock not found\n", path);
1232 void ast_set_lock_type(enum AST_LOCK_TYPE type)
1234 ast_lock_type = type;
1237 enum AST_LOCK_RESULT ast_lock_path(const char *path)
1239 enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
1241 switch (ast_lock_type) {
1242 case AST_LOCK_TYPE_LOCKFILE:
1243 r = ast_lock_path_lockfile(path);
1245 case AST_LOCK_TYPE_FLOCK:
1246 r = ast_lock_path_flock(path);
1253 int ast_unlock_path(const char *path)
1257 switch (ast_lock_type) {
1258 case AST_LOCK_TYPE_LOCKFILE:
1259 r = ast_unlock_path_lockfile(path);
1261 case AST_LOCK_TYPE_FLOCK:
1262 r = ast_unlock_path_flock(path);
1269 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
1271 int silencethreshold = 128;
1275 int max_attempts = 3;
1278 int message_exists = 0;
1279 /* Note that urgent and private are for flagging messages as such in the future */
1281 /* barf if no pointer passed to store duration in */
1283 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1287 cmd = '3'; /* Want to start by recording */
1289 while ((cmd >= 0) && (cmd != 't')) {
1292 if (!message_exists) {
1293 /* In this case, 1 is to record a message */
1297 ast_stream_and_wait(chan, "vm-msgsaved", "");
1303 ast_verb(3, "Reviewing the recording\n");
1304 cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
1310 ast_verb(3, "Re-recording\n");
1312 ast_verb(3, "Recording\n");
1314 cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path);
1316 /* User has hung up, no options to give */
1321 } else if (cmd == '*') {
1325 /* If all is well, a message exists */
1338 cmd = ast_play_and_wait(chan, "vm-sorry");
1341 if (message_exists) {
1342 cmd = ast_play_and_wait(chan, "vm-review");
1345 cmd = ast_play_and_wait(chan, "vm-torerecord");
1347 cmd = ast_waitfordigit(chan, 600);
1351 cmd = ast_waitfordigit(chan, 6000);
1355 if (attempts > max_attempts) {
1365 #define RES_UPONE (1 << 16)
1366 #define RES_EXIT (1 << 17)
1367 #define RES_REPEAT (1 << 18)
1368 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1370 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1372 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1375 int (*ivr_func)(struct ast_channel *, void *);
1379 switch (option->action) {
1380 case AST_ACTION_UPONE:
1382 case AST_ACTION_EXIT:
1383 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1384 case AST_ACTION_REPEAT:
1385 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1386 case AST_ACTION_RESTART:
1387 return RES_RESTART ;
1388 case AST_ACTION_NOOP:
1390 case AST_ACTION_BACKGROUND:
1391 res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
1393 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1397 case AST_ACTION_PLAYBACK:
1398 res = ast_stream_and_wait(chan, (char *)option->adata, "");
1400 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1404 case AST_ACTION_MENU:
1405 res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata);
1406 /* Do not pass entry errors back up, treat as though it was an "UPONE" */
1410 case AST_ACTION_WAITOPTION:
1411 res = ast_waitfordigit(chan, 1000 * (chan->pbx ? chan->pbx->rtimeout : 10));
1415 case AST_ACTION_CALLBACK:
1416 ivr_func = option->adata;
1417 res = ivr_func(chan, cbdata);
1419 case AST_ACTION_TRANSFER:
1420 res = ast_parseable_goto(chan, option->adata);
1422 case AST_ACTION_PLAYLIST:
1423 case AST_ACTION_BACKLIST:
1425 c = ast_strdupa(option->adata);
1426 while ((n = strsep(&c, ";"))) {
1427 if ((res = ast_stream_and_wait(chan, n,
1428 (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : "")))
1431 ast_stopstream(chan);
1434 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1440 static int option_exists(struct ast_ivr_menu *menu, char *option)
1443 for (x = 0; menu->options[x].option; x++)
1444 if (!strcasecmp(menu->options[x].option, option))
1449 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1452 for (x = 0; menu->options[x].option; x++)
1453 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
1454 (menu->options[x].option[strlen(option)]))
1459 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1463 while (option_matchmore(menu, exten)) {
1464 ms = chan->pbx ? chan->pbx->dtimeout : 5000;
1465 if (strlen(exten) >= maxexten - 1)
1467 res = ast_waitfordigit(chan, ms);
1470 exten[strlen(exten) + 1] = '\0';
1471 exten[strlen(exten)] = res;
1473 return res > 0 ? 0 : res;
1476 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1478 /* Execute an IVR menu structure */
1482 char exten[AST_MAX_EXTENSION] = "s";
1483 if (option_exists(menu, "s") < 0) {
1485 if (option_exists(menu, "g") < 0) {
1486 ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1491 while (menu->options[pos].option) {
1492 if (!strcasecmp(menu->options[pos].option, exten)) {
1493 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1494 ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1497 else if (res & RES_UPONE)
1499 else if (res & RES_EXIT)
1501 else if (res & RES_REPEAT) {
1502 int maxretries = res & 0xffff;
1503 if ((res & RES_RESTART) == RES_RESTART) {
1509 if ((maxretries > 0) && (retries >= maxretries)) {
1510 ast_debug(1, "Max retries %d exceeded\n", maxretries);
1513 if (option_exists(menu, "g") > -1)
1515 else if (option_exists(menu, "s") > -1)
1520 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1521 ast_debug(1, "Got start of extension, %c\n", res);
1524 if ((res = read_newoption(chan, menu, exten, sizeof(exten))))
1526 if (option_exists(menu, exten) < 0) {
1527 if (option_exists(menu, "i")) {
1528 ast_debug(1, "Invalid extension entered, going to 'i'!\n");
1533 ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
1538 ast_debug(1, "New existing extension: %s\n", exten);
1546 ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
1548 if (!strcasecmp(exten, "s"))
1556 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1558 int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1559 /* Hide internal coding */
1560 return res > 0 ? 0 : res;
1563 char *ast_read_textfile(const char *filename)
1565 int fd, count = 0, res;
1566 char *output = NULL;
1567 struct stat filesize;
1569 if (stat(filename, &filesize) == -1) {
1570 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
1574 count = filesize.st_size + 1;
1576 if ((fd = open(filename, O_RDONLY)) < 0) {
1577 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1581 if ((output = ast_malloc(count))) {
1582 res = read(fd, output, count - 1);
1583 if (res == count - 1) {
1586 ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
1597 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
1600 int curarg, res = 0;
1601 unsigned int argloc;
1603 ast_clear_flag(flags, AST_FLAGS_ALL);
1610 curarg = *s++ & 0x7f; /* the array (in app.h) has 128 entries */
1611 argloc = options[curarg].arg_index;
1615 if ((s = strchr(s, ')'))) {
1617 args[argloc - 1] = arg;
1620 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
1624 } else if (argloc) {
1625 args[argloc - 1] = "";
1627 ast_set_flag(flags, options[curarg].flag);
1633 /* the following function will probably only be used in app_dial, until app_dial is reorganized to
1634 better handle the large number of options it provides. After it is, you need to get rid of this variant
1635 -- unless, of course, someone else digs up some use for large flag fields. */
1637 int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
1640 int curarg, res = 0;
1641 unsigned int argloc;
1650 curarg = *s++ & 0x7f; /* the array (in app.h) has 128 entries */
1651 ast_set_flag64(flags, options[curarg].flag);
1652 argloc = options[curarg].arg_index;
1656 if ((s = strchr(s, ')'))) {
1658 args[argloc - 1] = arg;
1661 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
1665 } else if (argloc) {
1666 args[argloc - 1] = NULL;
1673 int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
1678 if (*stream == '\\') {
1680 switch (*(stream + 1)) {
1692 if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
1694 if (*(stream + 2) <= '9')
1695 *result = *(stream + 2) - '0';
1696 else if (*(stream + 2) <= 'F')
1697 *result = *(stream + 2) - 'A' + 10;
1699 *result = *(stream + 2) - 'a' + 10;
1701 ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
1705 if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
1708 if (*(stream + 3) <= '9')
1709 *result += *(stream + 3) - '0';
1710 else if (*(stream + 3) <= 'F')
1711 *result += *(stream + 3) - 'A' + 10;
1713 *result += *(stream + 3) - 'a' + 10;
1719 for (i = 2; ; i++) {
1720 if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
1722 ast_debug(5, "result was %d, ", *result);
1724 *result += *(stream + i) - '0';
1725 ast_debug(5, "is now %d\n", *result);
1731 *result = *(stream + 1);