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>
27 * \par This is an example of how to develop an app.
28 * Application Skeleton is an example of creating an application for Asterisk.
29 * \verbinclude app_skel.c
33 <support_level>core</support_level>
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40 #ifdef HAVE_SYS_STAT_H
43 #include <regex.h> /* for regcomp(3) */
44 #include <sys/file.h> /* for flock(2) */
45 #include <signal.h> /* for pthread_sigmask(3) */
46 #include <stdlib.h> /* for closefrom(3) */
47 #include <sys/types.h>
48 #include <sys/wait.h> /* for waitpid(2) */
49 #ifndef HAVE_CLOSEFROM
50 #include <dirent.h> /* for opendir(3) */
53 #include <sys/capability.h>
56 #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
57 #include "asterisk/channel.h"
58 #include "asterisk/pbx.h"
59 #include "asterisk/file.h"
60 #include "asterisk/app.h"
61 #include "asterisk/dsp.h"
62 #include "asterisk/utils.h"
63 #include "asterisk/lock.h"
64 #include "asterisk/indications.h"
65 #include "asterisk/linkedlists.h"
66 #include "asterisk/threadstorage.h"
67 #include "asterisk/test.h"
68 #include "asterisk/module.h"
69 #include "asterisk/astobj2.h"
70 #include "asterisk/stasis.h"
71 #include "asterisk/stasis_channels.h"
72 #include "asterisk/json.h"
74 #define MWI_TOPIC_BUCKETS 57
76 AST_THREADSTORAGE_PUBLIC(ast_str_thread_global_buf);
78 static pthread_t shaun_of_the_dead_thread = AST_PTHREADT_NULL;
82 AST_LIST_ENTRY(zombie) list;
85 static AST_LIST_HEAD_STATIC(zombies, zombie);
88 * @{ \brief Define \ref stasis topic objects
90 static struct stasis_topic *mwi_topic_all;
91 static struct stasis_cache *mwi_state_cache;
92 static struct stasis_caching_topic *mwi_topic_cached;
93 static struct stasis_topic_pool *mwi_topic_pool;
95 static struct stasis_topic *queue_topic_all;
96 static struct stasis_topic_pool *queue_topic_pool;
100 * @{ \brief Define \ref stasis message types for MWI
102 STASIS_MESSAGE_TYPE_DEFN(ast_mwi_state_type);
103 STASIS_MESSAGE_TYPE_DEFN(ast_mwi_vm_app_type);
108 static void *shaun_of_the_dead(void *data)
113 if (!AST_LIST_EMPTY(&zombies)) {
114 /* Don't allow cancellation while we have a lock. */
115 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
116 AST_LIST_LOCK(&zombies);
117 AST_LIST_TRAVERSE_SAFE_BEGIN(&zombies, cur, list) {
118 if (waitpid(cur->pid, &status, WNOHANG) != 0) {
119 AST_LIST_REMOVE_CURRENT(list);
123 AST_LIST_TRAVERSE_SAFE_END
124 AST_LIST_UNLOCK(&zombies);
125 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
127 pthread_testcancel();
128 /* Wait for 60 seconds, without engaging in a busy loop. */
129 ast_poll(NULL, 0, AST_LIST_FIRST(&zombies) ? 5000 : 60000);
135 #define AST_MAX_FORMATS 10
137 static AST_RWLIST_HEAD_STATIC(groups, ast_group_info);
140 * \brief This function presents a dialtone and reads an extension into 'collect'
141 * which must be a pointer to a **pre-initialized** array of char having a
142 * size of 'size' suitable for writing to. It will collect no more than the smaller
143 * of 'maxlen' or 'size' minus the original strlen() of collect digits.
144 * \param chan struct.
149 * \param timeout timeout in milliseconds
151 * \return 0 if extension does not exist, 1 if extension exists
153 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
155 struct ast_tone_zone_sound *ts;
163 if (ast_channel_pbx(chan) && ast_channel_pbx(chan)->dtimeoutms) {
164 timeout = ast_channel_pbx(chan)->dtimeoutms;
170 if ((ts = ast_get_indication_tone(ast_channel_zone(chan), "dial"))) {
171 res = ast_playtones_start(chan, 0, ts->data, 0);
172 ts = ast_tone_zone_sound_unref(ts);
174 ast_log(LOG_NOTICE, "Huh....? no dial for indications?\n");
177 for (x = strlen(collect); x < maxlen; ) {
178 res = ast_waitfordigit(chan, timeout);
179 if (!ast_ignore_pattern(context, collect)) {
180 ast_playtones_stop(chan);
189 if (!ast_matchmore_extension(chan, context, collect, 1,
190 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
196 res = ast_exists_extension(chan, context, collect, 1,
197 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL)) ? 1 : 0;
204 * \brief ast_app_getdata
205 * \param c The channel to read from
206 * \param prompt The file to stream to the channel
207 * \param s The string to read in to. Must be at least the size of your length
208 * \param maxlen How many digits to read (maximum)
209 * \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for
210 * "ludicrous time" (essentially never times out) */
211 enum ast_getdata_result ast_app_getdata(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout)
213 int res = 0, to, fto;
214 char *front, *filename;
216 /* XXX Merge with full version? XXX */
224 filename = ast_strdupa(prompt);
225 while ((front = strsep(&filename, "&"))) {
226 ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", front, ast_channel_name(c));
227 if (!ast_strlen_zero(front)) {
228 res = ast_streamfile(c, front, ast_channel_language(c));
232 if (ast_strlen_zero(filename)) {
233 /* set timeouts for the last prompt */
234 fto = ast_channel_pbx(c) ? ast_channel_pbx(c)->rtimeoutms : 6000;
235 to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
241 fto = to = 1000000000;
244 /* there is more than one prompt, so
245 * get rid of the long timeout between
246 * prompts, and make it 50ms */
248 to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
250 res = ast_readstring(c, s, maxlen, to, fto, "#");
251 if (res == AST_GETDATA_EMPTY_END_TERMINATED) {
254 if (!ast_strlen_zero(s)) {
262 /* The lock type used by ast_lock_path() / ast_unlock_path() */
263 static enum AST_LOCK_TYPE ast_lock_type = AST_LOCK_TYPE_LOCKFILE;
265 int ast_app_getdata_full(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
267 int res, to = 2000, fto = 6000;
269 if (!ast_strlen_zero(prompt)) {
270 res = ast_streamfile(c, prompt, ast_channel_language(c));
280 fto = to = 1000000000;
283 res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
288 int ast_app_exec_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char *macro_args)
290 struct ast_app *macro_app;
293 macro_app = pbx_findapp("Macro");
296 "Cannot run 'Macro(%s)'. The application is not available.\n", macro_args);
299 if (autoservice_chan) {
300 ast_autoservice_start(autoservice_chan);
303 ast_debug(4, "%s Original location: %s,%s,%d\n", ast_channel_name(macro_chan),
304 ast_channel_context(macro_chan), ast_channel_exten(macro_chan),
305 ast_channel_priority(macro_chan));
307 res = pbx_exec(macro_chan, macro_app, macro_args);
308 ast_debug(4, "Macro exited with status %d\n", res);
311 * Assume anything negative from Macro is an error.
312 * Anything else is success.
320 ast_debug(4, "%s Ending location: %s,%s,%d\n", ast_channel_name(macro_chan),
321 ast_channel_context(macro_chan), ast_channel_exten(macro_chan),
322 ast_channel_priority(macro_chan));
324 if (autoservice_chan) {
325 ast_autoservice_stop(autoservice_chan);
330 int ast_app_run_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char *macro_name, const char *macro_args)
336 if (ast_strlen_zero(macro_args)) {
337 return ast_app_exec_macro(autoservice_chan, macro_chan, macro_name);
340 /* Create the Macro application argument string. */
341 args_len = strlen(macro_name) + strlen(macro_args) + 2;
342 args_str = ast_malloc(args_len);
346 snprintf(args_str, args_len, "%s,%s", macro_name, macro_args);
348 res = ast_app_exec_macro(autoservice_chan, macro_chan, args_str);
353 static const struct ast_app_stack_funcs *app_stack_callbacks;
355 void ast_install_stack_functions(const struct ast_app_stack_funcs *funcs)
357 app_stack_callbacks = funcs;
360 const char *ast_app_expand_sub_args(struct ast_channel *chan, const char *args)
362 const struct ast_app_stack_funcs *funcs;
363 const char *new_args;
365 funcs = app_stack_callbacks;
366 if (!funcs || !funcs->expand_sub_args) {
368 "Cannot expand 'Gosub(%s)' arguments. The app_stack module is not available.\n",
372 ast_module_ref(funcs->module);
374 new_args = funcs->expand_sub_args(chan, args);
375 ast_module_unref(funcs->module);
379 int ast_app_exec_sub(struct ast_channel *autoservice_chan, struct ast_channel *sub_chan, const char *sub_args, int ignore_hangup)
381 const struct ast_app_stack_funcs *funcs;
384 funcs = app_stack_callbacks;
385 if (!funcs || !funcs->run_sub) {
387 "Cannot run 'Gosub(%s)'. The app_stack module is not available.\n",
391 ast_module_ref(funcs->module);
393 if (autoservice_chan) {
394 ast_autoservice_start(autoservice_chan);
397 res = funcs->run_sub(sub_chan, sub_args, ignore_hangup);
398 ast_module_unref(funcs->module);
400 if (autoservice_chan) {
401 ast_autoservice_stop(autoservice_chan);
406 int ast_app_run_sub(struct ast_channel *autoservice_chan, struct ast_channel *sub_chan, const char *sub_location, const char *sub_args, int ignore_hangup)
412 if (ast_strlen_zero(sub_args)) {
413 return ast_app_exec_sub(autoservice_chan, sub_chan, sub_location, ignore_hangup);
416 /* Create the Gosub application argument string. */
417 args_len = strlen(sub_location) + strlen(sub_args) + 3;
418 args_str = ast_malloc(args_len);
422 snprintf(args_str, args_len, "%s(%s)", sub_location, sub_args);
424 res = ast_app_exec_sub(autoservice_chan, sub_chan, args_str, ignore_hangup);
429 /*! \brief The container for the voicemail provider */
430 static AO2_GLOBAL_OBJ_STATIC(vm_provider);
432 /*! Voicemail not registered warning */
433 static int vm_warnings;
435 int ast_vm_is_registered(void)
437 struct ast_vm_functions *table;
440 table = ao2_global_obj_ref(vm_provider);
441 is_registered = table ? 1 : 0;
443 return is_registered;
446 int __ast_vm_register(const struct ast_vm_functions *vm_table, struct ast_module *module)
448 RAII_VAR(struct ast_vm_functions *, table, NULL, ao2_cleanup);
450 if (!vm_table->module_name) {
451 ast_log(LOG_ERROR, "Voicemail provider missing required information.\n");
454 if (vm_table->module_version != VM_MODULE_VERSION) {
455 ast_log(LOG_ERROR, "Voicemail provider '%s' has incorrect version\n",
456 vm_table->module_name);
460 table = ao2_global_obj_ref(vm_provider);
462 ast_log(LOG_WARNING, "Voicemail provider already registered by %s.\n",
467 table = ao2_alloc_options(sizeof(*table), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
472 table->module = module;
474 ao2_global_obj_replace_unref(vm_provider, table);
478 void ast_vm_unregister(const char *module_name)
480 struct ast_vm_functions *table;
482 table = ao2_global_obj_ref(vm_provider);
483 if (table && !strcmp(table->module_name, module_name)) {
484 ao2_global_obj_release(vm_provider);
489 #ifdef TEST_FRAMEWORK
490 static ast_vm_test_create_user_fn *ast_vm_test_create_user_func = NULL;
491 static ast_vm_test_destroy_user_fn *ast_vm_test_destroy_user_func = NULL;
493 void ast_install_vm_test_functions(ast_vm_test_create_user_fn *vm_test_create_user_func,
494 ast_vm_test_destroy_user_fn *vm_test_destroy_user_func)
496 ast_vm_test_create_user_func = vm_test_create_user_func;
497 ast_vm_test_destroy_user_func = vm_test_destroy_user_func;
500 void ast_uninstall_vm_test_functions(void)
502 ast_vm_test_create_user_func = NULL;
503 ast_vm_test_destroy_user_func = NULL;
507 static void vm_warn_no_provider(void)
509 if (vm_warnings++ % 10 == 0) {
510 ast_verb(3, "No voicemail provider registered.\n");
514 #define VM_API_CALL(res, api_call, api_parms) \
516 struct ast_vm_functions *table = ao2_global_obj_ref(vm_provider); \
518 vm_warn_no_provider(); \
519 } else if (table->api_call) { \
520 ast_module_ref(table->module); \
521 (res) = table->api_call api_parms; \
522 ast_module_unref(table->module); \
524 ao2_cleanup(table); \
527 int ast_app_has_voicemail(const char *mailboxes, const char *folder)
531 VM_API_CALL(res, has_voicemail, (mailboxes, folder));
537 * \brief Function used as a callback for ast_copy_recording_to_vm when a real one isn't installed.
538 * \param vm_rec_data Stores crucial information about the voicemail that will basically just be used
539 * to figure out what the name of the recipient was supposed to be
541 int ast_app_copy_recording_to_vm(struct ast_vm_recording_data *vm_rec_data)
545 VM_API_CALL(res, copy_recording_to_vm, (vm_rec_data));
549 int ast_app_inboxcount(const char *mailboxes, int *newmsgs, int *oldmsgs)
560 VM_API_CALL(res, inboxcount, (mailboxes, newmsgs, oldmsgs));
564 int ast_app_inboxcount2(const char *mailboxes, int *urgentmsgs, int *newmsgs, int *oldmsgs)
578 VM_API_CALL(res, inboxcount2, (mailboxes, urgentmsgs, newmsgs, oldmsgs));
582 int ast_app_sayname(struct ast_channel *chan, const char *mailbox, const char *context)
586 VM_API_CALL(res, sayname, (chan, mailbox, context));
590 int ast_app_messagecount(const char *mailbox_id, const char *folder)
594 VM_API_CALL(res, messagecount, (mailbox_id, folder));
598 const char *ast_vm_index_to_foldername(int id)
600 const char *res = NULL;
602 VM_API_CALL(res, index_to_foldername, (id));
606 struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_create(const char *mailbox,
610 enum ast_vm_snapshot_sort_val sort_val,
611 int combine_INBOX_and_OLD)
613 struct ast_vm_mailbox_snapshot *res = NULL;
615 VM_API_CALL(res, mailbox_snapshot_create, (mailbox, context, folder, descending,
616 sort_val, combine_INBOX_and_OLD));
620 struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_destroy(struct ast_vm_mailbox_snapshot *mailbox_snapshot)
622 struct ast_vm_mailbox_snapshot *res = NULL;
624 VM_API_CALL(res, mailbox_snapshot_destroy, (mailbox_snapshot));
628 int ast_vm_msg_move(const char *mailbox,
631 const char *oldfolder,
632 const char *old_msg_ids[],
633 const char *newfolder)
637 VM_API_CALL(res, msg_move, (mailbox, context, num_msgs, oldfolder, old_msg_ids,
642 int ast_vm_msg_remove(const char *mailbox,
650 VM_API_CALL(res, msg_remove, (mailbox, context, num_msgs, folder, msgs));
654 int ast_vm_msg_forward(const char *from_mailbox,
655 const char *from_context,
656 const char *from_folder,
657 const char *to_mailbox,
658 const char *to_context,
659 const char *to_folder,
661 const char *msg_ids[],
666 VM_API_CALL(res, msg_forward, (from_mailbox, from_context, from_folder, to_mailbox,
667 to_context, to_folder, num_msgs, msg_ids, delete_old));
671 int ast_vm_msg_play(struct ast_channel *chan,
676 ast_vm_msg_play_cb *cb)
680 VM_API_CALL(res, msg_play, (chan, mailbox, context, folder, msg_num, cb));
684 #ifdef TEST_FRAMEWORK
685 int ast_vm_test_create_user(const char *context, const char *mailbox)
687 if (ast_vm_test_create_user_func) {
688 return ast_vm_test_create_user_func(context, mailbox);
693 int ast_vm_test_destroy_user(const char *context, const char *mailbox)
695 if (ast_vm_test_destroy_user_func) {
696 return ast_vm_test_destroy_user_func(context, mailbox);
702 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between, unsigned int duration)
706 struct ast_silence_generator *silgen = NULL;
712 if (peer && ast_autoservice_start(peer)) {
716 /* Need a quiet time before sending digits. */
717 if (ast_opt_transmit_silence) {
718 silgen = ast_channel_start_silence_generator(chan);
720 res = ast_safe_sleep(chan, 100);
722 goto dtmf_stream_cleanup;
725 for (ptr = digits; *ptr; ptr++) {
727 /* 'w' -- wait half a second */
728 if ((res = ast_safe_sleep(chan, 500))) {
731 } else if (*ptr == 'W') {
732 /* 'W' -- wait a second */
733 if ((res = ast_safe_sleep(chan, 1000))) {
736 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
737 if (*ptr == 'f' || *ptr == 'F') {
738 /* ignore return values if not supported by channel */
739 ast_indicate(chan, AST_CONTROL_FLASH);
741 /* Character represents valid DTMF */
742 ast_senddigit(chan, *ptr, duration);
744 /* pause between digits */
745 if ((res = ast_safe_sleep(chan, between))) {
749 ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n", *ptr);
755 ast_channel_stop_silence_generator(chan, silgen);
757 if (peer && ast_autoservice_stop(peer)) {
764 struct linear_state {
768 struct ast_format origwfmt;
771 static void linear_release(struct ast_channel *chan, void *params)
773 struct linear_state *ls = params;
775 if (ls->origwfmt.id && ast_set_write_format(chan, &ls->origwfmt)) {
776 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", ast_channel_name(chan), ls->origwfmt.id);
786 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
788 short buf[2048 + AST_FRIENDLY_OFFSET / 2];
789 struct linear_state *ls = data;
790 struct ast_frame f = {
791 .frametype = AST_FRAME_VOICE,
792 .data.ptr = buf + AST_FRIENDLY_OFFSET / 2,
793 .offset = AST_FRIENDLY_OFFSET,
797 ast_format_set(&f.subclass.format, AST_FORMAT_SLINEAR, 0);
800 if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
801 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" , len);
802 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
804 res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
816 static void *linear_alloc(struct ast_channel *chan, void *params)
818 struct linear_state *ls = params;
824 /* In this case, params is already malloc'd */
825 if (ls->allowoverride) {
826 ast_set_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
828 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
831 ast_format_copy(&ls->origwfmt, ast_channel_writeformat(chan));
833 if (ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR)) {
834 ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", ast_channel_name(chan));
842 static struct ast_generator linearstream =
844 .alloc = linear_alloc,
845 .release = linear_release,
846 .generate = linear_generator,
849 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
851 struct linear_state *lin;
856 if (ast_strlen_zero(filename)) {
860 if (filename[0] == '/') {
861 ast_copy_string(tmpf, filename, sizeof(tmpf));
863 snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", ast_config_AST_DATA_DIR, "sounds", filename);
865 if ((fd = open(tmpf, O_RDONLY)) < 0) {
866 ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
870 if ((lin = ast_calloc(1, sizeof(*lin)))) {
872 lin->allowoverride = allowoverride;
873 lin->autoclose = autoclose;
874 res = ast_activate_generator(chan, &linearstream, lin);
879 static int control_streamfile(struct ast_channel *chan,
889 ast_waitstream_fr_cb cb)
895 long pause_restart_point = 0;
902 offset = *offsetms * 8; /* XXX Assumes 8kHz */
905 lang = ast_channel_language(chan);
909 blen += strlen(stop);
912 blen += strlen(suspend);
915 blen += strlen(restart);
919 breaks = ast_alloca(blen + 1);
922 strcat(breaks, stop);
925 strcat(breaks, suspend);
928 strcat(breaks, restart);
931 if (ast_channel_state(chan) != AST_STATE_UP) {
932 res = ast_answer(chan);
935 if ((end = strchr(file, ':'))) {
936 if (!strcasecmp(end, ":end")) {
943 ast_stopstream(chan);
944 res = ast_streamfile(chan, file, lang);
946 if (pause_restart_point) {
947 ast_seekstream(ast_channel_stream(chan), pause_restart_point, SEEK_SET);
948 pause_restart_point = 0;
950 else if (end || offset < 0) {
954 ast_verb(3, "ControlPlayback seek to offset %ld from end\n", offset);
956 ast_seekstream(ast_channel_stream(chan), offset, SEEK_END);
960 ast_verb(3, "ControlPlayback seek to offset %ld\n", offset);
961 ast_seekstream(ast_channel_stream(chan), offset, SEEK_SET);
965 res = ast_waitstream_fr_w_cb(chan, breaks, fwd, rev, skipms, cb);
967 res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
975 /* We go at next loop if we got the restart char */
976 if ((restart && strchr(restart, res)) || res == AST_CONTROL_STREAM_RESTART) {
977 ast_debug(1, "we'll restart the stream here at next loop\n");
978 pause_restart_point = 0;
979 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
981 ast_channel_name(chan),
986 if ((suspend && strchr(suspend, res)) || res == AST_CONTROL_STREAM_SUSPEND) {
987 pause_restart_point = ast_tellstream(ast_channel_stream(chan));
988 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
990 ast_channel_name(chan),
993 ast_stopstream(chan);
994 if (!(res = ast_waitfordigit(chan, 1000))) {
996 } else if (res == -1 || (suspend && strchr(suspend, res)) || (stop && strchr(stop, res))
997 || res == AST_CONTROL_STREAM_SUSPEND || res == AST_CONTROL_STREAM_STOP) {
1001 if ((suspend && (res == *suspend)) || res == AST_CONTROL_STREAM_SUSPEND) {
1003 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1005 ast_channel_name(chan),
1015 /* if we get one of our stop chars, return it to the calling function */
1016 if ((stop && strchr(stop, res)) || res == AST_CONTROL_STREAM_STOP) {
1017 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1019 ast_channel_name(chan),
1025 if (pause_restart_point) {
1026 offset = pause_restart_point;
1028 if (ast_channel_stream(chan)) {
1029 offset = ast_tellstream(ast_channel_stream(chan));
1031 offset = -8; /* indicate end of file */
1036 *offsetms = offset / 8; /* samples --> ms ... XXX Assumes 8 kHz */
1039 ast_stopstream(chan);
1044 int ast_control_streamfile_w_cb(struct ast_channel *chan,
1049 const char *suspend,
1050 const char *restart,
1053 ast_waitstream_fr_cb cb)
1055 return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, NULL, cb);
1058 int ast_control_streamfile(struct ast_channel *chan, const char *file,
1059 const char *fwd, const char *rev,
1060 const char *stop, const char *suspend,
1061 const char *restart, int skipms, long *offsetms)
1063 return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, NULL, NULL);
1066 int ast_control_streamfile_lang(struct ast_channel *chan, const char *file,
1067 const char *fwd, const char *rev, const char *stop, const char *suspend,
1068 const char *restart, int skipms, const char *lang, long *offsetms)
1070 return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, lang, NULL);
1073 enum control_tone_frame_response_result {
1074 CONTROL_TONE_RESPONSE_FAILED = -1,
1075 CONTROL_TONE_RESPONSE_NORMAL = 0,
1076 CONTROL_TONE_RESPONSE_FINISHED = 1,
1079 static enum control_tone_frame_response_result control_tone_frame_response(struct ast_channel *chan, struct ast_frame *fr, struct ast_tone_zone_sound *ts, const char *tone, int *paused)
1081 switch (fr->subclass.integer) {
1082 case AST_CONTROL_STREAM_STOP:
1083 ast_playtones_stop(chan);
1084 return CONTROL_TONE_RESPONSE_FINISHED;
1085 case AST_CONTROL_STREAM_SUSPEND:
1088 if (ast_playtones_start(chan, 0, ts ? ts->data : tone, 0)) {
1089 return CONTROL_TONE_RESPONSE_FAILED;
1093 ast_playtones_stop(chan);
1095 return CONTROL_TONE_RESPONSE_NORMAL;
1096 case AST_CONTROL_STREAM_RESTART:
1097 ast_playtones_stop(chan);
1098 if (ast_playtones_start(chan, 0, ts ? ts->data : tone, 0)) {
1099 return CONTROL_TONE_RESPONSE_FAILED;
1101 return CONTROL_TONE_RESPONSE_NORMAL;
1102 case AST_CONTROL_STREAM_REVERSE:
1103 ast_log(LOG_NOTICE, "Media control operation 'reverse' not supported for media type 'tone'\n");
1104 return CONTROL_TONE_RESPONSE_NORMAL;
1105 case AST_CONTROL_STREAM_FORWARD:
1106 ast_log(LOG_NOTICE, "Media control operation 'forward' not supported for media type 'tone'\n");
1107 return CONTROL_TONE_RESPONSE_NORMAL;
1108 case AST_CONTROL_HANGUP:
1109 case AST_CONTROL_BUSY:
1110 case AST_CONTROL_CONGESTION:
1111 return CONTROL_TONE_RESPONSE_FINISHED;
1114 return CONTROL_TONE_RESPONSE_NORMAL;
1117 static int parse_tone_uri(char *tone_parser,
1118 const char **tone_indication,
1119 const char **tone_zone)
1121 *tone_indication = strsep(&tone_parser, ";");
1123 if (ast_strlen_zero(tone_parser)) {
1124 /* Only the indication is included */
1128 if (!(strncmp(tone_parser, "tonezone=", 9))) {
1129 *tone_zone = tone_parser + 9;
1131 ast_log(LOG_ERROR, "Unexpected Tone URI component: %s\n", tone_parser);
1138 int ast_control_tone(struct ast_channel *chan, const char *tone)
1140 struct ast_tone_zone *zone = NULL;
1141 struct ast_tone_zone_sound *ts;
1145 const char *tone_indication = NULL;
1146 const char *tone_zone = NULL;
1147 char *tone_uri_parser;
1149 if (ast_strlen_zero(tone)) {
1153 tone_uri_parser = ast_strdupa(tone);
1155 if (parse_tone_uri(tone_uri_parser, &tone_indication, &tone_zone)) {
1160 zone = ast_get_indication_zone(tone_zone);
1163 ts = ast_get_indication_tone(zone ? zone : ast_channel_zone(chan), tone_indication);
1165 if (ast_playtones_start(chan, 0, ts ? ts->data : tone_indication, 0)) {
1170 struct ast_frame *fr;
1173 if (ast_waitfor(chan, -1) < 0) {
1178 fr = ast_read_noaudio(chan);
1185 if (fr->frametype != AST_FRAME_CONTROL) {
1189 res = control_tone_frame_response(chan, fr, ts, tone_indication, &paused);
1190 if (res == CONTROL_TONE_RESPONSE_FINISHED) {
1193 } else if (res == CONTROL_TONE_RESPONSE_FAILED) {
1200 ast_tone_zone_sound_unref(ts);
1204 ast_tone_zone_unref(zone);
1210 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
1214 ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", fn, ast_channel_name(chan));
1215 if ((d = ast_streamfile(chan, fn, ast_channel_language(chan)))) {
1219 d = ast_waitstream(chan, AST_DIGIT_ANY);
1221 ast_stopstream(chan);
1227 * \brief Construct a silence frame of the same duration as \a orig.
1229 * The \a orig frame must be \ref AST_FORMAT_SLINEAR.
1231 * \param orig Frame as basis for silence to generate.
1232 * \return New frame of silence; free with ast_frfree().
1233 * \return \c NULL on error.
1235 static struct ast_frame *make_silence(const struct ast_frame *orig)
1237 struct ast_frame *silence;
1241 struct ast_frame *next;
1247 if (orig->subclass.format.id != AST_FORMAT_SLINEAR) {
1248 ast_log(LOG_WARNING, "Attempting to silence non-slin frame\n");
1252 for (next = AST_LIST_NEXT(orig, frame_list);
1254 orig = next, next = orig ? AST_LIST_NEXT(orig, frame_list) : NULL) {
1255 samples += orig->samples;
1258 ast_verb(4, "Silencing %zd samples\n", samples);
1261 datalen = sizeof(short) * samples;
1262 size = sizeof(*silence) + datalen;
1263 silence = ast_calloc(1, size);
1268 silence->mallocd = AST_MALLOCD_HDR;
1269 silence->frametype = AST_FRAME_VOICE;
1270 silence->data.ptr = (void *)(silence + 1);
1271 silence->samples = samples;
1272 silence->datalen = datalen;
1274 ast_format_set(&silence->subclass.format, AST_FORMAT_SLINEAR, 0);
1280 * \brief Sets a channel's read format to \ref AST_FORMAT_SLINEAR, recording
1281 * its original format.
1283 * \param chan Channel to modify.
1284 * \param[out] orig_format Output variable to store channel's original read
1286 * \return 0 on success.
1287 * \return -1 on error.
1289 static int set_read_to_slin(struct ast_channel *chan, struct ast_format *orig_format)
1291 if (!chan || !orig_format) {
1294 ast_format_copy(orig_format, ast_channel_readformat(chan));
1295 return ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
1298 static int global_silence_threshold = 128;
1299 static int global_maxsilence = 0;
1301 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
1302 * \param chan Channel to playback to/record from.
1303 * \param playfile Filename of sound to play before recording begins.
1304 * \param recordfile Filename to record to.
1305 * \param maxtime Maximum length of recording (in seconds).
1306 * \param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
1307 * \param duration Where to store actual length of the recorded message (in milliseconds).
1308 * \param sound_duration Where to store the length of the recorded message (in milliseconds), minus any silence
1309 * \param beep Whether to play a beep before starting to record.
1310 * \param silencethreshold
1311 * \param maxsilence Length of silence that will end a recording (in milliseconds).
1312 * \param path Optional filesystem path to unlock.
1313 * \param prepend If true, prepend the recorded audio to an existing file and follow prepend mode recording rules
1314 * \param acceptdtmf DTMF digits that will end the recording.
1315 * \param canceldtmf DTMF digits that will cancel the recording.
1316 * \param skip_confirmation_sound If true, don't play auth-thankyou at end. Nice for custom recording prompts in apps.
1318 * \retval -1 failure or hangup
1319 * \retval 'S' Recording ended from silence timeout
1320 * \retval 't' Recording ended from the message exceeding the maximum duration, or via DTMF in prepend mode
1321 * \retval dtmfchar Recording ended via the return value's DTMF character for either cancel or accept.
1323 static int __ast_play_and_record(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int *sound_duration, int beep, int silencethreshold, int maxsilence, const char *path, int prepend, const char *acceptdtmf, const char *canceldtmf, int skip_confirmation_sound, enum ast_record_if_exists if_exists)
1328 int x, fmtcnt = 1, res = -1, outmsg = 0;
1329 struct ast_filestream *others[AST_MAX_FORMATS];
1330 char *sfmt[AST_MAX_FORMATS];
1331 char *stringp = NULL;
1333 struct ast_dsp *sildet = NULL; /* silence detector dsp */
1334 int totalsilence = 0;
1336 int olddspsilence = 0;
1337 struct ast_format rfmt;
1338 struct ast_silence_generator *silgen = NULL;
1339 char prependfile[PATH_MAX];
1340 int ioflags; /* IO flags for writing output file */
1342 ioflags = O_CREAT|O_WRONLY;
1344 switch (if_exists) {
1345 case AST_RECORD_IF_EXISTS_FAIL:
1348 case AST_RECORD_IF_EXISTS_OVERWRITE:
1351 case AST_RECORD_IF_EXISTS_APPEND:
1352 ioflags |= O_APPEND;
1356 ast_format_clear(&rfmt);
1357 if (silencethreshold < 0) {
1358 silencethreshold = global_silence_threshold;
1361 if (maxsilence < 0) {
1362 maxsilence = global_maxsilence;
1365 /* barf if no pointer passed to store duration in */
1367 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
1371 ast_debug(1, "play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
1372 snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, ast_channel_name(chan));
1374 if (playfile || beep) {
1376 d = ast_play_and_wait(chan, playfile);
1379 d = ast_stream_and_wait(chan, "beep", "");
1387 ast_copy_string(prependfile, recordfile, sizeof(prependfile));
1388 strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
1391 fmts = ast_strdupa(fmt);
1394 strsep(&stringp, "|");
1395 ast_debug(1, "Recording Formats: sfmts=%s\n", fmts);
1396 sfmt[0] = ast_strdupa(fmts);
1398 while ((fmt = strsep(&stringp, "|"))) {
1399 if (fmtcnt > AST_MAX_FORMATS - 1) {
1400 ast_log(LOG_WARNING, "Please increase AST_MAX_FORMATS in file.h\n");
1403 sfmt[fmtcnt++] = ast_strdupa(fmt);
1406 end = start = time(NULL); /* pre-initialize end to be same as start in case we never get into loop */
1407 for (x = 0; x < fmtcnt; x++) {
1408 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, ioflags, 0, AST_FILE_MODE);
1409 ast_verb(3, "x=%d, open writing: %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
1417 ast_unlock_path(path);
1420 if (maxsilence > 0) {
1421 sildet = ast_dsp_new(); /* Create the silence detector */
1423 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
1426 ast_dsp_set_threshold(sildet, silencethreshold);
1427 res = set_read_to_slin(chan, &rfmt);
1429 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
1430 ast_dsp_free(sildet);
1436 /* Request a video update */
1437 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
1439 if (ast_opt_transmit_silence) {
1440 silgen = ast_channel_start_silence_generator(chan);
1445 /* Loop, writing the packets we read to the writer(s), until
1446 * we have reason to stop. */
1447 struct ast_frame *f;
1450 time_t pause_start = 0;
1451 int paused_secs = 0;
1452 int pausedsilence = 0;
1455 if (!(res = ast_waitfor(chan, 2000))) {
1456 ast_debug(1, "One waitfor failed, trying another\n");
1457 /* Try one more time in case of masq */
1458 if (!(res = ast_waitfor(chan, 2000))) {
1459 ast_log(LOG_WARNING, "No audio available on %s??\n", ast_channel_name(chan));
1468 if (!(f = ast_read(chan))) {
1471 if (f->frametype == AST_FRAME_VOICE) {
1472 /* write each format */
1477 RAII_VAR(struct ast_frame *, silence, NULL, ast_frame_dtor);
1478 struct ast_frame *orig = f;
1481 silence = make_silence(orig);
1483 ast_log(LOG_WARNING,
1484 "Error creating silence\n");
1489 for (x = 0; x < fmtcnt; x++) {
1490 if (prepend && !others[x]) {
1493 res = ast_writestream(others[x], f);
1498 /* Silence Detection */
1499 if (maxsilence > 0) {
1501 ast_dsp_silence(sildet, f, &dspsilence);
1502 if (olddspsilence > dspsilence) {
1503 totalsilence += olddspsilence;
1505 olddspsilence = dspsilence;
1508 /* record how much silence there was while we are paused */
1509 pausedsilence = dspsilence;
1510 } else if (dspsilence > pausedsilence) {
1511 /* ignore the paused silence */
1512 dspsilence -= pausedsilence;
1514 /* dspsilence has reset, reset pausedsilence */
1518 if (dspsilence > maxsilence) {
1519 /* Ended happily with silence */
1520 ast_verb(3, "Recording automatically stopped after a silence of %d seconds\n", dspsilence/1000);
1526 /* Exit on any error */
1528 ast_log(LOG_WARNING, "Error writing frame\n");
1531 } else if (f->frametype == AST_FRAME_VIDEO) {
1532 /* Write only once */
1533 ast_writestream(others[0], f);
1534 } else if (f->frametype == AST_FRAME_DTMF) {
1536 /* stop recording with any digit */
1537 ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
1542 if (strchr(acceptdtmf, f->subclass.integer)) {
1543 ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
1544 res = f->subclass.integer;
1548 if (strchr(canceldtmf, f->subclass.integer)) {
1549 ast_verb(3, "User canceled message by pressing %c\n", f->subclass.integer);
1550 res = f->subclass.integer;
1554 } else if (f->frametype == AST_FRAME_CONTROL) {
1555 if (f->subclass.integer == AST_CONTROL_RECORD_CANCEL) {
1556 ast_verb(3, "Message canceled by control\n");
1557 outmsg = 0; /* cancels the recording */
1560 } else if (f->subclass.integer == AST_CONTROL_RECORD_STOP) {
1561 ast_verb(3, "Message ended by control\n");
1564 } else if (f->subclass.integer == AST_CONTROL_RECORD_SUSPEND) {
1566 ast_verb(3, "Message %spaused by control\n",
1567 paused ? "" : "un");
1569 pause_start = time(NULL);
1571 paused_secs += time(NULL) - pause_start;
1573 } else if (f->subclass.integer == AST_CONTROL_RECORD_MUTE) {
1575 ast_verb(3, "Message %smuted by control\n",
1577 /* We can only silence slin frames, so
1578 * set the mode, if we haven't already
1581 if (muted && !rfmt.id) {
1582 ast_verb(3, "Setting read format to linear mode\n");
1583 res = set_read_to_slin(chan, &rfmt);
1585 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
1591 if (maxtime && !paused) {
1593 if (maxtime < (end - start - paused_secs)) {
1594 ast_verb(3, "Took too long, cutting it short...\n");
1603 ast_verb(3, "User hung up\n");
1610 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
1615 ast_channel_stop_silence_generator(chan, silgen);
1620 * Instead of asking how much time passed (end - start), calculate the number
1621 * of seconds of audio which actually went into the file. This fixes a
1622 * problem where audio is stopped up on the network and never gets to us.
1624 * Note that we still want to use the number of seconds passed for the max
1625 * message, otherwise we could get a situation where this stream is never
1626 * closed (which would create a resource leak).
1628 *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
1629 if (sound_duration) {
1630 *sound_duration = *duration;
1634 /* Reduce duration by a total silence amount */
1635 if (olddspsilence <= dspsilence) {
1636 totalsilence += dspsilence;
1639 if (sound_duration) {
1640 if (totalsilence > 0) {
1641 *sound_duration -= (totalsilence - 200) / 1000;
1643 if (*sound_duration < 0) {
1644 *sound_duration = 0;
1648 if (dspsilence > 0) {
1649 *duration -= (dspsilence - 200) / 1000;
1652 if (*duration < 0) {
1656 for (x = 0; x < fmtcnt; x++) {
1661 * If we ended with silence, trim all but the first 200ms of silence
1662 * off the recording. However, if we ended with '#', we don't want
1663 * to trim ANY part of the recording.
1665 if (res > 0 && dspsilence) {
1666 /* rewind only the trailing silence */
1667 ast_stream_rewind(others[x], dspsilence - 200);
1669 ast_truncstream(others[x]);
1670 ast_closestream(others[x]);
1674 if (prepend && outmsg) {
1675 struct ast_filestream *realfiles[AST_MAX_FORMATS];
1676 struct ast_frame *fr;
1678 for (x = 0; x < fmtcnt; x++) {
1679 snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
1680 realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
1681 if (!others[x] || !realfiles[x]) {
1684 /*!\note Same logic as above. */
1686 ast_stream_rewind(others[x], dspsilence - 200);
1688 ast_truncstream(others[x]);
1689 /* add the original file too */
1690 while ((fr = ast_readframe(realfiles[x]))) {
1691 ast_writestream(others[x], fr);
1694 ast_closestream(others[x]);
1695 ast_closestream(realfiles[x]);
1696 ast_filerename(prependfile, recordfile, sfmt[x]);
1697 ast_verb(4, "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
1698 ast_filedelete(prependfile, sfmt[x]);
1701 if (rfmt.id && ast_set_read_format(chan, &rfmt)) {
1702 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(&rfmt), ast_channel_name(chan));
1704 if ((outmsg == 2) && (!skip_confirmation_sound)) {
1705 ast_stream_and_wait(chan, "auth-thankyou", "");
1708 ast_dsp_free(sildet);
1713 static const char default_acceptdtmf[] = "#";
1714 static const char default_canceldtmf[] = "";
1716 int ast_play_and_record_full(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int *sound_duration, int beep, int silencethreshold, int maxsilence, const char *path, const char *acceptdtmf, const char *canceldtmf, int skip_confirmation_sound, enum ast_record_if_exists if_exists)
1718 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, beep, silencethreshold, maxsilence, path, 0, S_OR(acceptdtmf, default_acceptdtmf), S_OR(canceldtmf, default_canceldtmf), skip_confirmation_sound, if_exists);
1721 int ast_play_and_record(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int *sound_duration, int silencethreshold, int maxsilence, const char *path)
1723 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf, 0, AST_RECORD_IF_EXISTS_OVERWRITE);
1726 int ast_play_and_prepend(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime, char *fmt, int *duration, int *sound_duration, int beep, int silencethreshold, int maxsilence)
1728 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf, 1, AST_RECORD_IF_EXISTS_OVERWRITE);
1731 /* Channel group core functions */
1733 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
1737 char *grp = NULL, *cat = NULL;
1739 if (!ast_strlen_zero(data)) {
1740 ast_copy_string(tmp, data, sizeof(tmp));
1742 if ((cat = strchr(tmp, '@'))) {
1747 if (!ast_strlen_zero(grp)) {
1748 ast_copy_string(group, grp, group_max);
1753 if (!ast_strlen_zero(cat)) {
1754 ast_copy_string(category, cat, category_max);
1760 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
1763 char group[80] = "", category[80] = "";
1764 struct ast_group_info *gi = NULL;
1767 if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
1771 /* Calculate memory we will need if this is new */
1772 len = sizeof(*gi) + strlen(group) + 1;
1773 if (!ast_strlen_zero(category)) {
1774 len += strlen(category) + 1;
1777 AST_RWLIST_WRLOCK(&groups);
1778 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1779 if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
1780 AST_RWLIST_REMOVE_CURRENT(group_list);
1785 AST_RWLIST_TRAVERSE_SAFE_END;
1787 if (ast_strlen_zero(group)) {
1788 /* Enable unsetting the group */
1789 } else if ((gi = calloc(1, len))) {
1791 gi->group = (char *) gi + sizeof(*gi);
1792 strcpy(gi->group, group);
1793 if (!ast_strlen_zero(category)) {
1794 gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
1795 strcpy(gi->category, category);
1797 AST_RWLIST_INSERT_TAIL(&groups, gi, group_list);
1802 AST_RWLIST_UNLOCK(&groups);
1807 int ast_app_group_get_count(const char *group, const char *category)
1809 struct ast_group_info *gi = NULL;
1812 if (ast_strlen_zero(group)) {
1816 AST_RWLIST_RDLOCK(&groups);
1817 AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
1818 if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
1822 AST_RWLIST_UNLOCK(&groups);
1827 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
1829 struct ast_group_info *gi = NULL;
1830 regex_t regexbuf_group;
1831 regex_t regexbuf_category;
1834 if (ast_strlen_zero(groupmatch)) {
1835 ast_log(LOG_NOTICE, "groupmatch empty\n");
1839 /* if regex compilation fails, return zero matches */
1840 if (regcomp(®exbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) {
1841 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch);
1845 if (!ast_strlen_zero(category) && regcomp(®exbuf_category, category, REG_EXTENDED | REG_NOSUB)) {
1846 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", category);
1847 regfree(®exbuf_group);
1851 AST_RWLIST_RDLOCK(&groups);
1852 AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
1853 if (!regexec(®exbuf_group, gi->group, 0, NULL, 0) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !regexec(®exbuf_category, gi->category, 0, NULL, 0)))) {
1857 AST_RWLIST_UNLOCK(&groups);
1859 regfree(®exbuf_group);
1860 if (!ast_strlen_zero(category)) {
1861 regfree(®exbuf_category);
1867 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
1869 struct ast_group_info *gi = NULL;
1871 AST_RWLIST_WRLOCK(&groups);
1872 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1873 if (gi->chan == old) {
1875 } else if (gi->chan == new) {
1876 AST_RWLIST_REMOVE_CURRENT(group_list);
1880 AST_RWLIST_TRAVERSE_SAFE_END;
1881 AST_RWLIST_UNLOCK(&groups);
1886 int ast_app_group_discard(struct ast_channel *chan)
1888 struct ast_group_info *gi = NULL;
1890 AST_RWLIST_WRLOCK(&groups);
1891 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1892 if (gi->chan == chan) {
1893 AST_RWLIST_REMOVE_CURRENT(group_list);
1897 AST_RWLIST_TRAVERSE_SAFE_END;
1898 AST_RWLIST_UNLOCK(&groups);
1903 int ast_app_group_list_wrlock(void)
1905 return AST_RWLIST_WRLOCK(&groups);
1908 int ast_app_group_list_rdlock(void)
1910 return AST_RWLIST_RDLOCK(&groups);
1913 struct ast_group_info *ast_app_group_list_head(void)
1915 return AST_RWLIST_FIRST(&groups);
1918 int ast_app_group_list_unlock(void)
1920 return AST_RWLIST_UNLOCK(&groups);
1923 #undef ast_app_separate_args
1924 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen);
1926 unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen)
1929 char *scan, *wasdelim = NULL;
1930 int paren = 0, quote = 0, bracket = 0;
1932 if (!array || !arraylen) {
1936 memset(array, 0, arraylen * sizeof(*array));
1944 for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
1946 for (; *scan; scan++) {
1949 } else if (*scan == ')') {
1953 } else if (*scan == '[') {
1955 } else if (*scan == ']') {
1959 } else if (*scan == '"' && delim != '"') {
1960 quote = quote ? 0 : 1;
1962 /* Remove quote character from argument */
1963 memmove(scan, scan + 1, strlen(scan));
1966 } else if (*scan == '\\') {
1968 /* Literal character, don't parse */
1969 memmove(scan, scan + 1, strlen(scan));
1973 } else if ((*scan == delim) && !paren && !quote && !bracket) {
1981 /* If the last character in the original string was the delimiter, then
1982 * there is one additional argument. */
1983 if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
1984 array[argc++] = scan;
1990 /* ABI compatible function */
1991 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
1993 return __ast_app_separate_args(buf, delim, 1, array, arraylen);
1996 static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
2002 int lp = strlen(path);
2005 s = ast_alloca(lp + 10);
2006 fs = ast_alloca(lp + 20);
2008 snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
2009 fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
2011 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
2012 return AST_LOCK_PATH_NOT_FOUND;
2016 snprintf(s, strlen(path) + 9, "%s/.lock", path);
2018 while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
2025 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
2026 return AST_LOCK_TIMEOUT;
2028 ast_debug(1, "Locked path '%s'\n", path);
2029 return AST_LOCK_SUCCESS;
2033 static int ast_unlock_path_lockfile(const char *path)
2038 s = ast_alloca(strlen(path) + 10);
2040 snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
2042 if ((res = unlink(s))) {
2043 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
2045 ast_debug(1, "Unlocked path '%s'\n", path);
2052 AST_LIST_ENTRY(path_lock) le;
2057 static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
2059 static void path_lock_destroy(struct path_lock *obj)
2070 static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
2076 struct path_lock *pl;
2077 struct stat st, ost;
2079 fs = ast_alloca(strlen(path) + 20);
2081 snprintf(fs, strlen(path) + 19, "%s/lock", path);
2082 if (lstat(fs, &st) == 0) {
2083 if ((st.st_mode & S_IFMT) == S_IFLNK) {
2084 ast_log(LOG_WARNING, "Unable to create lock file "
2085 "'%s': it's already a symbolic link\n",
2087 return AST_LOCK_FAILURE;
2089 if (st.st_nlink > 1) {
2090 ast_log(LOG_WARNING, "Unable to create lock file "
2091 "'%s': %u hard links exist\n",
2092 fs, (unsigned int) st.st_nlink);
2093 return AST_LOCK_FAILURE;
2096 if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
2097 ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
2098 fs, strerror(errno));
2099 return AST_LOCK_PATH_NOT_FOUND;
2101 if (!(pl = ast_calloc(1, sizeof(*pl)))) {
2102 /* We don't unlink the lock file here, on the possibility that
2103 * someone else created it - better to leave a little mess
2104 * than create a big one by destroying someone else's lock
2105 * and causing something to be corrupted.
2108 return AST_LOCK_FAILURE;
2111 pl->path = strdup(path);
2116 ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
2118 ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
2120 (errno == EWOULDBLOCK) &&
2121 (time(NULL) - start < 5))
2124 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
2125 path, strerror(errno));
2126 /* No unlinking of lock done, since we tried and failed to
2129 path_lock_destroy(pl);
2130 return AST_LOCK_TIMEOUT;
2133 /* Check for the race where the file is recreated or deleted out from
2136 if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
2137 st.st_dev != ost.st_dev &&
2138 st.st_ino != ost.st_ino) {
2139 ast_log(LOG_WARNING, "Unable to create lock file '%s': "
2140 "file changed underneath us\n", fs);
2141 path_lock_destroy(pl);
2142 return AST_LOCK_FAILURE;
2145 /* Success: file created, flocked, and is the one we started with */
2146 AST_LIST_LOCK(&path_lock_list);
2147 AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
2148 AST_LIST_UNLOCK(&path_lock_list);
2150 ast_debug(1, "Locked path '%s'\n", path);
2152 return AST_LOCK_SUCCESS;
2155 static int ast_unlock_path_flock(const char *path)
2158 struct path_lock *p;
2160 s = ast_alloca(strlen(path) + 20);
2162 AST_LIST_LOCK(&path_lock_list);
2163 AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
2164 if (!strcmp(p->path, path)) {
2165 AST_LIST_REMOVE_CURRENT(le);
2169 AST_LIST_TRAVERSE_SAFE_END;
2170 AST_LIST_UNLOCK(&path_lock_list);
2173 snprintf(s, strlen(path) + 19, "%s/lock", path);
2175 path_lock_destroy(p);
2176 ast_debug(1, "Unlocked path '%s'\n", path);
2178 ast_debug(1, "Failed to unlock path '%s': "
2179 "lock not found\n", path);
2185 void ast_set_lock_type(enum AST_LOCK_TYPE type)
2187 ast_lock_type = type;
2190 enum AST_LOCK_RESULT ast_lock_path(const char *path)
2192 enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
2194 switch (ast_lock_type) {
2195 case AST_LOCK_TYPE_LOCKFILE:
2196 r = ast_lock_path_lockfile(path);
2198 case AST_LOCK_TYPE_FLOCK:
2199 r = ast_lock_path_flock(path);
2206 int ast_unlock_path(const char *path)
2210 switch (ast_lock_type) {
2211 case AST_LOCK_TYPE_LOCKFILE:
2212 r = ast_unlock_path_lockfile(path);
2214 case AST_LOCK_TYPE_FLOCK:
2215 r = ast_unlock_path_flock(path);
2222 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
2224 int silencethreshold;
2228 int max_attempts = 3;
2231 int message_exists = 0;
2232 /* Note that urgent and private are for flagging messages as such in the future */
2234 /* barf if no pointer passed to store duration in */
2236 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
2240 cmd = '3'; /* Want to start by recording */
2242 silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
2244 while ((cmd >= 0) && (cmd != 't')) {
2247 if (!message_exists) {
2248 /* In this case, 1 is to record a message */
2252 ast_stream_and_wait(chan, "vm-msgsaved", "");
2258 ast_verb(3, "Reviewing the recording\n");
2259 cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
2264 ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
2266 if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, NULL, silencethreshold, maxsilence, path)) == -1) {
2267 /* User has hung up, no options to give */
2272 } else if (cmd == '*') {
2275 /* If all is well, a message exists */
2288 cmd = ast_play_and_wait(chan, "vm-sorry");
2291 if (message_exists) {
2292 cmd = ast_play_and_wait(chan, "vm-review");
2294 if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
2295 cmd = ast_waitfordigit(chan, 600);
2300 cmd = ast_waitfordigit(chan, 6000);
2305 if (attempts > max_attempts) {
2316 #define RES_UPONE (1 << 16)
2317 #define RES_EXIT (1 << 17)
2318 #define RES_REPEAT (1 << 18)
2319 #define RES_RESTART ((1 << 19) | RES_REPEAT)
2321 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
2323 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
2326 int (*ivr_func)(struct ast_channel *, void *);
2330 switch (option->action) {
2331 case AST_ACTION_UPONE:
2333 case AST_ACTION_EXIT:
2334 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
2335 case AST_ACTION_REPEAT:
2336 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
2337 case AST_ACTION_RESTART:
2338 return RES_RESTART ;
2339 case AST_ACTION_NOOP:
2341 case AST_ACTION_BACKGROUND:
2342 res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
2344 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
2348 case AST_ACTION_PLAYBACK:
2349 res = ast_stream_and_wait(chan, (char *)option->adata, "");
2351 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
2355 case AST_ACTION_MENU:
2356 if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
2357 /* Do not pass entry errors back up, treat as though it was an "UPONE" */
2361 case AST_ACTION_WAITOPTION:
2362 if (!(res = ast_waitfordigit(chan, ast_channel_pbx(chan) ? ast_channel_pbx(chan)->rtimeoutms : 10000))) {
2366 case AST_ACTION_CALLBACK:
2367 ivr_func = option->adata;
2368 res = ivr_func(chan, cbdata);
2370 case AST_ACTION_TRANSFER:
2371 res = ast_parseable_goto(chan, option->adata);
2373 case AST_ACTION_PLAYLIST:
2374 case AST_ACTION_BACKLIST:
2376 c = ast_strdupa(option->adata);
2377 while ((n = strsep(&c, ";"))) {
2378 if ((res = ast_stream_and_wait(chan, n,
2379 (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
2383 ast_stopstream(chan);
2386 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
2392 static int option_exists(struct ast_ivr_menu *menu, char *option)
2395 for (x = 0; menu->options[x].option; x++) {
2396 if (!strcasecmp(menu->options[x].option, option)) {
2403 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
2406 for (x = 0; menu->options[x].option; x++) {
2407 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
2408 (menu->options[x].option[strlen(option)])) {
2415 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
2419 while (option_matchmore(menu, exten)) {
2420 ms = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->dtimeoutms : 5000;
2421 if (strlen(exten) >= maxexten - 1) {
2424 if ((res = ast_waitfordigit(chan, ms)) < 1) {
2427 exten[strlen(exten) + 1] = '\0';
2428 exten[strlen(exten)] = res;
2430 return res > 0 ? 0 : res;
2433 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
2435 /* Execute an IVR menu structure */
2439 char exten[AST_MAX_EXTENSION] = "s";
2440 if (option_exists(menu, "s") < 0) {
2442 if (option_exists(menu, "g") < 0) {
2443 ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
2448 while (menu->options[pos].option) {
2449 if (!strcasecmp(menu->options[pos].option, exten)) {
2450 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
2451 ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
2454 } else if (res & RES_UPONE) {
2456 } else if (res & RES_EXIT) {
2458 } else if (res & RES_REPEAT) {
2459 int maxretries = res & 0xffff;
2460 if ((res & RES_RESTART) == RES_RESTART) {
2468 if ((maxretries > 0) && (retries >= maxretries)) {
2469 ast_debug(1, "Max retries %d exceeded\n", maxretries);
2472 if (option_exists(menu, "g") > -1) {
2474 } else if (option_exists(menu, "s") > -1) {
2480 } else if (res && strchr(AST_DIGIT_ANY, res)) {
2481 ast_debug(1, "Got start of extension, %c\n", res);
2484 if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
2487 if (option_exists(menu, exten) < 0) {
2488 if (option_exists(menu, "i")) {
2489 ast_debug(1, "Invalid extension entered, going to 'i'!\n");
2494 ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
2499 ast_debug(1, "New existing extension: %s\n", exten);
2507 ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
2509 if (!strcasecmp(exten, "s")) {
2518 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
2520 int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
2521 /* Hide internal coding */
2522 return res > 0 ? 0 : res;
2525 char *ast_read_textfile(const char *filename)
2527 int fd, count = 0, res;
2528 char *output = NULL;
2529 struct stat filesize;
2531 if (stat(filename, &filesize) == -1) {
2532 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
2536 count = filesize.st_size + 1;
2538 if ((fd = open(filename, O_RDONLY)) < 0) {
2539 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
2543 if ((output = ast_malloc(count))) {
2544 res = read(fd, output, count - 1);
2545 if (res == count - 1) {
2548 ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
2559 static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
2562 int curarg, res = 0;
2563 unsigned int argloc;
2564 struct ast_flags *flags = _flags;
2565 struct ast_flags64 *flags64 = _flags;
2567 if (flaglen == 32) {
2568 ast_clear_flag(flags, AST_FLAGS_ALL);
2579 curarg = *s++ & 0x7f; /* the array (in app.h) has 128 entries */
2580 argloc = options[curarg].arg_index;
2582 int paren = 1, quote = 0;
2583 int parsequotes = (s[1] == '"') ? 1 : 0;
2588 if (*s == '(' && !quote) {
2590 } else if (*s == ')' && !quote) {
2591 /* Count parentheses, unless they're within quotes (or backslashed, below) */
2593 } else if (*s == '"' && parsequotes) {
2594 /* Leave embedded quotes alone, unless they are the first character */
2595 quote = quote ? 0 : 1;
2596 ast_copy_string(s, s + 1, INT_MAX);
2598 } else if (*s == '\\') {
2600 /* If a backslash is found outside of quotes, remove it */
2601 ast_copy_string(s, s + 1, INT_MAX);
2602 } else if (quote && s[1] == '"') {
2603 /* Backslash for a quote character within quotes, remove the backslash */
2604 ast_copy_string(s, s + 1, INT_MAX);
2606 /* Backslash within quotes, keep both characters */
2615 /* This will find the closing paren we found above, or none, if the string ended before we found one. */
2616 if ((s = strchr(s, ')'))) {
2618 args[argloc - 1] = arg;
2622 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
2626 } else if (argloc) {
2627 args[argloc - 1] = "";
2629 if (flaglen == 32) {
2630 ast_set_flag(flags, options[curarg].flag);
2632 ast_set_flag64(flags64, options[curarg].flag);
2639 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
2641 return parse_options(options, flags, args, optstr, 32);
2644 int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
2646 return parse_options(options, flags, args, optstr, 64);
2649 void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
2651 unsigned int i, found = 0;
2652 for (i = 32; i < 128 && found < len; i++) {
2653 if (ast_test_flag64(flags, options[i].flag)) {
2660 int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
2665 if (ast_strlen_zero(stream)) {
2670 if (*stream == '\\') {
2672 switch (*(stream + 1)) {
2684 if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
2686 if (*(stream + 2) <= '9') {
2687 *result = *(stream + 2) - '0';
2688 } else if (*(stream + 2) <= 'F') {
2689 *result = *(stream + 2) - 'A' + 10;
2691 *result = *(stream + 2) - 'a' + 10;
2694 ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
2698 if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
2701 if (*(stream + 3) <= '9') {
2702 *result += *(stream + 3) - '0';
2703 } else if (*(stream + 3) <= 'F') {
2704 *result += *(stream + 3) - 'A' + 10;
2706 *result += *(stream + 3) - 'a' + 10;
2713 for (i = 2; ; i++) {
2714 if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
2716 ast_debug(5, "result was %d, ", *result);
2718 *result += *(stream + i) - '0';
2719 ast_debug(5, "is now %d\n", *result);
2726 *result = *(stream + 1);
2735 char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
2740 while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
2748 int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
2754 if (strchr(stream, '\\')) {
2755 while (!ast_get_encoded_char(stream, &next, &consumed)) {
2756 if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
2757 ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
2759 if (offset + 2 > ast_str_size(*str)) {
2762 buf = ast_str_buffer(*str);
2763 buf[offset++] = next;
2766 buf = ast_str_buffer(*str);
2767 buf[offset++] = '\0';
2768 ast_str_update(*str);
2770 ast_str_set(str, maxlen, "%s", stream);
2775 void ast_close_fds_above_n(int n)
2780 int ast_safe_fork(int stop_reaper)
2782 sigset_t signal_set, old_set;
2785 /* Don't let the default signal handler for children reap our status */
2787 ast_replace_sigchld();
2790 sigfillset(&signal_set);
2791 pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
2796 /* Fork failed or parent */
2797 pthread_sigmask(SIG_SETMASK, &old_set, NULL);
2798 if (!stop_reaper && pid > 0) {
2799 struct zombie *cur = ast_calloc(1, sizeof(*cur));
2802 AST_LIST_LOCK(&zombies);
2803 AST_LIST_INSERT_TAIL(&zombies, cur, list);
2804 AST_LIST_UNLOCK(&zombies);
2805 if (shaun_of_the_dead_thread == AST_PTHREADT_NULL) {
2806 if (ast_pthread_create_background(&shaun_of_the_dead_thread, NULL, shaun_of_the_dead, NULL)) {
2807 ast_log(LOG_ERROR, "Shaun of the Dead wants to kill zombies, but can't?!!\n");
2808 shaun_of_the_dead_thread = AST_PTHREADT_NULL;
2817 cap_t cap = cap_from_text("cap_net_admin-eip");
2819 if (cap_set_proc(cap)) {
2820 ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
2825 /* Before we unblock our signals, return our trapped signals back to the defaults */
2826 signal(SIGHUP, SIG_DFL);
2827 signal(SIGCHLD, SIG_DFL);
2828 signal(SIGINT, SIG_DFL);
2829 signal(SIGURG, SIG_DFL);
2830 signal(SIGTERM, SIG_DFL);
2831 signal(SIGPIPE, SIG_DFL);
2832 signal(SIGXFSZ, SIG_DFL);
2834 /* unblock important signal handlers */
2835 if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
2836 ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
2844 void ast_safe_fork_cleanup(void)
2846 ast_unreplace_sigchld();
2849 int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
2853 #ifdef HAVE_LONG_DOUBLE_WIDER
2855 #define FMT "%30Lf%9s"
2858 #define FMT "%30lf%9s"
2864 res = sscanf(timestr, FMT, &amount, u);
2866 if (res == 0 || res == EOF) {
2869 } else if (res == 2) {
2873 unit = TIMELEN_HOURS;
2877 unit = TIMELEN_SECONDS;
2881 if (toupper(u[1]) == 'S') {
2882 unit = TIMELEN_MILLISECONDS;
2883 } else if (u[1] == '\0') {
2884 unit = TIMELEN_MINUTES;
2894 case TIMELEN_MINUTES:
2897 case TIMELEN_SECONDS:
2900 case TIMELEN_MILLISECONDS:
2903 *result = amount > INT_MAX ? INT_MAX : (int) amount;
2909 static void mwi_state_dtor(void *obj)
2911 struct ast_mwi_state *mwi_state = obj;
2912 ast_string_field_free_memory(mwi_state);
2913 ao2_cleanup(mwi_state->snapshot);
2914 mwi_state->snapshot = NULL;
2917 struct stasis_topic *ast_mwi_topic_all(void)
2919 return mwi_topic_all;
2922 struct stasis_cache *ast_mwi_state_cache(void)
2924 return mwi_state_cache;
2927 struct stasis_topic *ast_mwi_topic_cached(void)
2929 return stasis_caching_get_topic(mwi_topic_cached);
2932 struct stasis_topic *ast_mwi_topic(const char *uniqueid)
2934 return stasis_topic_pool_get_topic(mwi_topic_pool, uniqueid);
2937 struct ast_mwi_state *ast_mwi_create(const char *mailbox, const char *context)
2939 RAII_VAR(struct ast_mwi_state *, mwi_state, NULL, ao2_cleanup);
2941 ast_assert(!ast_strlen_zero(mailbox));
2943 mwi_state = ao2_alloc(sizeof(*mwi_state), mwi_state_dtor);
2948 if (ast_string_field_init(mwi_state, 256)) {
2951 if (!ast_strlen_zero(context)) {
2952 ast_string_field_build(mwi_state, uniqueid, "%s@%s", mailbox, context);
2954 ast_string_field_set(mwi_state, uniqueid, mailbox);
2957 ao2_ref(mwi_state, +1);
2963 * \brief Create a MWI state snapshot message.
2966 * \param[in] mailbox The mailbox identifier string.
2967 * \param[in] context The context this mailbox resides in (NULL or "" if only using mailbox)
2968 * \param[in] new_msgs The number of new messages in this mailbox
2969 * \param[in] old_msgs The number of old messages in this mailbox
2970 * \param[in] channel_id A unique identifier for a channel associated with this
2971 * change in mailbox state
2972 * \param[in] eid The EID of the server that originally published the message
2974 * \retval message on success. Use ao2_cleanup() when done with it.
2975 * \retval NULL on error.
2977 static struct stasis_message *mwi_state_create_message(
2978 const char *mailbox,
2979 const char *context,
2982 const char *channel_id,
2983 struct ast_eid *eid)
2985 struct ast_mwi_state *mwi_state;
2986 struct stasis_message *message;
2988 mwi_state = ast_mwi_create(mailbox, context);
2993 mwi_state->new_msgs = new_msgs;
2994 mwi_state->old_msgs = old_msgs;
2996 if (!ast_strlen_zero(channel_id)) {
2997 struct stasis_message *chan_message;
2999 chan_message = stasis_cache_get(ast_channel_cache(), ast_channel_snapshot_type(),
3002 mwi_state->snapshot = stasis_message_data(chan_message);
3003 ao2_ref(mwi_state->snapshot, +1);
3005 ao2_cleanup(chan_message);
3009 mwi_state->eid = *eid;
3011 mwi_state->eid = ast_eid_default;
3015 * XXX As far as stasis is concerned, all MWI events are local.
3017 * We may in the future want to make MWI aggregate local/remote
3018 * message counts similar to how device state aggregates state.
3020 message = stasis_message_create_full(ast_mwi_state_type(), mwi_state, &ast_eid_default);
3021 ao2_cleanup(mwi_state);
3025 int ast_publish_mwi_state_full(
3026 const char *mailbox,
3027 const char *context,
3030 const char *channel_id,
3031 struct ast_eid *eid)
3033 struct ast_mwi_state *mwi_state;
3034 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
3035 struct stasis_topic *mailbox_specific_topic;
3037 message = mwi_state_create_message(mailbox, context, new_msgs, old_msgs, channel_id, eid);
3042 mwi_state = stasis_message_data(message);
3043 mailbox_specific_topic = ast_mwi_topic(mwi_state->uniqueid);
3044 if (!mailbox_specific_topic) {
3048 stasis_publish(mailbox_specific_topic, message);
3053 int ast_delete_mwi_state_full(const char *mailbox, const char *context, struct ast_eid *eid)
3055 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
3056 struct stasis_message *cached_msg;
3057 struct stasis_message *clear_msg;
3058 struct ast_mwi_state *mwi_state;
3059 struct stasis_topic *mailbox_specific_topic;
3061 msg = mwi_state_create_message(mailbox, context, 0, 0, NULL, eid);
3066 mwi_state = stasis_message_data(msg);
3069 * XXX As far as stasis is concerned, all MWI events are local.
3071 * For now, it is assumed that there is only one entity
3072 * maintaining the state of a particular mailbox.
3074 * If we ever have multiple MWI event entities maintaining
3075 * the same mailbox that wish to delete their cached entry
3076 * we will need to do something about the race condition
3077 * potential between checking the cache and removing the
3080 cached_msg = stasis_cache_get_by_eid(ast_mwi_state_cache(),
3081 ast_mwi_state_type(), mwi_state->uniqueid, &ast_eid_default);
3083 /* Nothing to clear */
3086 ao2_cleanup(cached_msg);
3088 mailbox_specific_topic = ast_mwi_topic(mwi_state->uniqueid);
3089 if (!mailbox_specific_topic) {
3093 clear_msg = stasis_cache_clear_create(msg);
3095 stasis_publish(mailbox_specific_topic, clear_msg);
3097 ao2_cleanup(clear_msg);
3101 static const char *mwi_state_get_id(struct stasis_message *message)
3103 if (ast_mwi_state_type() == stasis_message_type(message)) {
3104 struct ast_mwi_state *mwi_state = stasis_message_data(message);
3105 return mwi_state->uniqueid;
3106 } else if (stasis_subscription_change_type() == stasis_message_type(message)) {
3107 struct stasis_subscription_change *change = stasis_message_data(message);
3108 return change->uniqueid;
3114 static void mwi_blob_dtor(void *obj)
3116 struct ast_mwi_blob *mwi_blob = obj;
3118 ao2_cleanup(mwi_blob->mwi_state);
3119 ast_json_unref(mwi_blob->blob);
3122 struct stasis_message *ast_mwi_blob_create(struct ast_mwi_state *mwi_state,
3123 struct stasis_message_type *message_type,
3124 struct ast_json *blob)
3126 RAII_VAR(struct ast_mwi_blob *, obj, NULL, ao2_cleanup);
3127 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
3129 ast_assert(blob != NULL);
3131 obj = ao2_alloc(sizeof(*obj), mwi_blob_dtor);
3136 obj->mwi_state = mwi_state;
3137 ao2_ref(obj->mwi_state, +1);
3138 obj->blob = ast_json_ref(blob);
3140 /* This is not a normal MWI event. Only used by the MinivmNotify app. */
3141 msg = stasis_message_create(message_type, obj);
3150 struct stasis_topic *ast_queue_topic_all(void)
3152 return queue_topic_all;
3155 struct stasis_topic *ast_queue_topic(const char *queuename)
3157 return stasis_topic_pool_get_topic(queue_topic_pool, queuename);
3160 static void app_cleanup(void)
3162 ao2_cleanup(queue_topic_pool);
3163 queue_topic_pool = NULL;
3164 ao2_cleanup(queue_topic_all);
3165 queue_topic_all = NULL;
3166 ao2_cleanup(mwi_topic_pool);
3167 mwi_topic_pool = NULL;
3168 ao2_cleanup(mwi_topic_all);
3169 mwi_topic_all = NULL;
3170 ao2_cleanup(mwi_state_cache);
3171 mwi_state_cache = NULL;
3172 mwi_topic_cached = stasis_caching_unsubscribe_and_join(mwi_topic_cached);
3173 STASIS_MESSAGE_TYPE_CLEANUP(ast_mwi_state_type);
3174 STASIS_MESSAGE_TYPE_CLEANUP(ast_mwi_vm_app_type);
3179 ast_register_cleanup(app_cleanup);
3181 if (STASIS_MESSAGE_TYPE_INIT(ast_mwi_state_type) != 0) {
3184 if (STASIS_MESSAGE_TYPE_INIT(ast_mwi_vm_app_type) != 0) {
3187 mwi_topic_all = stasis_topic_create("stasis_mwi_topic");
3188 if (!mwi_topic_all) {
3191 mwi_state_cache = stasis_cache_create(mwi_state_get_id);
3192 if (!mwi_state_cache) {
3195 mwi_topic_cached = stasis_caching_topic_create(mwi_topic_all, mwi_state_cache);
3196 if (!mwi_topic_cached) {
3199 mwi_topic_pool = stasis_topic_pool_create(mwi_topic_all);
3200 if (!mwi_topic_pool) {
3203 queue_topic_all = stasis_topic_create("stasis_queue_topic");
3204 if (!queue_topic_all) {
3207 queue_topic_pool = stasis_topic_pool_create(queue_topic_all);
3208 if (!queue_topic_pool) {