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"
73 #include "asterisk/format_cache.h"
75 #define MWI_TOPIC_BUCKETS 57
77 AST_THREADSTORAGE_PUBLIC(ast_str_thread_global_buf);
79 static pthread_t shaun_of_the_dead_thread = AST_PTHREADT_NULL;
83 AST_LIST_ENTRY(zombie) list;
86 static AST_LIST_HEAD_STATIC(zombies, zombie);
89 * @{ \brief Define \ref stasis topic objects
91 static struct stasis_topic *mwi_topic_all;
92 static struct stasis_cache *mwi_state_cache;
93 static struct stasis_caching_topic *mwi_topic_cached;
94 static struct stasis_topic_pool *mwi_topic_pool;
96 static struct stasis_topic *queue_topic_all;
97 static struct stasis_topic_pool *queue_topic_pool;
100 /*! \brief Convert a MWI \ref stasis_message to a \ref ast_event */
101 static struct ast_event *mwi_to_event(struct stasis_message *message)
103 struct ast_event *event;
104 struct ast_mwi_state *mwi_state;
112 mwi_state = stasis_message_data(message);
114 /* Strip off @context */
115 context = mailbox = ast_strdupa(mwi_state->uniqueid);
116 strsep(&context, "@");
117 if (ast_strlen_zero(context)) {
121 event = ast_event_new(AST_EVENT_MWI,
122 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
123 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
124 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, mwi_state->new_msgs,
125 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, mwi_state->old_msgs,
126 AST_EVENT_IE_EID, AST_EVENT_IE_PLTYPE_RAW, &mwi_state->eid, sizeof(mwi_state->eid),
133 * @{ \brief Define \ref stasis message types for MWI
135 STASIS_MESSAGE_TYPE_DEFN(ast_mwi_state_type,
136 .to_event = mwi_to_event, );
137 STASIS_MESSAGE_TYPE_DEFN(ast_mwi_vm_app_type);
142 static void *shaun_of_the_dead(void *data)
147 if (!AST_LIST_EMPTY(&zombies)) {
148 /* Don't allow cancellation while we have a lock. */
149 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
150 AST_LIST_LOCK(&zombies);
151 AST_LIST_TRAVERSE_SAFE_BEGIN(&zombies, cur, list) {
152 if (waitpid(cur->pid, &status, WNOHANG) != 0) {
153 AST_LIST_REMOVE_CURRENT(list);
157 AST_LIST_TRAVERSE_SAFE_END
158 AST_LIST_UNLOCK(&zombies);
159 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
161 pthread_testcancel();
162 /* Wait for 60 seconds, without engaging in a busy loop. */
163 ast_poll(NULL, 0, AST_LIST_FIRST(&zombies) ? 5000 : 60000);
169 #define AST_MAX_FORMATS 10
171 static AST_RWLIST_HEAD_STATIC(groups, ast_group_info);
174 * \brief This function presents a dialtone and reads an extension into 'collect'
175 * which must be a pointer to a **pre-initialized** array of char having a
176 * size of 'size' suitable for writing to. It will collect no more than the smaller
177 * of 'maxlen' or 'size' minus the original strlen() of collect digits.
178 * \param chan struct.
183 * \param timeout timeout in milliseconds
185 * \return 0 if extension does not exist, 1 if extension exists
187 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
189 struct ast_tone_zone_sound *ts;
197 if (ast_channel_pbx(chan) && ast_channel_pbx(chan)->dtimeoutms) {
198 timeout = ast_channel_pbx(chan)->dtimeoutms;
204 if ((ts = ast_get_indication_tone(ast_channel_zone(chan), "dial"))) {
205 res = ast_playtones_start(chan, 0, ts->data, 0);
206 ts = ast_tone_zone_sound_unref(ts);
208 ast_log(LOG_NOTICE, "Huh....? no dial for indications?\n");
211 for (x = strlen(collect); x < maxlen; ) {
212 res = ast_waitfordigit(chan, timeout);
213 if (!ast_ignore_pattern(context, collect)) {
214 ast_playtones_stop(chan);
223 if (!ast_matchmore_extension(chan, context, collect, 1,
224 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
230 res = ast_exists_extension(chan, context, collect, 1,
231 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL)) ? 1 : 0;
238 * \brief ast_app_getdata
239 * \param c The channel to read from
240 * \param prompt The file to stream to the channel
241 * \param s The string to read in to. Must be at least the size of your length
242 * \param maxlen How many digits to read (maximum)
243 * \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for
244 * "ludicrous time" (essentially never times out) */
245 enum ast_getdata_result ast_app_getdata(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout)
247 int res = 0, to, fto;
248 char *front, *filename;
250 /* XXX Merge with full version? XXX */
258 filename = ast_strdupa(prompt);
259 while ((front = strsep(&filename, "&"))) {
260 if (!ast_strlen_zero(front)) {
261 res = ast_streamfile(c, front, ast_channel_language(c));
265 if (ast_strlen_zero(filename)) {
266 /* set timeouts for the last prompt */
267 fto = ast_channel_pbx(c) ? ast_channel_pbx(c)->rtimeoutms : 6000;
268 to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
274 fto = to = 1000000000;
277 /* there is more than one prompt, so
278 * get rid of the long timeout between
279 * prompts, and make it 50ms */
281 to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
283 res = ast_readstring(c, s, maxlen, to, fto, "#");
284 if (res == AST_GETDATA_EMPTY_END_TERMINATED) {
287 if (!ast_strlen_zero(s)) {
295 /* The lock type used by ast_lock_path() / ast_unlock_path() */
296 static enum AST_LOCK_TYPE ast_lock_type = AST_LOCK_TYPE_LOCKFILE;
298 int ast_app_getdata_full(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
300 int res, to = 2000, fto = 6000;
302 if (!ast_strlen_zero(prompt)) {
303 res = ast_streamfile(c, prompt, ast_channel_language(c));
313 fto = to = 1000000000;
316 res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
321 int ast_app_exec_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char *macro_args)
323 struct ast_app *macro_app;
326 macro_app = pbx_findapp("Macro");
329 "Cannot run 'Macro(%s)'. The application is not available.\n", macro_args);
332 if (autoservice_chan) {
333 ast_autoservice_start(autoservice_chan);
336 ast_debug(4, "%s Original location: %s,%s,%d\n", ast_channel_name(macro_chan),
337 ast_channel_context(macro_chan), ast_channel_exten(macro_chan),
338 ast_channel_priority(macro_chan));
340 res = pbx_exec(macro_chan, macro_app, macro_args);
341 ast_debug(4, "Macro exited with status %d\n", res);
344 * Assume anything negative from Macro is an error.
345 * Anything else is success.
353 ast_debug(4, "%s Ending location: %s,%s,%d\n", ast_channel_name(macro_chan),
354 ast_channel_context(macro_chan), ast_channel_exten(macro_chan),
355 ast_channel_priority(macro_chan));
357 if (autoservice_chan) {
358 ast_autoservice_stop(autoservice_chan);
363 int ast_app_run_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char *macro_name, const char *macro_args)
369 if (ast_strlen_zero(macro_args)) {
370 return ast_app_exec_macro(autoservice_chan, macro_chan, macro_name);
373 /* Create the Macro application argument string. */
374 args_len = strlen(macro_name) + strlen(macro_args) + 2;
375 args_str = ast_malloc(args_len);
379 snprintf(args_str, args_len, "%s,%s", macro_name, macro_args);
381 res = ast_app_exec_macro(autoservice_chan, macro_chan, args_str);
386 static const struct ast_app_stack_funcs *app_stack_callbacks;
388 void ast_install_stack_functions(const struct ast_app_stack_funcs *funcs)
390 app_stack_callbacks = funcs;
393 const char *ast_app_expand_sub_args(struct ast_channel *chan, const char *args)
395 const struct ast_app_stack_funcs *funcs;
396 const char *new_args;
398 funcs = app_stack_callbacks;
399 if (!funcs || !funcs->expand_sub_args) {
401 "Cannot expand 'Gosub(%s)' arguments. The app_stack module is not available.\n",
405 ast_module_ref(funcs->module);
407 new_args = funcs->expand_sub_args(chan, args);
408 ast_module_unref(funcs->module);
412 int ast_app_exec_sub(struct ast_channel *autoservice_chan, struct ast_channel *sub_chan, const char *sub_args, int ignore_hangup)
414 const struct ast_app_stack_funcs *funcs;
417 funcs = app_stack_callbacks;
418 if (!funcs || !funcs->run_sub) {
420 "Cannot run 'Gosub(%s)'. The app_stack module is not available.\n",
424 ast_module_ref(funcs->module);
426 if (autoservice_chan) {
427 ast_autoservice_start(autoservice_chan);
430 res = funcs->run_sub(sub_chan, sub_args, ignore_hangup);
431 ast_module_unref(funcs->module);
433 if (autoservice_chan) {
434 ast_autoservice_stop(autoservice_chan);
439 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)
445 if (ast_strlen_zero(sub_args)) {
446 return ast_app_exec_sub(autoservice_chan, sub_chan, sub_location, ignore_hangup);
449 /* Create the Gosub application argument string. */
450 args_len = strlen(sub_location) + strlen(sub_args) + 3;
451 args_str = ast_malloc(args_len);
455 snprintf(args_str, args_len, "%s(%s)", sub_location, sub_args);
457 res = ast_app_exec_sub(autoservice_chan, sub_chan, args_str, ignore_hangup);
462 /*! \brief The container for the voicemail provider */
463 static AO2_GLOBAL_OBJ_STATIC(vm_provider);
465 /*! Voicemail not registered warning */
466 static int vm_warnings;
468 int ast_vm_is_registered(void)
470 struct ast_vm_functions *table;
473 table = ao2_global_obj_ref(vm_provider);
474 is_registered = table ? 1 : 0;
476 return is_registered;
479 int __ast_vm_register(const struct ast_vm_functions *vm_table, struct ast_module *module)
481 RAII_VAR(struct ast_vm_functions *, table, NULL, ao2_cleanup);
483 if (!vm_table->module_name) {
484 ast_log(LOG_ERROR, "Voicemail provider missing required information.\n");
487 if (vm_table->module_version != VM_MODULE_VERSION) {
488 ast_log(LOG_ERROR, "Voicemail provider '%s' has incorrect version\n",
489 vm_table->module_name);
493 table = ao2_global_obj_ref(vm_provider);
495 ast_log(LOG_WARNING, "Voicemail provider already registered by %s.\n",
500 table = ao2_alloc_options(sizeof(*table), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
505 table->module = module;
507 ao2_global_obj_replace_unref(vm_provider, table);
511 void ast_vm_unregister(const char *module_name)
513 struct ast_vm_functions *table;
515 table = ao2_global_obj_ref(vm_provider);
516 if (table && !strcmp(table->module_name, module_name)) {
517 ao2_global_obj_release(vm_provider);
522 /*! \brief The container for the voicemail greeter provider */
523 static AO2_GLOBAL_OBJ_STATIC(vm_greeter_provider);
525 /*! Voicemail greeter not registered warning */
526 static int vm_greeter_warnings;
528 int ast_vm_greeter_is_registered(void)
530 struct ast_vm_greeter_functions *table;
533 table = ao2_global_obj_ref(vm_greeter_provider);
534 is_registered = table ? 1 : 0;
536 return is_registered;
539 int __ast_vm_greeter_register(const struct ast_vm_greeter_functions *vm_table, struct ast_module *module)
541 RAII_VAR(struct ast_vm_greeter_functions *, table, NULL, ao2_cleanup);
543 if (!vm_table->module_name) {
544 ast_log(LOG_ERROR, "Voicemail greeter provider missing required information.\n");
547 if (vm_table->module_version != VM_GREETER_MODULE_VERSION) {
548 ast_log(LOG_ERROR, "Voicemail greeter provider '%s' has incorrect version\n",
549 vm_table->module_name);
553 table = ao2_global_obj_ref(vm_greeter_provider);
555 ast_log(LOG_WARNING, "Voicemail greeter provider already registered by %s.\n",
560 table = ao2_alloc_options(sizeof(*table), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
565 table->module = module;
567 ao2_global_obj_replace_unref(vm_greeter_provider, table);
571 void ast_vm_greeter_unregister(const char *module_name)
573 struct ast_vm_greeter_functions *table;
575 table = ao2_global_obj_ref(vm_greeter_provider);
576 if (table && !strcmp(table->module_name, module_name)) {
577 ao2_global_obj_release(vm_greeter_provider);
582 #ifdef TEST_FRAMEWORK
583 static ast_vm_test_create_user_fn *ast_vm_test_create_user_func = NULL;
584 static ast_vm_test_destroy_user_fn *ast_vm_test_destroy_user_func = NULL;
586 void ast_install_vm_test_functions(ast_vm_test_create_user_fn *vm_test_create_user_func,
587 ast_vm_test_destroy_user_fn *vm_test_destroy_user_func)
589 ast_vm_test_create_user_func = vm_test_create_user_func;
590 ast_vm_test_destroy_user_func = vm_test_destroy_user_func;
593 void ast_uninstall_vm_test_functions(void)
595 ast_vm_test_create_user_func = NULL;
596 ast_vm_test_destroy_user_func = NULL;
600 static void vm_warn_no_provider(void)
602 if (vm_warnings++ % 10 == 0) {
603 ast_verb(3, "No voicemail provider registered.\n");
607 #define VM_API_CALL(res, api_call, api_parms) \
609 struct ast_vm_functions *table; \
610 table = ao2_global_obj_ref(vm_provider); \
612 vm_warn_no_provider(); \
613 } else if (table->api_call) { \
614 ast_module_ref(table->module); \
615 (res) = table->api_call api_parms; \
616 ast_module_unref(table->module); \
618 ao2_cleanup(table); \
621 static void vm_greeter_warn_no_provider(void)
623 if (vm_greeter_warnings++ % 10 == 0) {
624 ast_verb(3, "No voicemail greeter provider registered.\n");
628 #define VM_GREETER_API_CALL(res, api_call, api_parms) \
630 struct ast_vm_greeter_functions *table; \
631 table = ao2_global_obj_ref(vm_greeter_provider); \
633 vm_greeter_warn_no_provider(); \
634 } else if (table->api_call) { \
635 ast_module_ref(table->module); \
636 (res) = table->api_call api_parms; \
637 ast_module_unref(table->module); \
639 ao2_cleanup(table); \
642 int ast_app_has_voicemail(const char *mailboxes, const char *folder)
646 VM_API_CALL(res, has_voicemail, (mailboxes, folder));
652 * \brief Function used as a callback for ast_copy_recording_to_vm when a real one isn't installed.
653 * \param vm_rec_data Stores crucial information about the voicemail that will basically just be used
654 * to figure out what the name of the recipient was supposed to be
656 int ast_app_copy_recording_to_vm(struct ast_vm_recording_data *vm_rec_data)
660 VM_API_CALL(res, copy_recording_to_vm, (vm_rec_data));
664 int ast_app_inboxcount(const char *mailboxes, int *newmsgs, int *oldmsgs)
675 VM_API_CALL(res, inboxcount, (mailboxes, newmsgs, oldmsgs));
679 int ast_app_inboxcount2(const char *mailboxes, int *urgentmsgs, int *newmsgs, int *oldmsgs)
693 VM_API_CALL(res, inboxcount2, (mailboxes, urgentmsgs, newmsgs, oldmsgs));
697 int ast_app_sayname(struct ast_channel *chan, const char *mailbox_id)
701 VM_GREETER_API_CALL(res, sayname, (chan, mailbox_id));
705 int ast_app_messagecount(const char *mailbox_id, const char *folder)
709 VM_API_CALL(res, messagecount, (mailbox_id, folder));
713 const char *ast_vm_index_to_foldername(int id)
715 const char *res = NULL;
717 VM_API_CALL(res, index_to_foldername, (id));
721 struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_create(const char *mailbox,
725 enum ast_vm_snapshot_sort_val sort_val,
726 int combine_INBOX_and_OLD)
728 struct ast_vm_mailbox_snapshot *res = NULL;
730 VM_API_CALL(res, mailbox_snapshot_create, (mailbox, context, folder, descending,
731 sort_val, combine_INBOX_and_OLD));
735 struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_destroy(struct ast_vm_mailbox_snapshot *mailbox_snapshot)
737 struct ast_vm_mailbox_snapshot *res = NULL;
739 VM_API_CALL(res, mailbox_snapshot_destroy, (mailbox_snapshot));
743 int ast_vm_msg_move(const char *mailbox,
746 const char *oldfolder,
747 const char *old_msg_ids[],
748 const char *newfolder)
752 VM_API_CALL(res, msg_move, (mailbox, context, num_msgs, oldfolder, old_msg_ids,
757 int ast_vm_msg_remove(const char *mailbox,
765 VM_API_CALL(res, msg_remove, (mailbox, context, num_msgs, folder, msgs));
769 int ast_vm_msg_forward(const char *from_mailbox,
770 const char *from_context,
771 const char *from_folder,
772 const char *to_mailbox,
773 const char *to_context,
774 const char *to_folder,
776 const char *msg_ids[],
781 VM_API_CALL(res, msg_forward, (from_mailbox, from_context, from_folder, to_mailbox,
782 to_context, to_folder, num_msgs, msg_ids, delete_old));
786 int ast_vm_msg_play(struct ast_channel *chan,
791 ast_vm_msg_play_cb *cb)
795 VM_API_CALL(res, msg_play, (chan, mailbox, context, folder, msg_num, cb));
799 #ifdef TEST_FRAMEWORK
800 int ast_vm_test_create_user(const char *context, const char *mailbox)
802 if (ast_vm_test_create_user_func) {
803 return ast_vm_test_create_user_func(context, mailbox);
808 int ast_vm_test_destroy_user(const char *context, const char *mailbox)
810 if (ast_vm_test_destroy_user_func) {
811 return ast_vm_test_destroy_user_func(context, mailbox);
817 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between, unsigned int duration)
821 struct ast_silence_generator *silgen = NULL;
827 if (peer && ast_autoservice_start(peer)) {
831 /* Need a quiet time before sending digits. */
832 if (ast_opt_transmit_silence) {
833 silgen = ast_channel_start_silence_generator(chan);
835 res = ast_safe_sleep(chan, 100);
837 goto dtmf_stream_cleanup;
840 for (ptr = digits; *ptr; ptr++) {
842 /* 'w' -- wait half a second */
843 if ((res = ast_safe_sleep(chan, 500))) {
846 } else if (*ptr == 'W') {
847 /* 'W' -- wait a second */
848 if ((res = ast_safe_sleep(chan, 1000))) {
851 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
852 if (*ptr == 'f' || *ptr == 'F') {
853 /* ignore return values if not supported by channel */
854 ast_indicate(chan, AST_CONTROL_FLASH);
856 /* Character represents valid DTMF */
857 ast_senddigit(chan, *ptr, duration);
859 /* pause between digits */
860 if ((res = ast_safe_sleep(chan, between))) {
864 ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n", *ptr);
870 ast_channel_stop_silence_generator(chan, silgen);
872 if (peer && ast_autoservice_stop(peer)) {
879 struct linear_state {
883 struct ast_format *origwfmt;
886 static void linear_release(struct ast_channel *chan, void *params)
888 struct linear_state *ls = params;
890 if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt)) {
891 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%s'\n",
892 ast_channel_name(chan), ast_format_get_name(ls->origwfmt));
894 ao2_cleanup(ls->origwfmt);
903 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
905 short buf[2048 + AST_FRIENDLY_OFFSET / 2];
906 struct linear_state *ls = data;
907 struct ast_frame f = {
908 .frametype = AST_FRAME_VOICE,
909 .data.ptr = buf + AST_FRIENDLY_OFFSET / 2,
910 .offset = AST_FRIENDLY_OFFSET,
914 f.subclass.format = ast_format_slin;
917 if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
918 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" , len);
919 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
921 res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
933 static void *linear_alloc(struct ast_channel *chan, void *params)
935 struct linear_state *ls = params;
941 /* In this case, params is already malloc'd */
942 if (ls->allowoverride) {
943 ast_set_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
945 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
948 ls->origwfmt = ao2_bump(ast_channel_writeformat(chan));
950 if (ast_set_write_format(chan, ast_format_slin)) {
951 ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", ast_channel_name(chan));
952 ao2_cleanup(ls->origwfmt);
960 static struct ast_generator linearstream =
962 .alloc = linear_alloc,
963 .release = linear_release,
964 .generate = linear_generator,
967 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
969 struct linear_state *lin;
974 if (ast_strlen_zero(filename)) {
978 if (filename[0] == '/') {
979 ast_copy_string(tmpf, filename, sizeof(tmpf));
981 snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", ast_config_AST_DATA_DIR, "sounds", filename);
983 if ((fd = open(tmpf, O_RDONLY)) < 0) {
984 ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
988 if ((lin = ast_calloc(1, sizeof(*lin)))) {
990 lin->allowoverride = allowoverride;
991 lin->autoclose = autoclose;
992 res = ast_activate_generator(chan, &linearstream, lin);
997 static int control_streamfile(struct ast_channel *chan,
1002 const char *suspend,
1003 const char *restart,
1007 ast_waitstream_fr_cb cb)
1009 char *breaks = NULL;
1013 long pause_restart_point = 0;
1020 offset = *offsetms * 8; /* XXX Assumes 8kHz */
1023 lang = ast_channel_language(chan);
1027 blen += strlen(stop);
1030 blen += strlen(suspend);
1033 blen += strlen(restart);
1037 breaks = ast_alloca(blen + 1);
1040 strcat(breaks, stop);
1043 strcat(breaks, suspend);
1046 strcat(breaks, restart);
1050 if ((end = strchr(file, ':'))) {
1051 if (!strcasecmp(end, ":end")) {
1058 ast_stopstream(chan);
1059 res = ast_streamfile(chan, file, lang);
1061 if (pause_restart_point) {
1062 ast_seekstream(ast_channel_stream(chan), pause_restart_point, SEEK_SET);
1063 pause_restart_point = 0;
1065 else if (end || offset < 0) {
1069 ast_verb(3, "ControlPlayback seek to offset %ld from end\n", offset);
1071 ast_seekstream(ast_channel_stream(chan), offset, SEEK_END);
1074 } else if (offset) {
1075 ast_verb(3, "ControlPlayback seek to offset %ld\n", offset);
1076 ast_seekstream(ast_channel_stream(chan), offset, SEEK_SET);
1080 res = ast_waitstream_fr_w_cb(chan, breaks, fwd, rev, skipms, cb);
1082 res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
1090 /* We go at next loop if we got the restart char */
1091 if ((restart && strchr(restart, res)) || res == AST_CONTROL_STREAM_RESTART) {
1092 ast_debug(1, "we'll restart the stream here at next loop\n");
1093 pause_restart_point = 0;
1094 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1096 ast_channel_name(chan),
1101 if ((suspend && strchr(suspend, res)) || res == AST_CONTROL_STREAM_SUSPEND) {
1102 pause_restart_point = ast_tellstream(ast_channel_stream(chan));
1103 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1105 ast_channel_name(chan),
1108 ast_stopstream(chan);
1109 if (!(res = ast_waitfordigit(chan, 1000))) {
1111 } else if (res == -1 || (suspend && strchr(suspend, res)) || (stop && strchr(stop, res))
1112 || res == AST_CONTROL_STREAM_SUSPEND || res == AST_CONTROL_STREAM_STOP) {
1116 if ((suspend && (res == *suspend)) || res == AST_CONTROL_STREAM_SUSPEND) {
1118 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1120 ast_channel_name(chan),
1130 /* if we get one of our stop chars, return it to the calling function */
1131 if ((stop && strchr(stop, res)) || res == AST_CONTROL_STREAM_STOP) {
1132 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1134 ast_channel_name(chan),
1140 if (pause_restart_point) {
1141 offset = pause_restart_point;
1143 if (ast_channel_stream(chan)) {
1144 offset = ast_tellstream(ast_channel_stream(chan));
1146 offset = -8; /* indicate end of file */
1151 *offsetms = offset / 8; /* samples --> ms ... XXX Assumes 8 kHz */
1154 ast_stopstream(chan);
1159 int ast_control_streamfile_w_cb(struct ast_channel *chan,
1164 const char *suspend,
1165 const char *restart,
1168 ast_waitstream_fr_cb cb)
1170 return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, NULL, cb);
1173 int ast_control_streamfile(struct ast_channel *chan, const char *file,
1174 const char *fwd, const char *rev,
1175 const char *stop, const char *suspend,
1176 const char *restart, int skipms, long *offsetms)
1178 return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, NULL, NULL);
1181 int ast_control_streamfile_lang(struct ast_channel *chan, const char *file,
1182 const char *fwd, const char *rev, const char *stop, const char *suspend,
1183 const char *restart, int skipms, const char *lang, long *offsetms)
1185 return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, lang, NULL);
1188 enum control_tone_frame_response_result {
1189 CONTROL_TONE_RESPONSE_FAILED = -1,
1190 CONTROL_TONE_RESPONSE_NORMAL = 0,
1191 CONTROL_TONE_RESPONSE_FINISHED = 1,
1194 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)
1196 switch (fr->subclass.integer) {
1197 case AST_CONTROL_STREAM_STOP:
1198 ast_playtones_stop(chan);
1199 return CONTROL_TONE_RESPONSE_FINISHED;
1200 case AST_CONTROL_STREAM_SUSPEND:
1203 if (ast_playtones_start(chan, 0, ts ? ts->data : tone, 0)) {
1204 return CONTROL_TONE_RESPONSE_FAILED;
1208 ast_playtones_stop(chan);
1210 return CONTROL_TONE_RESPONSE_NORMAL;
1211 case AST_CONTROL_STREAM_RESTART:
1212 ast_playtones_stop(chan);
1213 if (ast_playtones_start(chan, 0, ts ? ts->data : tone, 0)) {
1214 return CONTROL_TONE_RESPONSE_FAILED;
1216 return CONTROL_TONE_RESPONSE_NORMAL;
1217 case AST_CONTROL_STREAM_REVERSE:
1218 ast_log(LOG_NOTICE, "Media control operation 'reverse' not supported for media type 'tone'\n");
1219 return CONTROL_TONE_RESPONSE_NORMAL;
1220 case AST_CONTROL_STREAM_FORWARD:
1221 ast_log(LOG_NOTICE, "Media control operation 'forward' not supported for media type 'tone'\n");
1222 return CONTROL_TONE_RESPONSE_NORMAL;
1223 case AST_CONTROL_HANGUP:
1224 case AST_CONTROL_BUSY:
1225 case AST_CONTROL_CONGESTION:
1226 return CONTROL_TONE_RESPONSE_FINISHED;
1229 return CONTROL_TONE_RESPONSE_NORMAL;
1232 static int parse_tone_uri(char *tone_parser,
1233 const char **tone_indication,
1234 const char **tone_zone)
1236 *tone_indication = strsep(&tone_parser, ";");
1238 if (ast_strlen_zero(tone_parser)) {
1239 /* Only the indication is included */
1243 if (!(strncmp(tone_parser, "tonezone=", 9))) {
1244 *tone_zone = tone_parser + 9;
1246 ast_log(LOG_ERROR, "Unexpected Tone URI component: %s\n", tone_parser);
1253 int ast_control_tone(struct ast_channel *chan, const char *tone)
1255 struct ast_tone_zone *zone = NULL;
1256 struct ast_tone_zone_sound *ts;
1260 const char *tone_indication = NULL;
1261 const char *tone_zone = NULL;
1262 char *tone_uri_parser;
1264 if (ast_strlen_zero(tone)) {
1268 tone_uri_parser = ast_strdupa(tone);
1270 if (parse_tone_uri(tone_uri_parser, &tone_indication, &tone_zone)) {
1275 zone = ast_get_indication_zone(tone_zone);
1278 ts = ast_get_indication_tone(zone ? zone : ast_channel_zone(chan), tone_indication);
1280 if (ast_playtones_start(chan, 0, ts ? ts->data : tone_indication, 0)) {
1285 struct ast_frame *fr;
1287 if (ast_waitfor(chan, -1) < 0) {
1292 fr = ast_read_noaudio(chan);
1299 if (fr->frametype != AST_FRAME_CONTROL) {
1303 res = control_tone_frame_response(chan, fr, ts, tone_indication, &paused);
1304 if (res == CONTROL_TONE_RESPONSE_FINISHED) {
1307 } else if (res == CONTROL_TONE_RESPONSE_FAILED) {
1314 ast_tone_zone_sound_unref(ts);
1318 ast_tone_zone_unref(zone);
1324 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
1328 if ((d = ast_streamfile(chan, fn, ast_channel_language(chan)))) {
1332 d = ast_waitstream(chan, AST_DIGIT_ANY);
1334 ast_stopstream(chan);
1340 * \brief Construct a silence frame of the same duration as \a orig.
1342 * The \a orig frame must be \ref AST_FORMAT_SLINEAR.
1344 * \param orig Frame as basis for silence to generate.
1345 * \return New frame of silence; free with ast_frfree().
1346 * \return \c NULL on error.
1348 static struct ast_frame *make_silence(const struct ast_frame *orig)
1350 struct ast_frame *silence;
1354 struct ast_frame *next;
1360 if (ast_format_cmp(orig->subclass.format, ast_format_slin) == AST_FORMAT_CMP_NOT_EQUAL) {
1361 ast_log(LOG_WARNING, "Attempting to silence non-slin frame\n");
1365 for (next = AST_LIST_NEXT(orig, frame_list);
1367 orig = next, next = orig ? AST_LIST_NEXT(orig, frame_list) : NULL) {
1368 samples += orig->samples;
1371 ast_verb(4, "Silencing %zu samples\n", samples);
1374 datalen = sizeof(short) * samples;
1375 size = sizeof(*silence) + datalen;
1376 silence = ast_calloc(1, size);
1381 silence->mallocd = AST_MALLOCD_HDR;
1382 silence->frametype = AST_FRAME_VOICE;
1383 silence->data.ptr = (void *)(silence + 1);
1384 silence->samples = samples;
1385 silence->datalen = datalen;
1387 silence->subclass.format = ast_format_slin;
1393 * \brief Sets a channel's read format to \ref AST_FORMAT_SLINEAR, recording
1394 * its original format.
1396 * \param chan Channel to modify.
1397 * \param[out] orig_format Output variable to store channel's original read
1399 * \return 0 on success.
1400 * \return -1 on error.
1402 static int set_read_to_slin(struct ast_channel *chan, struct ast_format **orig_format)
1404 if (!chan || !orig_format) {
1407 *orig_format = ao2_bump(ast_channel_readformat(chan));
1408 return ast_set_read_format(chan, ast_format_slin);
1411 static int global_silence_threshold = 128;
1412 static int global_maxsilence = 0;
1414 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
1415 * \param chan Channel to playback to/record from.
1416 * \param playfile Filename of sound to play before recording begins.
1417 * \param recordfile Filename to record to.
1418 * \param maxtime Maximum length of recording (in seconds).
1419 * \param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
1420 * \param duration Where to store actual length of the recorded message (in milliseconds).
1421 * \param sound_duration Where to store the length of the recorded message (in milliseconds), minus any silence
1422 * \param beep Whether to play a beep before starting to record.
1423 * \param silencethreshold
1424 * \param maxsilence Length of silence that will end a recording (in milliseconds).
1425 * \param path Optional filesystem path to unlock.
1426 * \param prepend If true, prepend the recorded audio to an existing file and follow prepend mode recording rules
1427 * \param acceptdtmf DTMF digits that will end the recording.
1428 * \param canceldtmf DTMF digits that will cancel the recording.
1429 * \param skip_confirmation_sound If true, don't play auth-thankyou at end. Nice for custom recording prompts in apps.
1431 * \retval -1 failure or hangup
1432 * \retval 'S' Recording ended from silence timeout
1433 * \retval 't' Recording ended from the message exceeding the maximum duration, or via DTMF in prepend mode
1434 * \retval dtmfchar Recording ended via the return value's DTMF character for either cancel or accept.
1436 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)
1441 int x, fmtcnt = 1, res = -1, outmsg = 0;
1442 struct ast_filestream *others[AST_MAX_FORMATS];
1443 char *sfmt[AST_MAX_FORMATS];
1444 char *stringp = NULL;
1446 struct ast_dsp *sildet = NULL; /* silence detector dsp */
1447 int totalsilence = 0;
1449 int olddspsilence = 0;
1450 struct ast_format *rfmt = NULL;
1451 struct ast_silence_generator *silgen = NULL;
1452 char prependfile[PATH_MAX];
1453 int ioflags; /* IO flags for writing output file */
1455 ioflags = O_CREAT|O_WRONLY;
1457 switch (if_exists) {
1458 case AST_RECORD_IF_EXISTS_FAIL:
1461 case AST_RECORD_IF_EXISTS_OVERWRITE:
1464 case AST_RECORD_IF_EXISTS_APPEND:
1465 ioflags |= O_APPEND;
1469 if (silencethreshold < 0) {
1470 silencethreshold = global_silence_threshold;
1473 if (maxsilence < 0) {
1474 maxsilence = global_maxsilence;
1477 /* barf if no pointer passed to store duration in */
1479 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
1483 ast_debug(1, "play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
1484 snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, ast_channel_name(chan));
1486 if (playfile || beep) {
1488 d = ast_play_and_wait(chan, playfile);
1491 d = ast_stream_and_wait(chan, "beep", "");
1499 ast_copy_string(prependfile, recordfile, sizeof(prependfile));
1500 strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
1503 fmts = ast_strdupa(fmt);
1506 strsep(&stringp, "|");
1507 ast_debug(1, "Recording Formats: sfmts=%s\n", fmts);
1508 sfmt[0] = ast_strdupa(fmts);
1510 while ((fmt = strsep(&stringp, "|"))) {
1511 if (fmtcnt > AST_MAX_FORMATS - 1) {
1512 ast_log(LOG_WARNING, "Please increase AST_MAX_FORMATS in file.h\n");
1515 sfmt[fmtcnt++] = ast_strdupa(fmt);
1518 end = start = time(NULL); /* pre-initialize end to be same as start in case we never get into loop */
1519 for (x = 0; x < fmtcnt; x++) {
1520 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, ioflags, 0, AST_FILE_MODE);
1521 ast_verb(3, "x=%d, open writing: %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
1529 ast_unlock_path(path);
1532 if (maxsilence > 0) {
1533 sildet = ast_dsp_new(); /* Create the silence detector */
1535 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
1538 ast_dsp_set_threshold(sildet, silencethreshold);
1539 res = set_read_to_slin(chan, &rfmt);
1541 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
1542 ast_dsp_free(sildet);
1549 /* Request a video update */
1550 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
1552 if (ast_opt_transmit_silence) {
1553 silgen = ast_channel_start_silence_generator(chan);
1558 /* Loop, writing the packets we read to the writer(s), until
1559 * we have reason to stop. */
1560 struct ast_frame *f;
1563 time_t pause_start = 0;
1564 int paused_secs = 0;
1565 int pausedsilence = 0;
1568 if (!(res = ast_waitfor(chan, 2000))) {
1569 ast_debug(1, "One waitfor failed, trying another\n");
1570 /* Try one more time in case of masq */
1571 if (!(res = ast_waitfor(chan, 2000))) {
1572 ast_log(LOG_WARNING, "No audio available on %s??\n", ast_channel_name(chan));
1581 if (!(f = ast_read(chan))) {
1584 if (f->frametype == AST_FRAME_VOICE) {
1585 /* write each format */
1590 RAII_VAR(struct ast_frame *, silence, NULL, ast_frame_dtor);
1591 struct ast_frame *orig = f;
1594 silence = make_silence(orig);
1596 ast_log(LOG_WARNING,
1597 "Error creating silence\n");
1602 for (x = 0; x < fmtcnt; x++) {
1603 if (prepend && !others[x]) {
1606 res = ast_writestream(others[x], f);
1611 /* Silence Detection */
1612 if (maxsilence > 0) {
1614 ast_dsp_silence(sildet, f, &dspsilence);
1615 if (olddspsilence > dspsilence) {
1616 totalsilence += olddspsilence;
1618 olddspsilence = dspsilence;
1621 /* record how much silence there was while we are paused */
1622 pausedsilence = dspsilence;
1623 } else if (dspsilence > pausedsilence) {
1624 /* ignore the paused silence */
1625 dspsilence -= pausedsilence;
1627 /* dspsilence has reset, reset pausedsilence */
1631 if (dspsilence > maxsilence) {
1632 /* Ended happily with silence */
1633 ast_verb(3, "Recording automatically stopped after a silence of %d seconds\n", dspsilence/1000);
1639 /* Exit on any error */
1641 ast_log(LOG_WARNING, "Error writing frame\n");
1644 } else if (f->frametype == AST_FRAME_VIDEO) {
1645 /* Write only once */
1646 ast_writestream(others[0], f);
1647 } else if (f->frametype == AST_FRAME_DTMF) {
1649 /* stop recording with any digit */
1650 ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
1655 if (strchr(acceptdtmf, f->subclass.integer)) {
1656 ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
1657 res = f->subclass.integer;
1661 if (strchr(canceldtmf, f->subclass.integer)) {
1662 ast_verb(3, "User canceled message by pressing %c\n", f->subclass.integer);
1663 res = f->subclass.integer;
1667 } else if (f->frametype == AST_FRAME_CONTROL) {
1668 if (f->subclass.integer == AST_CONTROL_RECORD_CANCEL) {
1669 ast_verb(3, "Message canceled by control\n");
1670 outmsg = 0; /* cancels the recording */
1673 } else if (f->subclass.integer == AST_CONTROL_RECORD_STOP) {
1674 ast_verb(3, "Message ended by control\n");
1677 } else if (f->subclass.integer == AST_CONTROL_RECORD_SUSPEND) {
1679 ast_verb(3, "Message %spaused by control\n",
1680 paused ? "" : "un");
1682 pause_start = time(NULL);
1684 paused_secs += time(NULL) - pause_start;
1686 } else if (f->subclass.integer == AST_CONTROL_RECORD_MUTE) {
1688 ast_verb(3, "Message %smuted by control\n",
1690 /* We can only silence slin frames, so
1691 * set the mode, if we haven't already
1694 if (muted && !rfmt) {
1695 ast_verb(3, "Setting read format to linear mode\n");
1696 res = set_read_to_slin(chan, &rfmt);
1698 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
1704 if (maxtime && !paused) {
1706 if (maxtime < (end - start - paused_secs)) {
1707 ast_verb(3, "Took too long, cutting it short...\n");
1716 ast_verb(3, "User hung up\n");
1723 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
1728 ast_channel_stop_silence_generator(chan, silgen);
1733 * Instead of asking how much time passed (end - start), calculate the number
1734 * of seconds of audio which actually went into the file. This fixes a
1735 * problem where audio is stopped up on the network and never gets to us.
1737 * Note that we still want to use the number of seconds passed for the max
1738 * message, otherwise we could get a situation where this stream is never
1739 * closed (which would create a resource leak).
1741 *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
1742 if (sound_duration) {
1743 *sound_duration = *duration;
1747 /* Reduce duration by a total silence amount */
1748 if (olddspsilence <= dspsilence) {
1749 totalsilence += dspsilence;
1752 if (sound_duration) {
1753 if (totalsilence > 0) {
1754 *sound_duration -= (totalsilence - 200) / 1000;
1756 if (*sound_duration < 0) {
1757 *sound_duration = 0;
1761 if (dspsilence > 0) {
1762 *duration -= (dspsilence - 200) / 1000;
1765 if (*duration < 0) {
1769 for (x = 0; x < fmtcnt; x++) {
1774 * If we ended with silence, trim all but the first 200ms of silence
1775 * off the recording. However, if we ended with '#', we don't want
1776 * to trim ANY part of the recording.
1778 if (res > 0 && dspsilence) {
1779 /* rewind only the trailing silence */
1780 ast_stream_rewind(others[x], dspsilence - 200);
1782 ast_truncstream(others[x]);
1783 ast_closestream(others[x]);
1787 if (prepend && outmsg) {
1788 struct ast_filestream *realfiles[AST_MAX_FORMATS];
1789 struct ast_frame *fr;
1791 for (x = 0; x < fmtcnt; x++) {
1792 snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
1793 realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
1794 if (!others[x] || !realfiles[x]) {
1797 /*!\note Same logic as above. */
1799 ast_stream_rewind(others[x], dspsilence - 200);
1801 ast_truncstream(others[x]);
1802 /* add the original file too */
1803 while ((fr = ast_readframe(realfiles[x]))) {
1804 ast_writestream(others[x], fr);
1807 ast_closestream(others[x]);
1808 ast_closestream(realfiles[x]);
1809 ast_filerename(prependfile, recordfile, sfmt[x]);
1810 ast_verb(4, "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
1811 ast_filedelete(prependfile, sfmt[x]);
1814 if (rfmt && ast_set_read_format(chan, rfmt)) {
1815 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_format_get_name(rfmt), ast_channel_name(chan));
1818 if ((outmsg == 2) && (!skip_confirmation_sound)) {
1819 ast_stream_and_wait(chan, "auth-thankyou", "");
1822 ast_dsp_free(sildet);
1827 static const char default_acceptdtmf[] = "#";
1828 static const char default_canceldtmf[] = "";
1830 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)
1832 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);
1835 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)
1837 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);
1840 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)
1842 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);
1845 /* Channel group core functions */
1847 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
1851 char *grp = NULL, *cat = NULL;
1853 if (!ast_strlen_zero(data)) {
1854 ast_copy_string(tmp, data, sizeof(tmp));
1856 if ((cat = strchr(tmp, '@'))) {
1861 if (!ast_strlen_zero(grp)) {
1862 ast_copy_string(group, grp, group_max);
1867 if (!ast_strlen_zero(cat)) {
1868 ast_copy_string(category, cat, category_max);
1874 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
1877 char group[80] = "", category[80] = "";
1878 struct ast_group_info *gi = NULL;
1881 if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
1885 /* Calculate memory we will need if this is new */
1886 len = sizeof(*gi) + strlen(group) + 1;
1887 if (!ast_strlen_zero(category)) {
1888 len += strlen(category) + 1;
1891 AST_RWLIST_WRLOCK(&groups);
1892 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1893 if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
1894 AST_RWLIST_REMOVE_CURRENT(group_list);
1899 AST_RWLIST_TRAVERSE_SAFE_END;
1901 if (ast_strlen_zero(group)) {
1902 /* Enable unsetting the group */
1903 } else if ((gi = calloc(1, len))) {
1905 gi->group = (char *) gi + sizeof(*gi);
1906 strcpy(gi->group, group);
1907 if (!ast_strlen_zero(category)) {
1908 gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
1909 strcpy(gi->category, category);
1911 AST_RWLIST_INSERT_TAIL(&groups, gi, group_list);
1916 AST_RWLIST_UNLOCK(&groups);
1921 int ast_app_group_get_count(const char *group, const char *category)
1923 struct ast_group_info *gi = NULL;
1926 if (ast_strlen_zero(group)) {
1930 AST_RWLIST_RDLOCK(&groups);
1931 AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
1932 if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
1936 AST_RWLIST_UNLOCK(&groups);
1941 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
1943 struct ast_group_info *gi = NULL;
1944 regex_t regexbuf_group;
1945 regex_t regexbuf_category;
1948 if (ast_strlen_zero(groupmatch)) {
1949 ast_log(LOG_NOTICE, "groupmatch empty\n");
1953 /* if regex compilation fails, return zero matches */
1954 if (regcomp(®exbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) {
1955 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch);
1959 if (!ast_strlen_zero(category) && regcomp(®exbuf_category, category, REG_EXTENDED | REG_NOSUB)) {
1960 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", category);
1961 regfree(®exbuf_group);
1965 AST_RWLIST_RDLOCK(&groups);
1966 AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
1967 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)))) {
1971 AST_RWLIST_UNLOCK(&groups);
1973 regfree(®exbuf_group);
1974 if (!ast_strlen_zero(category)) {
1975 regfree(®exbuf_category);
1981 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
1983 struct ast_group_info *gi = NULL;
1985 AST_RWLIST_WRLOCK(&groups);
1986 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1987 if (gi->chan == old) {
1989 } else if (gi->chan == new) {
1990 AST_RWLIST_REMOVE_CURRENT(group_list);
1994 AST_RWLIST_TRAVERSE_SAFE_END;
1995 AST_RWLIST_UNLOCK(&groups);
2000 int ast_app_group_discard(struct ast_channel *chan)
2002 struct ast_group_info *gi = NULL;
2004 AST_RWLIST_WRLOCK(&groups);
2005 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
2006 if (gi->chan == chan) {
2007 AST_RWLIST_REMOVE_CURRENT(group_list);
2011 AST_RWLIST_TRAVERSE_SAFE_END;
2012 AST_RWLIST_UNLOCK(&groups);
2017 int ast_app_group_list_wrlock(void)
2019 return AST_RWLIST_WRLOCK(&groups);
2022 int ast_app_group_list_rdlock(void)
2024 return AST_RWLIST_RDLOCK(&groups);
2027 struct ast_group_info *ast_app_group_list_head(void)
2029 return AST_RWLIST_FIRST(&groups);
2032 int ast_app_group_list_unlock(void)
2034 return AST_RWLIST_UNLOCK(&groups);
2037 #undef ast_app_separate_args
2038 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen);
2040 unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen)
2043 char *scan, *wasdelim = NULL;
2044 int paren = 0, quote = 0, bracket = 0;
2046 if (!array || !arraylen) {
2050 memset(array, 0, arraylen * sizeof(*array));
2058 for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
2060 for (; *scan; scan++) {
2063 } else if (*scan == ')') {
2067 } else if (*scan == '[') {
2069 } else if (*scan == ']') {
2073 } else if (*scan == '"' && delim != '"') {
2074 quote = quote ? 0 : 1;
2076 /* Remove quote character from argument */
2077 memmove(scan, scan + 1, strlen(scan));
2080 } else if (*scan == '\\') {
2082 /* Literal character, don't parse */
2083 memmove(scan, scan + 1, strlen(scan));
2087 } else if ((*scan == delim) && !paren && !quote && !bracket) {
2095 /* If the last character in the original string was the delimiter, then
2096 * there is one additional argument. */
2097 if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
2098 array[argc++] = scan;
2104 /* ABI compatible function */
2105 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
2107 return __ast_app_separate_args(buf, delim, 1, array, arraylen);
2110 static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
2116 int lp = strlen(path);
2119 s = ast_alloca(lp + 10);
2120 fs = ast_alloca(lp + 20);
2122 snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, (unsigned long)ast_random());
2123 fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
2125 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
2126 return AST_LOCK_PATH_NOT_FOUND;
2130 snprintf(s, strlen(path) + 9, "%s/.lock", path);
2132 while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
2139 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
2140 return AST_LOCK_TIMEOUT;
2142 ast_debug(1, "Locked path '%s'\n", path);
2143 return AST_LOCK_SUCCESS;
2147 static int ast_unlock_path_lockfile(const char *path)
2152 s = ast_alloca(strlen(path) + 10);
2154 snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
2156 if ((res = unlink(s))) {
2157 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
2159 ast_debug(1, "Unlocked path '%s'\n", path);
2166 AST_LIST_ENTRY(path_lock) le;
2171 static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
2173 static void path_lock_destroy(struct path_lock *obj)
2184 static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
2190 struct path_lock *pl;
2191 struct stat st, ost;
2193 fs = ast_alloca(strlen(path) + 20);
2195 snprintf(fs, strlen(path) + 19, "%s/lock", path);
2196 if (lstat(fs, &st) == 0) {
2197 if ((st.st_mode & S_IFMT) == S_IFLNK) {
2198 ast_log(LOG_WARNING, "Unable to create lock file "
2199 "'%s': it's already a symbolic link\n",
2201 return AST_LOCK_FAILURE;
2203 if (st.st_nlink > 1) {
2204 ast_log(LOG_WARNING, "Unable to create lock file "
2205 "'%s': %u hard links exist\n",
2206 fs, (unsigned int) st.st_nlink);
2207 return AST_LOCK_FAILURE;
2210 if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
2211 ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
2212 fs, strerror(errno));
2213 return AST_LOCK_PATH_NOT_FOUND;
2215 if (!(pl = ast_calloc(1, sizeof(*pl)))) {
2216 /* We don't unlink the lock file here, on the possibility that
2217 * someone else created it - better to leave a little mess
2218 * than create a big one by destroying someone else's lock
2219 * and causing something to be corrupted.
2222 return AST_LOCK_FAILURE;
2225 pl->path = strdup(path);
2230 ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
2232 ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
2234 (errno == EWOULDBLOCK) &&
2235 (time(NULL) - start < 5))
2238 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
2239 path, strerror(errno));
2240 /* No unlinking of lock done, since we tried and failed to
2243 path_lock_destroy(pl);
2244 return AST_LOCK_TIMEOUT;
2247 /* Check for the race where the file is recreated or deleted out from
2250 if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
2251 st.st_dev != ost.st_dev &&
2252 st.st_ino != ost.st_ino) {
2253 ast_log(LOG_WARNING, "Unable to create lock file '%s': "
2254 "file changed underneath us\n", fs);
2255 path_lock_destroy(pl);
2256 return AST_LOCK_FAILURE;
2259 /* Success: file created, flocked, and is the one we started with */
2260 AST_LIST_LOCK(&path_lock_list);
2261 AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
2262 AST_LIST_UNLOCK(&path_lock_list);
2264 ast_debug(1, "Locked path '%s'\n", path);
2266 return AST_LOCK_SUCCESS;
2269 static int ast_unlock_path_flock(const char *path)
2272 struct path_lock *p;
2274 s = ast_alloca(strlen(path) + 20);
2276 AST_LIST_LOCK(&path_lock_list);
2277 AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
2278 if (!strcmp(p->path, path)) {
2279 AST_LIST_REMOVE_CURRENT(le);
2283 AST_LIST_TRAVERSE_SAFE_END;
2284 AST_LIST_UNLOCK(&path_lock_list);
2287 snprintf(s, strlen(path) + 19, "%s/lock", path);
2289 path_lock_destroy(p);
2290 ast_debug(1, "Unlocked path '%s'\n", path);
2292 ast_debug(1, "Failed to unlock path '%s': "
2293 "lock not found\n", path);
2299 void ast_set_lock_type(enum AST_LOCK_TYPE type)
2301 ast_lock_type = type;
2304 enum AST_LOCK_RESULT ast_lock_path(const char *path)
2306 enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
2308 switch (ast_lock_type) {
2309 case AST_LOCK_TYPE_LOCKFILE:
2310 r = ast_lock_path_lockfile(path);
2312 case AST_LOCK_TYPE_FLOCK:
2313 r = ast_lock_path_flock(path);
2320 int ast_unlock_path(const char *path)
2324 switch (ast_lock_type) {
2325 case AST_LOCK_TYPE_LOCKFILE:
2326 r = ast_unlock_path_lockfile(path);
2328 case AST_LOCK_TYPE_FLOCK:
2329 r = ast_unlock_path_flock(path);
2336 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
2338 int silencethreshold;
2342 int max_attempts = 3;
2345 int message_exists = 0;
2346 /* Note that urgent and private are for flagging messages as such in the future */
2348 /* barf if no pointer passed to store duration in */
2350 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
2354 cmd = '3'; /* Want to start by recording */
2356 silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
2358 while ((cmd >= 0) && (cmd != 't')) {
2361 if (!message_exists) {
2362 /* In this case, 1 is to record a message */
2366 ast_stream_and_wait(chan, "vm-msgsaved", "");
2372 ast_verb(3, "Reviewing the recording\n");
2373 cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
2378 ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
2380 if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, NULL, silencethreshold, maxsilence, path)) == -1) {
2381 /* User has hung up, no options to give */
2386 } else if (cmd == '*') {
2389 /* If all is well, a message exists */
2402 cmd = ast_play_and_wait(chan, "vm-sorry");
2405 if (message_exists) {
2406 cmd = ast_play_and_wait(chan, "vm-review");
2408 if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
2409 cmd = ast_waitfordigit(chan, 600);
2414 cmd = ast_waitfordigit(chan, 6000);
2419 if (attempts > max_attempts) {
2430 #define RES_UPONE (1 << 16)
2431 #define RES_EXIT (1 << 17)
2432 #define RES_REPEAT (1 << 18)
2433 #define RES_RESTART ((1 << 19) | RES_REPEAT)
2435 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
2437 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
2440 int (*ivr_func)(struct ast_channel *, void *);
2444 switch (option->action) {
2445 case AST_ACTION_UPONE:
2447 case AST_ACTION_EXIT:
2448 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
2449 case AST_ACTION_REPEAT:
2450 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
2451 case AST_ACTION_RESTART:
2452 return RES_RESTART ;
2453 case AST_ACTION_NOOP:
2455 case AST_ACTION_BACKGROUND:
2456 res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
2458 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
2462 case AST_ACTION_PLAYBACK:
2463 res = ast_stream_and_wait(chan, (char *)option->adata, "");
2465 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
2469 case AST_ACTION_MENU:
2470 if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
2471 /* Do not pass entry errors back up, treat as though it was an "UPONE" */
2475 case AST_ACTION_WAITOPTION:
2476 if (!(res = ast_waitfordigit(chan, ast_channel_pbx(chan) ? ast_channel_pbx(chan)->rtimeoutms : 10000))) {
2480 case AST_ACTION_CALLBACK:
2481 ivr_func = option->adata;
2482 res = ivr_func(chan, cbdata);
2484 case AST_ACTION_TRANSFER:
2485 res = ast_parseable_goto(chan, option->adata);
2487 case AST_ACTION_PLAYLIST:
2488 case AST_ACTION_BACKLIST:
2490 c = ast_strdupa(option->adata);
2491 while ((n = strsep(&c, ";"))) {
2492 if ((res = ast_stream_and_wait(chan, n,
2493 (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
2497 ast_stopstream(chan);
2500 ast_log(LOG_NOTICE, "Unknown dispatch function %u, ignoring!\n", option->action);
2506 static int option_exists(struct ast_ivr_menu *menu, char *option)
2509 for (x = 0; menu->options[x].option; x++) {
2510 if (!strcasecmp(menu->options[x].option, option)) {
2517 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
2520 for (x = 0; menu->options[x].option; x++) {
2521 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
2522 (menu->options[x].option[strlen(option)])) {
2529 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
2533 while (option_matchmore(menu, exten)) {
2534 ms = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->dtimeoutms : 5000;
2535 if (strlen(exten) >= maxexten - 1) {
2538 if ((res = ast_waitfordigit(chan, ms)) < 1) {
2541 exten[strlen(exten) + 1] = '\0';
2542 exten[strlen(exten)] = res;
2544 return res > 0 ? 0 : res;
2547 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
2549 /* Execute an IVR menu structure */
2553 char exten[AST_MAX_EXTENSION] = "s";
2554 if (option_exists(menu, "s") < 0) {
2556 if (option_exists(menu, "g") < 0) {
2557 ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
2562 while (menu->options[pos].option) {
2563 if (!strcasecmp(menu->options[pos].option, exten)) {
2564 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
2565 ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
2568 } else if (res & RES_UPONE) {
2570 } else if (res & RES_EXIT) {
2572 } else if (res & RES_REPEAT) {
2573 int maxretries = res & 0xffff;
2574 if ((res & RES_RESTART) == RES_RESTART) {
2582 if ((maxretries > 0) && (retries >= maxretries)) {
2583 ast_debug(1, "Max retries %d exceeded\n", maxretries);
2586 if (option_exists(menu, "g") > -1) {
2588 } else if (option_exists(menu, "s") > -1) {
2594 } else if (res && strchr(AST_DIGIT_ANY, res)) {
2595 ast_debug(1, "Got start of extension, %c\n", res);
2598 if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
2601 if (option_exists(menu, exten) < 0) {
2602 if (option_exists(menu, "i")) {
2603 ast_debug(1, "Invalid extension entered, going to 'i'!\n");
2608 ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
2613 ast_debug(1, "New existing extension: %s\n", exten);
2621 ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
2623 if (!strcasecmp(exten, "s")) {
2632 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
2634 int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
2635 /* Hide internal coding */
2636 return res > 0 ? 0 : res;
2639 char *ast_read_textfile(const char *filename)
2641 int fd, count = 0, res;
2642 char *output = NULL;
2643 struct stat filesize;
2645 if (stat(filename, &filesize) == -1) {
2646 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
2650 count = filesize.st_size + 1;
2652 if ((fd = open(filename, O_RDONLY)) < 0) {
2653 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
2657 if ((output = ast_malloc(count))) {
2658 res = read(fd, output, count - 1);
2659 if (res == count - 1) {
2662 ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
2673 static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
2676 int curarg, res = 0;
2677 unsigned int argloc;
2678 struct ast_flags *flags = _flags;
2679 struct ast_flags64 *flags64 = _flags;
2681 if (flaglen == 32) {
2682 ast_clear_flag(flags, AST_FLAGS_ALL);
2693 curarg = *s++ & 0x7f; /* the array (in app.h) has 128 entries */
2694 argloc = options[curarg].arg_index;
2696 int paren = 1, quote = 0;
2697 int parsequotes = (s[1] == '"') ? 1 : 0;
2702 if (*s == '(' && !quote) {
2704 } else if (*s == ')' && !quote) {
2705 /* Count parentheses, unless they're within quotes (or backslashed, below) */
2707 } else if (*s == '"' && parsequotes) {
2708 /* Leave embedded quotes alone, unless they are the first character */
2709 quote = quote ? 0 : 1;
2710 ast_copy_string(s, s + 1, INT_MAX);
2712 } else if (*s == '\\') {
2714 /* If a backslash is found outside of quotes, remove it */
2715 ast_copy_string(s, s + 1, INT_MAX);
2716 } else if (quote && s[1] == '"') {
2717 /* Backslash for a quote character within quotes, remove the backslash */
2718 ast_copy_string(s, s + 1, INT_MAX);
2720 /* Backslash within quotes, keep both characters */
2729 /* This will find the closing paren we found above, or none, if the string ended before we found one. */
2730 if ((s = strchr(s, ')'))) {
2732 args[argloc - 1] = arg;
2736 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
2740 } else if (argloc) {
2741 args[argloc - 1] = "";
2743 if (flaglen == 32) {
2744 ast_set_flag(flags, options[curarg].flag);
2746 ast_set_flag64(flags64, options[curarg].flag);
2753 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
2755 return parse_options(options, flags, args, optstr, 32);
2758 int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
2760 return parse_options(options, flags, args, optstr, 64);
2763 void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
2765 unsigned int i, found = 0;
2766 for (i = 32; i < 128 && found < len; i++) {
2767 if (ast_test_flag64(flags, options[i].flag)) {
2774 int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
2779 if (ast_strlen_zero(stream)) {
2784 if (*stream == '\\') {
2786 switch (*(stream + 1)) {
2798 if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
2800 if (*(stream + 2) <= '9') {
2801 *result = *(stream + 2) - '0';
2802 } else if (*(stream + 2) <= 'F') {
2803 *result = *(stream + 2) - 'A' + 10;
2805 *result = *(stream + 2) - 'a' + 10;
2808 ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
2812 if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
2815 if (*(stream + 3) <= '9') {
2816 *result += *(stream + 3) - '0';
2817 } else if (*(stream + 3) <= 'F') {
2818 *result += *(stream + 3) - 'A' + 10;
2820 *result += *(stream + 3) - 'a' + 10;
2827 for (i = 2; ; i++) {
2828 if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
2830 ast_debug(5, "result was %d, ", *result);
2832 *result += *(stream + i) - '0';
2833 ast_debug(5, "is now %d\n", *result);
2840 *result = *(stream + 1);
2849 char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
2854 while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
2862 int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
2868 if (strchr(stream, '\\')) {
2869 while (!ast_get_encoded_char(stream, &next, &consumed)) {
2870 if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
2871 ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
2873 if (offset + 2 > ast_str_size(*str)) {
2876 buf = ast_str_buffer(*str);
2877 buf[offset++] = next;
2880 buf = ast_str_buffer(*str);
2881 buf[offset++] = '\0';
2882 ast_str_update(*str);
2884 ast_str_set(str, maxlen, "%s", stream);
2889 void ast_close_fds_above_n(int n)
2894 int ast_safe_fork(int stop_reaper)
2896 sigset_t signal_set, old_set;
2899 /* Don't let the default signal handler for children reap our status */
2901 ast_replace_sigchld();
2904 sigfillset(&signal_set);
2905 pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
2910 /* Fork failed or parent */
2911 pthread_sigmask(SIG_SETMASK, &old_set, NULL);
2912 if (!stop_reaper && pid > 0) {
2913 struct zombie *cur = ast_calloc(1, sizeof(*cur));
2916 AST_LIST_LOCK(&zombies);
2917 AST_LIST_INSERT_TAIL(&zombies, cur, list);
2918 AST_LIST_UNLOCK(&zombies);
2919 if (shaun_of_the_dead_thread == AST_PTHREADT_NULL) {
2920 if (ast_pthread_create_background(&shaun_of_the_dead_thread, NULL, shaun_of_the_dead, NULL)) {
2921 ast_log(LOG_ERROR, "Shaun of the Dead wants to kill zombies, but can't?!!\n");
2922 shaun_of_the_dead_thread = AST_PTHREADT_NULL;
2931 cap_t cap = cap_from_text("cap_net_admin-eip");
2933 if (cap_set_proc(cap)) {
2934 ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
2939 /* Before we unblock our signals, return our trapped signals back to the defaults */
2940 signal(SIGHUP, SIG_DFL);
2941 signal(SIGCHLD, SIG_DFL);
2942 signal(SIGINT, SIG_DFL);
2943 signal(SIGURG, SIG_DFL);
2944 signal(SIGTERM, SIG_DFL);
2945 signal(SIGPIPE, SIG_DFL);
2946 signal(SIGXFSZ, SIG_DFL);
2948 /* unblock important signal handlers */
2949 if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
2950 ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
2958 void ast_safe_fork_cleanup(void)
2960 ast_unreplace_sigchld();
2963 int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
2967 #ifdef HAVE_LONG_DOUBLE_WIDER
2969 #define FMT "%30Lf%9s"
2972 #define FMT "%30lf%9s"
2978 res = sscanf(timestr, FMT, &amount, u);
2980 if (res == 0 || res == EOF) {
2983 } else if (res == 2) {
2987 unit = TIMELEN_HOURS;
2991 unit = TIMELEN_SECONDS;
2995 if (toupper(u[1]) == 'S') {
2996 unit = TIMELEN_MILLISECONDS;
2997 } else if (u[1] == '\0') {
2998 unit = TIMELEN_MINUTES;
3008 case TIMELEN_MINUTES:
3011 case TIMELEN_SECONDS:
3014 case TIMELEN_MILLISECONDS:
3017 *result = amount > INT_MAX ? INT_MAX : (int) amount;
3023 static void mwi_state_dtor(void *obj)
3025 struct ast_mwi_state *mwi_state = obj;
3026 ast_string_field_free_memory(mwi_state);
3027 ao2_cleanup(mwi_state->snapshot);
3028 mwi_state->snapshot = NULL;
3031 struct stasis_topic *ast_mwi_topic_all(void)
3033 return mwi_topic_all;
3036 struct stasis_cache *ast_mwi_state_cache(void)
3038 return mwi_state_cache;
3041 struct stasis_topic *ast_mwi_topic_cached(void)
3043 return stasis_caching_get_topic(mwi_topic_cached);
3046 struct stasis_topic *ast_mwi_topic(const char *uniqueid)
3048 return stasis_topic_pool_get_topic(mwi_topic_pool, uniqueid);
3051 struct ast_mwi_state *ast_mwi_create(const char *mailbox, const char *context)
3053 RAII_VAR(struct ast_mwi_state *, mwi_state, NULL, ao2_cleanup);
3055 ast_assert(!ast_strlen_zero(mailbox));
3057 mwi_state = ao2_alloc(sizeof(*mwi_state), mwi_state_dtor);
3062 if (ast_string_field_init(mwi_state, 256)) {
3065 if (!ast_strlen_zero(context)) {
3066 ast_string_field_build(mwi_state, uniqueid, "%s@%s", mailbox, context);
3068 ast_string_field_set(mwi_state, uniqueid, mailbox);
3071 ao2_ref(mwi_state, +1);
3077 * \brief Create a MWI state snapshot message.
3080 * \param[in] mailbox The mailbox identifier string.
3081 * \param[in] context The context this mailbox resides in (NULL or "" if only using mailbox)
3082 * \param[in] new_msgs The number of new messages in this mailbox
3083 * \param[in] old_msgs The number of old messages in this mailbox
3084 * \param[in] channel_id A unique identifier for a channel associated with this
3085 * change in mailbox state
3086 * \param[in] eid The EID of the server that originally published the message
3088 * \retval message on success. Use ao2_cleanup() when done with it.
3089 * \retval NULL on error.
3091 static struct stasis_message *mwi_state_create_message(
3092 const char *mailbox,
3093 const char *context,
3096 const char *channel_id,
3097 struct ast_eid *eid)
3099 struct ast_mwi_state *mwi_state;
3100 struct stasis_message *message;
3102 if (!ast_mwi_state_type()) {
3106 mwi_state = ast_mwi_create(mailbox, context);
3111 mwi_state->new_msgs = new_msgs;
3112 mwi_state->old_msgs = old_msgs;
3114 if (!ast_strlen_zero(channel_id)) {
3115 struct stasis_message *chan_message;
3117 chan_message = stasis_cache_get(ast_channel_cache(), ast_channel_snapshot_type(),
3120 mwi_state->snapshot = stasis_message_data(chan_message);
3121 ao2_ref(mwi_state->snapshot, +1);
3123 ao2_cleanup(chan_message);
3127 mwi_state->eid = *eid;
3129 mwi_state->eid = ast_eid_default;
3133 * XXX As far as stasis is concerned, all MWI events are local.
3135 * We may in the future want to make MWI aggregate local/remote
3136 * message counts similar to how device state aggregates state.
3138 message = stasis_message_create_full(ast_mwi_state_type(), mwi_state, &ast_eid_default);
3139 ao2_cleanup(mwi_state);
3143 int ast_publish_mwi_state_full(
3144 const char *mailbox,
3145 const char *context,
3148 const char *channel_id,
3149 struct ast_eid *eid)
3151 struct ast_mwi_state *mwi_state;
3152 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
3153 struct stasis_topic *mailbox_specific_topic;
3155 message = mwi_state_create_message(mailbox, context, new_msgs, old_msgs, channel_id, eid);
3160 mwi_state = stasis_message_data(message);
3161 mailbox_specific_topic = ast_mwi_topic(mwi_state->uniqueid);
3162 if (!mailbox_specific_topic) {
3166 stasis_publish(mailbox_specific_topic, message);
3171 int ast_delete_mwi_state_full(const char *mailbox, const char *context, struct ast_eid *eid)
3173 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
3174 struct stasis_message *cached_msg;
3175 struct stasis_message *clear_msg;
3176 struct ast_mwi_state *mwi_state;
3177 struct stasis_topic *mailbox_specific_topic;
3179 msg = mwi_state_create_message(mailbox, context, 0, 0, NULL, eid);
3184 mwi_state = stasis_message_data(msg);
3187 * XXX As far as stasis is concerned, all MWI events are local.
3189 * For now, it is assumed that there is only one entity
3190 * maintaining the state of a particular mailbox.
3192 * If we ever have multiple MWI event entities maintaining
3193 * the same mailbox that wish to delete their cached entry
3194 * we will need to do something about the race condition
3195 * potential between checking the cache and removing the
3198 cached_msg = stasis_cache_get_by_eid(ast_mwi_state_cache(),
3199 ast_mwi_state_type(), mwi_state->uniqueid, &ast_eid_default);
3201 /* Nothing to clear */
3204 ao2_cleanup(cached_msg);
3206 mailbox_specific_topic = ast_mwi_topic(mwi_state->uniqueid);
3207 if (!mailbox_specific_topic) {
3211 clear_msg = stasis_cache_clear_create(msg);
3213 stasis_publish(mailbox_specific_topic, clear_msg);
3215 ao2_cleanup(clear_msg);
3219 static const char *mwi_state_get_id(struct stasis_message *message)
3221 if (ast_mwi_state_type() == stasis_message_type(message)) {
3222 struct ast_mwi_state *mwi_state = stasis_message_data(message);
3223 return mwi_state->uniqueid;
3224 } else if (stasis_subscription_change_type() == stasis_message_type(message)) {
3225 struct stasis_subscription_change *change = stasis_message_data(message);
3226 return change->uniqueid;
3232 static void mwi_blob_dtor(void *obj)
3234 struct ast_mwi_blob *mwi_blob = obj;
3236 ao2_cleanup(mwi_blob->mwi_state);
3237 ast_json_unref(mwi_blob->blob);
3240 struct stasis_message *ast_mwi_blob_create(struct ast_mwi_state *mwi_state,
3241 struct stasis_message_type *message_type,
3242 struct ast_json *blob)
3244 RAII_VAR(struct ast_mwi_blob *, obj, NULL, ao2_cleanup);
3245 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
3247 ast_assert(blob != NULL);
3249 if (!message_type) {
3253 obj = ao2_alloc(sizeof(*obj), mwi_blob_dtor);
3258 obj->mwi_state = mwi_state;
3259 ao2_ref(obj->mwi_state, +1);
3260 obj->blob = ast_json_ref(blob);
3262 /* This is not a normal MWI event. Only used by the MinivmNotify app. */
3263 msg = stasis_message_create(message_type, obj);
3272 struct stasis_topic *ast_queue_topic_all(void)
3274 return queue_topic_all;
3277 struct stasis_topic *ast_queue_topic(const char *queuename)
3279 return stasis_topic_pool_get_topic(queue_topic_pool, queuename);
3282 static void app_cleanup(void)
3284 ao2_cleanup(queue_topic_pool);
3285 queue_topic_pool = NULL;
3286 ao2_cleanup(queue_topic_all);
3287 queue_topic_all = NULL;
3288 ao2_cleanup(mwi_topic_pool);
3289 mwi_topic_pool = NULL;
3290 ao2_cleanup(mwi_topic_all);
3291 mwi_topic_all = NULL;
3292 ao2_cleanup(mwi_state_cache);
3293 mwi_state_cache = NULL;
3294 mwi_topic_cached = stasis_caching_unsubscribe_and_join(mwi_topic_cached);
3295 STASIS_MESSAGE_TYPE_CLEANUP(ast_mwi_state_type);
3296 STASIS_MESSAGE_TYPE_CLEANUP(ast_mwi_vm_app_type);
3301 ast_register_cleanup(app_cleanup);
3303 if (STASIS_MESSAGE_TYPE_INIT(ast_mwi_state_type) != 0) {
3306 if (STASIS_MESSAGE_TYPE_INIT(ast_mwi_vm_app_type) != 0) {
3309 mwi_topic_all = stasis_topic_create("stasis_mwi_topic");
3310 if (!mwi_topic_all) {
3313 mwi_state_cache = stasis_cache_create(mwi_state_get_id);
3314 if (!mwi_state_cache) {
3317 mwi_topic_cached = stasis_caching_topic_create(mwi_topic_all, mwi_state_cache);
3318 if (!mwi_topic_cached) {
3321 mwi_topic_pool = stasis_topic_pool_create(mwi_topic_all);
3322 if (!mwi_topic_pool) {
3325 queue_topic_all = stasis_topic_create("stasis_queue_topic");
3326 if (!queue_topic_all) {
3329 queue_topic_pool = stasis_topic_pool_create(queue_topic_all);
3330 if (!queue_topic_pool) {