Debian Codegraph @

main/app.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2005, Digium, Inc.
5 *
6 * Mark Spencer <[email protected]>
7 *
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.
13 *
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.
17 */
18
19 /*! \file
20 *
21 * \brief Convenient Application Routines
22 *
23 * \author Mark Spencer <[email protected]>
24 */
25
26 /*!
27 * Application Skeleton is an example of creating an application for Asterisk.
28 * \example app_skel.c
29 */
30
31 /*** MODULEINFO
32 <support_level>core</support_level>
33 ***/
34
35 #include "asterisk.h"
36
37 #ifdef HAVE_SYS_STAT_H
38 #include <sys/stat.h>
39 #endif
40 #include <regex.h> /* for regcomp(3) */
41 #include <sys/file.h> /* for flock(2) */
42 #include <signal.h> /* for pthread_sigmask(3) */
43 #include <stdlib.h> /* for closefrom(3) */
44 #include <sys/types.h>
45 #include <sys/wait.h> /* for waitpid(2) */
46 #ifndef HAVE_CLOSEFROM
47 #include <dirent.h> /* for opendir(3) */
48 #endif
49 #ifdef HAVE_CAP
50 #include <sys/capability.h>
51 #endif /* HAVE_CAP */
52
53 #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
54 #include "asterisk/channel.h"
55 #include "asterisk/pbx.h"
56 #include "asterisk/file.h"
57 #include "asterisk/app.h"
58 #include "asterisk/dsp.h"
59 #include "asterisk/utils.h"
60 #include "asterisk/lock.h"
61 #include "asterisk/indications.h"
62 #include "asterisk/linkedlists.h"
63 #include "asterisk/threadstorage.h"
64 #include "asterisk/test.h"
65 #include "asterisk/module.h"
66 #include "asterisk/astobj2.h"
67 #include "asterisk/stasis.h"
68 #include "asterisk/stasis_channels.h"
69 #include "asterisk/json.h"
70 #include "asterisk/format_cache.h"
71
72 AST_THREADSTORAGE_PUBLIC(ast_str_thread_global_buf);
73
74 static pthread_t shaun_of_the_dead_thread = AST_PTHREADT_NULL;
75
76 struct zombie {
77 pid_t pid;
78 AST_LIST_ENTRY(zombie) list;
79 };
80
81 static AST_LIST_HEAD_STATIC(zombies, zombie);
82
83 #ifdef HAVE_CAP
84 static cap_t child_cap;
85 #endif
86 /*!
87 * \brief Define \ref stasis topic objects
88 * @{
89 */
90 static struct stasis_topic *queue_topic_all;
91 static struct stasis_topic_pool *queue_topic_pool;
92
93 /*! @} */
94
95 static void *shaun_of_the_dead(void *data)
96 {
97 struct zombie *cur;
98 int status;
99 for (;;) {
100 if (!AST_LIST_EMPTY(&zombies)) {
101 /* Don't allow cancellation while we have a lock. */
102 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
103 AST_LIST_LOCK(&zombies);
104 AST_LIST_TRAVERSE_SAFE_BEGIN(&zombies, cur, list) {
105 if (waitpid(cur->pid, &status, WNOHANG) != 0) {
106 AST_LIST_REMOVE_CURRENT(list);
107 ast_free(cur);
108 }
109 }
110 AST_LIST_TRAVERSE_SAFE_END
111 AST_LIST_UNLOCK(&zombies);
112 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
113 }
114 pthread_testcancel();
115 /* Wait for 60 seconds, without engaging in a busy loop. */
116 ast_poll(NULL, 0, AST_LIST_FIRST(&zombies) ? 5000 : 60000);
117 }
118 return NULL;
119 }
120
121
122 #define AST_MAX_FORMATS 10
123
124 static AST_RWLIST_HEAD_STATIC(groups, ast_group_info);
125
126 /*!
127 * \brief This function presents a dialtone and reads an extension into 'collect'
128 * which must be a pointer to a **pre-initialized** array of char having a
129 * size of 'size' suitable for writing to. It will collect no more than the smaller
130 * of 'maxlen' or 'size' minus the original strlen() of collect digits.
131 * \param chan struct.
132 * \param context
133 * \param collect
134 * \param size
135 * \param maxlen
136 * \param timeout timeout in milliseconds
137 */
138 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
139 {
140 struct ast_tone_zone_sound *ts;
141 int res = 0, x = 0;
142
143 if (maxlen > size) {
144 maxlen = size;
145 }
146
147 if (!timeout) {
148 if (ast_channel_pbx(chan) && ast_channel_pbx(chan)->dtimeoutms) {
149 timeout = ast_channel_pbx(chan)->dtimeoutms;
150 } else {
151 timeout = 5000;
152 }
153 }
154
155 if ((ts = ast_get_indication_tone(ast_channel_zone(chan), "dial"))) {
156 res = ast_playtones_start(chan, 0, ts->data, 0);
157 ts = ast_tone_zone_sound_unref(ts);
158 } else {
159 ast_log(LOG_NOTICE, "Huh....? no dial for indications?\n");
160 }
161
162 for (x = strlen(collect); x < maxlen; ) {
163 res = ast_waitfordigit(chan, timeout);
164 if (!ast_ignore_pattern(context, collect)) {
165 ast_playtones_stop(chan);
166 }
167 if (res < 1) {
168 break;
169 }
170 if (res == '#') {
171 break;
172 }
173 collect[x++] = res;
174 if (!ast_matchmore_extension(chan, context, collect, 1,
175 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
176 break;
177 }
178 }
179
180 if (res >= 0) {
181 res = ast_exists_extension(chan, context, collect, 1,
182 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL)) ? 1 : 0;
183 }
184
185 return res;
186 }
187
188 enum ast_getdata_result ast_app_getdata(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout)
189 {
190 return ast_app_getdata_terminator(c, prompt, s, maxlen, timeout, NULL);
191 }
192
193 enum ast_getdata_result ast_app_getdata_terminator(struct ast_channel *c, const char *prompt, char *s,
194 int maxlen, int timeout, char *terminator)
195 {
196 int res = 0, to, fto;
197 char *front, *filename;
198
199 /* XXX Merge with full version? XXX */
200
201 if (maxlen)
202 s[0] = '\0';
203
204 if (!prompt)
205 prompt = "";
206
207 filename = ast_strdupa(prompt);
208 while ((front = ast_strsep(&filename, '&', AST_STRSEP_STRIP | AST_STRSEP_TRIM))) {
209 if (!ast_strlen_zero(front)) {
210 res = ast_streamfile(c, front, ast_channel_language(c));
211 if (res)
212 continue;
213 }
214 if (ast_strlen_zero(filename)) {
215 /* set timeouts for the last prompt */
216 fto = ast_channel_pbx(c) ? ast_channel_pbx(c)->rtimeoutms : 6000;
217 to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
218
219 if (timeout > 0) {
220 fto = to = timeout;
221 }
222 if (timeout < 0) {
223 fto = to = 1000000000;
224 }
225 } else {
226 /* there is more than one prompt, so
227 * get rid of the long timeout between
228 * prompts, and make it 50ms */
229 fto = 50;
230 to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
231 }
232 res = ast_readstring(c, s, maxlen, to, fto, (terminator ? terminator : "#"));
233 if (res == AST_GETDATA_EMPTY_END_TERMINATED) {
234 return res;
235 }
236 if (!ast_strlen_zero(s)) {
237 return res;
238 }
239 }
240
241 return res;
242 }
243
244 /* The lock type used by ast_lock_path() / ast_unlock_path() */
245 static enum AST_LOCK_TYPE ast_lock_type = AST_LOCK_TYPE_LOCKFILE;
246
247 int ast_app_getdata_full(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
248 {
249 int res, to = 2000, fto = 6000;
250
251 if (!ast_strlen_zero(prompt)) {
252 res = ast_streamfile(c, prompt, ast_channel_language(c));
253 if (res < 0) {
254 return res;
255 }
256 }
257
258 if (timeout > 0) {
259 fto = to = timeout;
260 }
261 if (timeout < 0) {
262 fto = to = 1000000000;
263 }
264
265 res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
266
267 return res;
268 }
269
270 /* BUGBUG this is not thread safe. */
271 static const struct ast_app_stack_funcs *app_stack_callbacks;
272
273 void ast_install_stack_functions(const struct ast_app_stack_funcs *funcs)
274 {
275 app_stack_callbacks = funcs;
276 }
277
278 const char *ast_app_expand_sub_args(struct ast_channel *chan, const char *args)
279 {
280 const struct ast_app_stack_funcs *funcs;
281 const char *new_args;
282
283 funcs = app_stack_callbacks;
284 if (!funcs || !funcs->expand_sub_args || !ast_module_running_ref(funcs->module)) {
285 ast_log(LOG_WARNING,
286 "Cannot expand 'Gosub(%s)' arguments. The app_stack module is not available.\n",
287 args);
288 return NULL;
289 }
290
291 new_args = funcs->expand_sub_args(chan, args);
292 ast_module_unref(funcs->module);
293
294 return new_args;
295 }
296
297 int ast_app_exec_sub(struct ast_channel *autoservice_chan, struct ast_channel *sub_chan, const char *sub_args, int ignore_hangup)
298 {
299 const struct ast_app_stack_funcs *funcs;
300 int res;
301
302 funcs = app_stack_callbacks;
303 if (!funcs || !funcs->run_sub || !ast_module_running_ref(funcs->module)) {
304 ast_log(LOG_WARNING,
305 "Cannot run 'Gosub(%s)'. The app_stack module is not available.\n",
306 sub_args);
307 return -1;
308 }
309
310 if (autoservice_chan) {
311 ast_autoservice_start(autoservice_chan);
312 }
313
314 res = funcs->run_sub(sub_chan, sub_args, ignore_hangup);
315 ast_module_unref(funcs->module);
316
317 if (autoservice_chan) {
318 ast_autoservice_stop(autoservice_chan);
319 }
320
321 if (!ignore_hangup && ast_check_hangup_locked(sub_chan)) {
322 ast_queue_hangup(sub_chan);
323 }
324
325 return res;
326 }
327
328 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)
329 {
330 int res;
331 char *args_str;
332 size_t args_len;
333
334 if (ast_strlen_zero(sub_args)) {
335 return ast_app_exec_sub(autoservice_chan, sub_chan, sub_location, ignore_hangup);
336 }
337
338 /* Create the Gosub application argument string. */
339 args_len = strlen(sub_location) + strlen(sub_args) + 3;
340 args_str = ast_malloc(args_len);
341 if (!args_str) {
342 return -1;
343 }
344 snprintf(args_str, args_len, "%s(%s)", sub_location, sub_args);
345
346 res = ast_app_exec_sub(autoservice_chan, sub_chan, args_str, ignore_hangup);
347 ast_free(args_str);
348 return res;
349 }
350
351 /*! \brief The container for the voicemail provider */
352 static AO2_GLOBAL_OBJ_STATIC(vm_provider);
353
354 /*! Voicemail not registered warning */
355 static int vm_warnings;
356
357 int ast_vm_is_registered(void)
358 {
359 struct ast_vm_functions *table;
360 int is_registered;
361
362 table = ao2_global_obj_ref(vm_provider);
363 is_registered = table ? 1 : 0;
364 ao2_cleanup(table);
365 return is_registered;
366 }
367
368 int __ast_vm_register(const struct ast_vm_functions *vm_table, struct ast_module *module)
369 {
370 RAII_VAR(struct ast_vm_functions *, table, NULL, ao2_cleanup);
371
372 if (!vm_table->module_name) {
373 ast_log(LOG_ERROR, "Voicemail provider missing required information.\n");
374 return -1;
375 }
376 if (vm_table->module_version != VM_MODULE_VERSION) {
377 ast_log(LOG_ERROR, "Voicemail provider '%s' has incorrect version\n",
378 vm_table->module_name);
379 return -1;
380 }
381
382 table = ao2_global_obj_ref(vm_provider);
383 if (table) {
384 ast_log(LOG_WARNING, "Voicemail provider already registered by %s.\n",
385 table->module_name);
386 return AST_MODULE_LOAD_DECLINE;
387 }
388
389 table = ao2_alloc_options(sizeof(*table), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
390 if (!table) {
391 return -1;
392 }
393 *table = *vm_table;
394 table->module = module;
395
396 ao2_global_obj_replace_unref(vm_provider, table);
397 return 0;
398 }
399
400 void ast_vm_unregister(const char *module_name)
401 {
402 struct ast_vm_functions *table;
403
404 table = ao2_global_obj_ref(vm_provider);
405 if (table && !strcmp(table->module_name, module_name)) {
406 ao2_global_obj_release(vm_provider);
407 }
408 ao2_cleanup(table);
409 }
410
411 #ifdef TEST_FRAMEWORK
412 /*! \brief Holding container for the voicemail provider used while testing */
413 static AO2_GLOBAL_OBJ_STATIC(vm_provider_holder);
414 static int provider_is_swapped = 0;
415
416 void ast_vm_test_swap_table_in(const struct ast_vm_functions *vm_table)
417 {
418 RAII_VAR(struct ast_vm_functions *, holding_table, NULL, ao2_cleanup);
419 RAII_VAR(struct ast_vm_functions *, new_table, NULL, ao2_cleanup);
420
421 if (provider_is_swapped) {
422 ast_log(LOG_ERROR, "Attempted to swap in test function table without swapping out old test table.\n");
423 return;
424 }
425
426 holding_table = ao2_global_obj_ref(vm_provider);
427
428 if (holding_table) {
429 ao2_global_obj_replace_unref(vm_provider_holder, holding_table);
430 }
431
432 new_table = ao2_alloc_options(sizeof(*new_table), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
433 if (!new_table) {
434 return;
435 }
436 *new_table = *vm_table;
437
438 ao2_global_obj_replace_unref(vm_provider, new_table);
439 provider_is_swapped = 1;
440 }
441
442 void ast_vm_test_swap_table_out(void)
443 {
444 RAII_VAR(struct ast_vm_functions *, held_table, NULL, ao2_cleanup);
445
446 if (!provider_is_swapped) {
447 ast_log(LOG_ERROR, "Attempted to swap out test function table, but none is currently installed.\n");
448 return;
449 }
450
451 held_table = ao2_global_obj_ref(vm_provider_holder);
452 if (!held_table) {
453 return;
454 }
455
456 ao2_global_obj_replace_unref(vm_provider, held_table);
457 ao2_global_obj_release(vm_provider_holder);
458 provider_is_swapped = 0;
459 }
460 #endif
461
462 /*! \brief The container for the voicemail greeter provider */
463 static AO2_GLOBAL_OBJ_STATIC(vm_greeter_provider);
464
465 /*! Voicemail greeter not registered warning */
466 static int vm_greeter_warnings;
467
468 int ast_vm_greeter_is_registered(void)
469 {
470 struct ast_vm_greeter_functions *table;
471 int is_registered;
472
473 table = ao2_global_obj_ref(vm_greeter_provider);
474 is_registered = table ? 1 : 0;
475 ao2_cleanup(table);
476 return is_registered;
477 }
478
479 int __ast_vm_greeter_register(const struct ast_vm_greeter_functions *vm_table, struct ast_module *module)
480 {
481 RAII_VAR(struct ast_vm_greeter_functions *, table, NULL, ao2_cleanup);
482
483 if (!vm_table->module_name) {
484 ast_log(LOG_ERROR, "Voicemail greeter provider missing required information.\n");
485 return -1;
486 }
487 if (vm_table->module_version != VM_GREETER_MODULE_VERSION) {
488 ast_log(LOG_ERROR, "Voicemail greeter provider '%s' has incorrect version\n",
489 vm_table->module_name);
490 return -1;
491 }
492
493 table = ao2_global_obj_ref(vm_greeter_provider);
494 if (table) {
495 ast_log(LOG_WARNING, "Voicemail greeter provider already registered by %s.\n",
496 table->module_name);
497 return AST_MODULE_LOAD_DECLINE;
498 }
499
500 table = ao2_alloc_options(sizeof(*table), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
501 if (!table) {
502 return -1;
503 }
504 *table = *vm_table;
505 table->module = module;
506
507 ao2_global_obj_replace_unref(vm_greeter_provider, table);
508 return 0;
509 }
510
511 void ast_vm_greeter_unregister(const char *module_name)
512 {
513 struct ast_vm_greeter_functions *table;
514
515 table = ao2_global_obj_ref(vm_greeter_provider);
516 if (table && !strcmp(table->module_name, module_name)) {
517 ao2_global_obj_release(vm_greeter_provider);
518 }
519 ao2_cleanup(table);
520 }
521
522 #ifdef TEST_FRAMEWORK
523 static ast_vm_test_create_user_fn *ast_vm_test_create_user_func = NULL;
524 static ast_vm_test_destroy_user_fn *ast_vm_test_destroy_user_func = NULL;
525
526 void ast_install_vm_test_functions(ast_vm_test_create_user_fn *vm_test_create_user_func,
527 ast_vm_test_destroy_user_fn *vm_test_destroy_user_func)
528 {
529 ast_vm_test_create_user_func = vm_test_create_user_func;
530 ast_vm_test_destroy_user_func = vm_test_destroy_user_func;
531 }
532
533 void ast_uninstall_vm_test_functions(void)
534 {
535 ast_vm_test_create_user_func = NULL;
536 ast_vm_test_destroy_user_func = NULL;
537 }
538 #endif
539
540 static void vm_warn_no_provider(void)
541 {
542 if (vm_warnings++ % 10 == 0) {
543 ast_verb(3, "No voicemail provider registered.\n");
544 }
545 }
546
547 #define VM_API_CALL(res, api_call, api_parms) \
548 do { \
549 struct ast_vm_functions *table; \
550 table = ao2_global_obj_ref(vm_provider); \
551 if (!table) { \
552 vm_warn_no_provider(); \
553 } else if (table->api_call) { \
554 ast_module_ref(table->module); \
555 (res) = table->api_call api_parms; \
556 ast_module_unref(table->module); \
557 } \
558 ao2_cleanup(table); \
559 } while (0)
560
561 static void vm_greeter_warn_no_provider(void)
562 {
563 if (vm_greeter_warnings++ % 10 == 0) {
564 ast_verb(3, "No voicemail greeter provider registered.\n");
565 }
566 }
567
568 #define VM_GREETER_API_CALL(res, api_call, api_parms) \
569 do { \
570 struct ast_vm_greeter_functions *table; \
571 table = ao2_global_obj_ref(vm_greeter_provider); \
572 if (!table) { \
573 vm_greeter_warn_no_provider(); \
574 } else if (table->api_call) { \
575 ast_module_ref(table->module); \
576 (res) = table->api_call api_parms; \
577 ast_module_unref(table->module); \
578 } \
579 ao2_cleanup(table); \
580 } while (0)
581
582 int ast_app_has_voicemail(const char *mailboxes, const char *folder)
583 {
584 int res = 0;
585
586 VM_API_CALL(res, has_voicemail, (mailboxes, folder));
587 return res;
588 }
589
590 /*!
591 * \internal
592 * \brief Function used as a callback for ast_copy_recording_to_vm when a real one isn't installed.
593 * \param vm_rec_data Stores crucial information about the voicemail that will basically just be used
594 * to figure out what the name of the recipient was supposed to be
595 */
596 int ast_app_copy_recording_to_vm(struct ast_vm_recording_data *vm_rec_data)
597 {
598 int res = -1;
599
600 VM_API_CALL(res, copy_recording_to_vm, (vm_rec_data));
601 return res;
602 }
603
604 int ast_app_inboxcount(const char *mailboxes, int *newmsgs, int *oldmsgs)
605 {
606 int res = 0;
607
608 if (newmsgs) {
609 *newmsgs = 0;
610 }
611 if (oldmsgs) {
612 *oldmsgs = 0;
613 }
614
615 VM_API_CALL(res, inboxcount, (mailboxes, newmsgs, oldmsgs));
616 return res;
617 }
618
619 int ast_app_inboxcount2(const char *mailboxes, int *urgentmsgs, int *newmsgs, int *oldmsgs)
620 {
621 int res = 0;
622
623 if (newmsgs) {
624 *newmsgs = 0;
625 }
626 if (oldmsgs) {
627 *oldmsgs = 0;
628 }
629 if (urgentmsgs) {
630 *urgentmsgs = 0;
631 }
632
633 VM_API_CALL(res, inboxcount2, (mailboxes, urgentmsgs, newmsgs, oldmsgs));
634 return res;
635 }
636
637 int ast_app_sayname(struct ast_channel *chan, const char *mailbox_id)
638 {
639 int res = -1;
640
641 VM_GREETER_API_CALL(res, sayname, (chan, mailbox_id));
642 return res;
643 }
644
645 int ast_app_messagecount(const char *mailbox_id, const char *folder)
646 {
647 int res = 0;
648
649 VM_API_CALL(res, messagecount, (mailbox_id, folder));
650 return res;
651 }
652
653 const char *ast_vm_index_to_foldername(int id)
654 {
655 const char *res = NULL;
656
657 VM_API_CALL(res, index_to_foldername, (id));
658 return res;
659 }
660
661 struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_create(const char *mailbox,
662 const char *context,
663 const char *folder,
664 int descending,
665 enum ast_vm_snapshot_sort_val sort_val,
666 int combine_INBOX_and_OLD)
667 {
668 struct ast_vm_mailbox_snapshot *res = NULL;
669
670 VM_API_CALL(res, mailbox_snapshot_create, (mailbox, context, folder, descending,
671 sort_val, combine_INBOX_and_OLD));
672 return res;
673 }
674
675 struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_destroy(struct ast_vm_mailbox_snapshot *mailbox_snapshot)
676 {
677 struct ast_vm_mailbox_snapshot *res = NULL;
678
679 VM_API_CALL(res, mailbox_snapshot_destroy, (mailbox_snapshot));
680 return res;
681 }
682
683 int ast_vm_msg_move(const char *mailbox,
684 const char *context,
685 size_t num_msgs,
686 const char *oldfolder,
687 const char *old_msg_ids[],
688 const char *newfolder)
689 {
690 int res = 0;
691
692 VM_API_CALL(res, msg_move, (mailbox, context, num_msgs, oldfolder, old_msg_ids,
693 newfolder));
694 return res;
695 }
696
697 int ast_vm_msg_remove(const char *mailbox,
698 const char *context,
699 size_t num_msgs,
700 const char *folder,
701 const char *msgs[])
702 {
703 int res = 0;
704
705 VM_API_CALL(res, msg_remove, (mailbox, context, num_msgs, folder, msgs));
706 return res;
707 }
708
709 int ast_vm_msg_forward(const char *from_mailbox,
710 const char *from_context,
711 const char *from_folder,
712 const char *to_mailbox,
713 const char *to_context,
714 const char *to_folder,
715 size_t num_msgs,
716 const char *msg_ids[],
717 int delete_old)
718 {
719 int res = 0;
720
721 VM_API_CALL(res, msg_forward, (from_mailbox, from_context, from_folder, to_mailbox,
722 to_context, to_folder, num_msgs, msg_ids, delete_old));
723 return res;
724 }
725
726 int ast_vm_msg_play(struct ast_channel *chan,
727 const char *mailbox,
728 const char *context,
729 const char *folder,
730 const char *msg_num,
731 ast_vm_msg_play_cb *cb)
732 {
733 int res = 0;
734
735 VM_API_CALL(res, msg_play, (chan, mailbox, context, folder, msg_num, cb));
736 return res;
737 }
738
739 #ifdef TEST_FRAMEWORK
740 int ast_vm_test_create_user(const char *context, const char *mailbox)
741 {
742 if (ast_vm_test_create_user_func) {
743 return ast_vm_test_create_user_func(context, mailbox);
744 }
745 return 0;
746 }
747
748 int ast_vm_test_destroy_user(const char *context, const char *mailbox)
749 {
750 if (ast_vm_test_destroy_user_func) {
751 return ast_vm_test_destroy_user_func(context, mailbox);
752 }
753 return 0;
754 }
755 #endif
756
757 static int external_sleep(struct ast_channel *chan, int ms)
758 {
759 usleep(ms * 1000);
760 return 0;
761 }
762
763 static int sf_stream(struct ast_channel *chan, struct ast_channel *chan2, const char *digits, int frequency, int is_external)
764 {
765 /* Bell System Technical Journal 39 (Nov. 1960) */
766 #define SF_ON 67
767 #define SF_OFF 33
768 #define SF_BETWEEN 600
769
770 const char *ptr;
771 int res;
772 struct ast_silence_generator *silgen = NULL, *silgen2 = NULL;
773 char *freq;
774 int (*my_sleep)(struct ast_channel *chan, int ms);
775
776 if (frequency >= 100000) {
777 ast_log(LOG_WARNING, "Frequency too large: %d\n", frequency);
778 return -1;
779 }
780
781 if (is_external) {
782 my_sleep = external_sleep;
783 } else {
784 my_sleep = ast_safe_sleep;
785 }
786
787 /* Need a quiet time before sending digits. */
788 if (ast_opt_transmit_silence) {
789 silgen = ast_channel_start_silence_generator(chan);
790 if (chan2) {
791 silgen2 = ast_channel_start_silence_generator(chan2);
792 }
793 }
794 if (chan2) {
795 ast_autoservice_start(chan2);
796 }
797 res = my_sleep(chan, 100);
798 if (chan2) {
799 ast_autoservice_stop(chan2);
800 }
801 if (res) {
802 goto sf_stream_cleanup;
803 }
804
805 /* len(SF_ON) + len(SF_OFF) + len(0) + maxlen(frequency) + /,/ + null terminator = 2 + 2 + 1 + 5 at most + 3 + 1 = 14 */
806 #define SF_BUF_LEN 20
807 freq = ast_alloca(SF_BUF_LEN); /* min 20 to avoid compiler warning about insufficient buffer */
808 /* pauses need to send audio, so send 0 Hz */
809 snprintf(freq, SF_BUF_LEN, "%d/%d,%d/%d", frequency, SF_ON, 0, SF_OFF);
810
811 for (ptr = digits; *ptr; ptr++) {
812 if (*ptr == 'w') {
813 /* 'w' -- wait half a second */
814 if (chan2) {
815 ast_autoservice_start(chan2);
816 }
817 res = my_sleep(chan, 500);
818 if (chan2) {
819 ast_autoservice_stop(chan2);
820 }
821 if (res) {
822 break;
823 }
824 } else if (*ptr == 'h' || *ptr == 'H') {
825 /* 'h' -- 2600 Hz for half a second, but
826 only to far end of trunk, not near end */
827 ast_playtones_start(chan, 0, "2600", 0);
828 if (chan2) {
829 ast_playtones_start(chan2, 0, "0", 0);
830 ast_autoservice_start(chan2);
831 }
832 res = my_sleep(chan, 250);
833 ast_senddigit_mf_end(chan);
834 if (chan2) {
835 ast_autoservice_stop(chan2);
836 ast_senddigit_mf_end(chan2);
837 }
838 if (res) {
839 break;
840 }
841 } else if (strchr("0123456789*#ABCDabcdwWfF", *ptr)) {
842 if (*ptr == 'f' || *ptr == 'F') {
843 /* ignore return values if not supported by channel */
844 ast_indicate(chan, AST_CONTROL_FLASH);
845 } else if (*ptr == 'W') {
846 /* ignore return values if not supported by channel */
847 ast_indicate(chan, AST_CONTROL_WINK);
848 } else {
849 /* Character represents valid SF */
850 int beeps;
851 if (*ptr == '*') {
852 beeps = 11;
853 } else if (*ptr == '#') {
854 beeps = 12;
855 } else if (*ptr == 'D') {
856 beeps = 13;
857 } else if (*ptr == 'C') {
858 beeps = 14;
859 } else if (*ptr == 'B') {
860 beeps = 15;
861 } else if (*ptr == 'A') {
862 beeps = 16;
863 } else {
864 beeps = (*ptr == '0') ? 10 : *ptr - '0';
865 }
866 while (beeps-- > 0) {
867 ast_playtones_start(chan, 0, freq, 0);
868 if (chan2) {
869 ast_playtones_start(chan2, 0, freq, 0);
870 ast_autoservice_start(chan2);
871 }
872 res = my_sleep(chan, SF_ON + SF_OFF);
873 ast_senddigit_mf_end(chan);
874 if (chan2) {
875 ast_autoservice_stop(chan2);
876 ast_senddigit_mf_end(chan2);
877 }
878 if (res) {
879 break;
880 }
881 }
882 }
883 /* pause between digits */
884 ast_playtones_start(chan, 0, "0", 0);
885 if (chan2) {
886 ast_playtones_start(chan2, 0, "0", 0);
887 ast_autoservice_start(chan2);
888 }
889 res = my_sleep(chan, SF_BETWEEN);
890 if (chan2) {
891 ast_autoservice_stop(chan2);
892 ast_senddigit_mf_end(chan2);
893 }
894 ast_senddigit_mf_end(chan);
895 if (res) {
896 break;
897 }
898 } else {
899 ast_log(LOG_WARNING, "Illegal SF character '%c' in string. (0-9A-DwWfFhH allowed)\n", *ptr);
900 }
901 }
902
903 sf_stream_cleanup:
904 if (silgen) {
905 ast_channel_stop_silence_generator(chan, silgen);
906 }
907 if (silgen2) {
908 ast_channel_stop_silence_generator(chan2, silgen2);
909 }
910
911 return res;
912 }
913
914 static int mf_stream(struct ast_channel *chan, struct ast_channel *chan2, const char *digits, int between, unsigned int duration,
915 unsigned int durationkp, unsigned int durationst, int is_external)
916 {
917 const char *ptr;
918 int res;
919 struct ast_silence_generator *silgen = NULL, *silgen2 = NULL;
920 int (*my_sleep)(struct ast_channel *chan, int ms);
921
922 if (is_external) {
923 my_sleep = external_sleep;
924 } else {
925 my_sleep = ast_safe_sleep;
926 }
927
928 if (!between) {
929 between = 100;
930 }
931
932 /* Need a quiet time before sending digits. */
933 if (ast_opt_transmit_silence) {
934 silgen = ast_channel_start_silence_generator(chan);
935 if (chan2) {
936 silgen2 = ast_channel_start_silence_generator(chan2);
937 }
938 }
939 if (chan2) {
940 ast_autoservice_start(chan2);
941 }
942 res = my_sleep(chan, 100);
943 if (chan2) {
944 ast_autoservice_stop(chan2);
945 }
946 if (res) {
947 goto mf_stream_cleanup;
948 }
949
950 for (ptr = digits; *ptr; ptr++) {
951 if (*ptr == 'w') {
952 /* 'w' -- wait half a second */
953 if (chan2) {
954 ast_autoservice_start(chan2);
955 }
956 res = my_sleep(chan, 500);
957 if (chan2) {
958 ast_autoservice_stop(chan2);
959 }
960 if (res) {
961 break;
962 }
963 } else if (*ptr == 'h' || *ptr == 'H') {
964 /* 'h' -- 2600 Hz for half a second, but
965 only to far end of trunk, not near end */
966 ast_playtones_start(chan, 0, "2600", 0);
967 if (chan2) {
968 ast_playtones_start(chan2, 0, "0", 0);
969 ast_autoservice_start(chan2);
970 }
971 res = my_sleep(chan, 250);
972 ast_senddigit_mf_end(chan);
973 if (chan2) {
974 ast_autoservice_stop(chan2);
975 ast_senddigit_mf_end(chan2);
976 }
977 if (res) {
978 break;
979 }
980 } else if (strchr("0123456789*#ABCwWfF", *ptr)) {
981 if (*ptr == 'f' || *ptr == 'F') {
982 /* ignore return values if not supported by channel */
983 ast_indicate(chan, AST_CONTROL_FLASH);
984 } else if (*ptr == 'W') {
985 /* ignore return values if not supported by channel */
986 ast_indicate(chan, AST_CONTROL_WINK);
987 } else {
988 /* Character represents valid MF */
989 ast_senddigit_mf(chan, *ptr, duration, durationkp, durationst, is_external);
990 if (chan2) {
991 ast_senddigit_mf(chan2, *ptr, duration, durationkp, durationst, is_external);
992 }
993 }
994 /* pause between digits */
995 /* The DSP code in Asterisk does not currently properly receive repeated tones
996 if no audio is sent in the middle. Simply sending audio (even 0 Hz)
997 works around this limitation and guarantees the correct behavior.
998 */
999 ast_playtones_start(chan, 0, "0", 0);
1000 if (chan2) {
1001 ast_playtones_start(chan2, 0, "0", 0);
1002 ast_autoservice_start(chan2);
1003 }
1004 res = my_sleep(chan, between);
1005 ast_senddigit_mf_end(chan);
1006 if (chan2) {
1007 ast_autoservice_stop(chan2);
1008 ast_senddigit_mf_end(chan2);
1009 }
1010 if (res) {
1011 break;
1012 }
1013 } else {
1014 ast_log(LOG_WARNING, "Illegal MF character '%c' in string. (0-9*#ABCwWfFhH allowed)\n", *ptr);
1015 }
1016 }
1017
1018 mf_stream_cleanup:
1019 if (silgen) {
1020 ast_channel_stop_silence_generator(chan, silgen);
1021 }
1022 if (silgen2) {
1023 ast_channel_stop_silence_generator(chan2, silgen2);
1024 }
1025
1026 return res;
1027 }
1028
1029 static int dtmf_stream(struct ast_channel *chan, const char *digits, int between, unsigned int duration, int is_external)
1030 {
1031 const char *ptr;
1032 int res;
1033 struct ast_silence_generator *silgen = NULL;
1034 int (*my_sleep)(struct ast_channel *chan, int ms);
1035 int (*my_senddigit)(struct ast_channel *chan, char digit, unsigned int duration);
1036
1037 if (is_external) {
1038 my_sleep = external_sleep;
1039 my_senddigit = ast_senddigit_external;
1040 } else {
1041 my_sleep = ast_safe_sleep;
1042 my_senddigit = ast_senddigit;
1043 }
1044
1045 if (!between) {
1046 between = 100;
1047 }
1048
1049 /* Need a quiet time before sending digits. */
1050 if (ast_opt_transmit_silence) {
1051 silgen = ast_channel_start_silence_generator(chan);
1052 }
1053 res = my_sleep(chan, 100);
1054 if (res) {
1055 goto dtmf_stream_cleanup;
1056 }
1057
1058 for (ptr = digits; *ptr; ptr++) {
1059 if (*ptr == 'w') {
1060 /* 'w' -- wait half a second */
1061 res = my_sleep(chan, 500);
1062 if (res) {
1063 break;
1064 }
1065 } else if (*ptr == 'W') {
1066 /* 'W' -- wait a second */
1067 res = my_sleep(chan, 1000);
1068 if (res) {
1069 break;
1070 }
1071 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
1072 if (*ptr == 'f' || *ptr == 'F') {
1073 /* ignore return values if not supported by channel */
1074 ast_indicate(chan, AST_CONTROL_FLASH);
1075 } else {
1076 /* Character represents valid DTMF */
1077 my_senddigit(chan, *ptr, duration);
1078 }
1079 /* pause between digits */
1080 res = my_sleep(chan, between);
1081 if (res) {
1082 break;
1083 }
1084 } else {
1085 ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n", *ptr);
1086 }
1087 }
1088
1089 dtmf_stream_cleanup:
1090 if (silgen) {
1091 ast_channel_stop_silence_generator(chan, silgen);
1092 }
1093
1094 return res;
1095 }
1096
1097 int ast_sf_stream(struct ast_channel *chan, struct ast_channel *peer, struct ast_channel *chan2, const char *digits, int frequency, int is_external)
1098 {
1099 int res;
1100 if (frequency <= 0) {
1101 frequency = 2600;
1102 }
1103 if (!is_external && !chan2 && peer && ast_autoservice_start(peer)) {
1104 return -1;
1105 }
1106 res = sf_stream(chan, chan2, digits, frequency, is_external);
1107 if (!is_external && !chan2 && peer && ast_autoservice_stop(peer)) {
1108 res = -1;
1109 }
1110 return res;
1111 }
1112
1113 int ast_mf_stream(struct ast_channel *chan, struct ast_channel *peer, struct ast_channel *chan2, const char *digits,
1114 int between, unsigned int duration, unsigned int durationkp, unsigned int durationst, int is_external)
1115 {
1116 int res;
1117 if (!is_external && !chan2 && peer && ast_autoservice_start(peer)) {
1118 return -1;
1119 }
1120 res = mf_stream(chan, chan2, digits, between, duration, durationkp, durationst, is_external);
1121 if (!is_external && !chan2 && peer && ast_autoservice_stop(peer)) {
1122 res = -1;
1123 }
1124 return res;
1125 }
1126
1127 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between, unsigned int duration)
1128 {
1129 int res;
1130
1131 if (peer && ast_autoservice_start(peer)) {
1132 return -1;
1133 }
1134 res = dtmf_stream(chan, digits, between, duration, 0);
1135 if (peer && ast_autoservice_stop(peer)) {
1136 res = -1;
1137 }
1138
1139 return res;
1140 }
1141
1142 void ast_dtmf_stream_external(struct ast_channel *chan, const char *digits, int between, unsigned int duration)
1143 {
1144 dtmf_stream(chan, digits, between, duration, 1);
1145 }
1146
1147 struct linear_state {
1148 int fd;
1149 int autoclose;
1150 int allowoverride;
1151 struct ast_format *origwfmt;
1152 };
1153
1154 static void linear_release(struct ast_channel *chan, void *params)
1155 {
1156 struct linear_state *ls = params;
1157
1158 if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt)) {
1159 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%s'\n",
1160 ast_channel_name(chan), ast_format_get_name(ls->origwfmt));
1161 }
1162 ao2_cleanup(ls->origwfmt);
1163
1164 if (ls->autoclose) {
1165 close(ls->fd);
1166 }
1167
1168 ast_free(params);
1169 }
1170
1171 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
1172 {
1173 short buf[2048 + AST_FRIENDLY_OFFSET / 2];
1174 struct linear_state *ls = data;
1175 struct ast_frame f = {
1176 .frametype = AST_FRAME_VOICE,
1177 .data.ptr = buf + AST_FRIENDLY_OFFSET / 2,
1178 .offset = AST_FRIENDLY_OFFSET,
1179 };
1180 int res;
1181
1182 f.subclass.format = ast_format_slin;
1183
1184 len = samples * 2;
1185 if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
1186 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" , len);
1187 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
1188 }
1189 res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
1190 if (res > 0) {
1191 f.datalen = res;
1192 f.samples = res / 2;
1193 ast_write(chan, &f);
1194 if (res == len) {
1195 return 0;
1196 }
1197 }
1198 return -1;
1199 }
1200
1201 static void *linear_alloc(struct ast_channel *chan, void *params)
1202 {
1203 struct linear_state *ls = params;
1204
1205 if (!params) {
1206 return NULL;
1207 }
1208
1209 /* In this case, params is already malloc'd */
1210 if (ls->allowoverride) {
1211 ast_set_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
1212 } else {
1213 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
1214 }
1215
1216 ls->origwfmt = ao2_bump(ast_channel_writeformat(chan));
1217
1218 if (ast_set_write_format(chan, ast_format_slin)) {
1219 ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", ast_channel_name(chan));
1220 ao2_cleanup(ls->origwfmt);
1221 ast_free(ls);
1222 ls = params = NULL;
1223 }
1224
1225 return params;
1226 }
1227
1228 static struct ast_generator linearstream =
1229 {
1230 .alloc = linear_alloc,
1231 .release = linear_release,
1232 .generate = linear_generator,
1233 };
1234
1235 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
1236 {
1237 struct linear_state *lin;
1238 char tmpf[256];
1239 int autoclose = 0;
1240
1241 if (fd < 0) {
1242 if (ast_strlen_zero(filename)) {
1243 return -1;
1244 }
1245
1246 autoclose = 1;
1247
1248 if (filename[0] == '/') {
1249 ast_copy_string(tmpf, filename, sizeof(tmpf));
1250 } else {
1251 snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", ast_config_AST_DATA_DIR, "sounds", filename);
1252 }
1253
1254 fd = open(tmpf, O_RDONLY);
1255 if (fd < 0) {
1256 ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
1257 return -1;
1258 }
1259 }
1260
1261 lin = ast_calloc(1, sizeof(*lin));
1262 if (!lin) {
1263 if (autoclose) {
1264 close(fd);
1265 }
1266
1267 return -1;
1268 }
1269
1270 lin->fd = fd;
1271 lin->allowoverride = allowoverride;
1272 lin->autoclose = autoclose;
1273
1274 return ast_activate_generator(chan, &linearstream, lin);
1275 }
1276
1277 static int control_streamfile(struct ast_channel *chan,
1278 const char *file,
1279 const char *fwd,
1280 const char *rev,
1281 const char *stop,
1282 const char *suspend,
1283 const char *restart,
1284 int skipms,
1285 long *offsetms,
1286 const char *lang,
1287 ast_waitstream_fr_cb cb)
1288 {
1289 char *file_copy = ast_strdupa(file);
1290 char *breaks = NULL;
1291 char *end = NULL;
1292 int blen = 2;
1293 int res;
1294 long pause_restart_point = 0;
1295 long offset = 0;
1296 struct ast_silence_generator *silgen = NULL;
1297
1298 if (!file) {
1299 return -1;
1300 }
1301 if (offsetms) {
1302 offset = *offsetms * 8; /* XXX Assumes 8kHz */
1303 }
1304 if (lang == NULL) {
1305 lang = ast_channel_language(chan);
1306 }
1307
1308 if (stop) {
1309 blen += strlen(stop);
1310 }
1311 if (suspend) {
1312 blen += strlen(suspend);
1313 }
1314 if (restart) {
1315 blen += strlen(restart);
1316 }
1317
1318 if (blen > 2) {
1319 breaks = ast_alloca(blen + 1);
1320 breaks[0] = '\0';
1321 if (stop) {
1322 strcat(breaks, stop);
1323 }
1324 if (suspend) {
1325 strcat(breaks, suspend);
1326 }
1327 if (restart) {
1328 strcat(breaks, restart);
1329 }
1330 }
1331
1332 if ((end = strchr(file_copy, ':'))) {
1333 if (!strcasecmp(end, ":end")) {
1334 *end = '\0';
1335 end++;
1336 } else {
1337 end = NULL;
1338 }
1339 }
1340
1341 for (;;) {
1342 ast_stopstream(chan);
1343 res = ast_streamfile(chan, file_copy, lang);
1344 if (!res) {
1345 if (pause_restart_point) {
1346 ast_seekstream(ast_channel_stream(chan), pause_restart_point, SEEK_SET);
1347 pause_restart_point = 0;
1348 }
1349 else if (end || offset < 0) {
1350 if (offset == -8) {
1351 offset = 0;
1352 }
1353 ast_verb(3, "ControlPlayback seek to offset %ld from end\n", offset);
1354
1355 ast_seekstream(ast_channel_stream(chan), offset, SEEK_END);
1356 end = NULL;
1357 offset = 0;
1358 } else if (offset) {
1359 ast_verb(3, "ControlPlayback seek to offset %ld\n", offset);
1360 ast_seekstream(ast_channel_stream(chan), offset, SEEK_SET);
1361 offset = 0;
1362 }
1363 if (cb) {
1364 res = ast_waitstream_fr_w_cb(chan, breaks, fwd, rev, skipms, cb);
1365 } else {
1366 res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
1367 }
1368 }
1369
1370 if (res < 1) {
1371 break;
1372 }
1373
1374 /* We go at next loop if we got the restart char */
1375 if ((restart && strchr(restart, res)) || res == AST_CONTROL_STREAM_RESTART) {
1376 ast_debug(1, "we'll restart the stream here at next loop\n");
1377 pause_restart_point = 0;
1378 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1379 "Control: %s\r\n",
1380 ast_channel_name(chan),
1381 "Restart");
1382 continue;
1383 }
1384
1385 if ((suspend && strchr(suspend, res)) || res == AST_CONTROL_STREAM_SUSPEND) {
1386 pause_restart_point = ast_tellstream(ast_channel_stream(chan));
1387
1388 if (ast_opt_transmit_silence) {
1389 silgen = ast_channel_start_silence_generator(chan);
1390 }
1391 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1392 "Control: %s\r\n",
1393 ast_channel_name(chan),
1394 "Pause");
1395 for (;;) {
1396 ast_stopstream(chan);
1397 if (!(res = ast_waitfordigit(chan, 1000))) {
1398 continue;
1399 } else if (res == -1 || (suspend && strchr(suspend, res)) || (stop && strchr(stop, res))
1400 || res == AST_CONTROL_STREAM_SUSPEND || res == AST_CONTROL_STREAM_STOP) {
1401 break;
1402 }
1403 }
1404 if (silgen) {
1405 ast_channel_stop_silence_generator(chan, silgen);
1406 silgen = NULL;
1407 }
1408
1409 if ((suspend && (res == *suspend)) || res == AST_CONTROL_STREAM_SUSPEND) {
1410 res = 0;
1411 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1412 "Control: %s\r\n",
1413 ast_channel_name(chan),
1414 "Unpause");
1415 continue;
1416 }
1417 }
1418
1419 if (res == -1) {
1420 break;
1421 }
1422
1423 /* if we get one of our stop chars, return it to the calling function */
1424 if ((stop && strchr(stop, res)) || res == AST_CONTROL_STREAM_STOP) {
1425 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1426 "Control: %s\r\n",
1427 ast_channel_name(chan),
1428 "Stop");
1429 break;
1430 }
1431 }
1432
1433 if (pause_restart_point) {
1434 offset = pause_restart_point;
1435 } else {
1436 if (ast_channel_stream(chan)) {
1437 offset = ast_tellstream(ast_channel_stream(chan));
1438 } else {
1439 offset = -8; /* indicate end of file */
1440 }
1441 }
1442
1443 if (offsetms) {
1444 *offsetms = offset / 8; /* samples --> ms ... XXX Assumes 8 kHz */
1445 }
1446
1447 ast_stopstream(chan);
1448
1449 return res;
1450 }
1451
1452 int ast_control_streamfile_w_cb(struct ast_channel *chan,
1453 const char *file,
1454 const char *fwd,
1455 const char *rev,
1456 const char *stop,
1457 const char *suspend,
1458 const char *restart,
1459 int skipms,
1460 long *offsetms,
1461 ast_waitstream_fr_cb cb)
1462 {
1463 return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, NULL, cb);
1464 }
1465
1466 int ast_control_streamfile(struct ast_channel *chan, const char *file,
1467 const char *fwd, const char *rev,
1468 const char *stop, const char *suspend,
1469 const char *restart, int skipms, long *offsetms)
1470 {
1471 return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, NULL, NULL);
1472 }
1473
1474 int ast_control_streamfile_lang(struct ast_channel *chan, const char *file,
1475 const char *fwd, const char *rev, const char *stop, const char *suspend,
1476 const char *restart, int skipms, const char *lang, long *offsetms)
1477 {
1478 return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, lang, NULL);
1479 }
1480
1481 enum control_tone_frame_response_result {
1482 CONTROL_TONE_RESPONSE_FAILED = -1,
1483 CONTROL_TONE_RESPONSE_NORMAL = 0,
1484 CONTROL_TONE_RESPONSE_FINISHED = 1,
1485 };
1486
1487 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)
1488 {
1489 switch (fr->subclass.integer) {
1490 case AST_CONTROL_STREAM_STOP:
1491 ast_playtones_stop(chan);
1492 return CONTROL_TONE_RESPONSE_FINISHED;
1493 case AST_CONTROL_STREAM_SUSPEND:
1494 if (*paused) {
1495 *paused = 0;
1496 if (ast_playtones_start(chan, 0, ts ? ts->data : tone, 0)) {
1497 return CONTROL_TONE_RESPONSE_FAILED;
1498 }
1499 } else {
1500 *paused = 1;
1501 ast_playtones_stop(chan);
1502 }
1503 return CONTROL_TONE_RESPONSE_NORMAL;
1504 case AST_CONTROL_STREAM_RESTART:
1505 ast_playtones_stop(chan);
1506 if (ast_playtones_start(chan, 0, ts ? ts->data : tone, 0)) {
1507 return CONTROL_TONE_RESPONSE_FAILED;
1508 }
1509 return CONTROL_TONE_RESPONSE_NORMAL;
1510 case AST_CONTROL_STREAM_REVERSE:
1511 ast_log(LOG_NOTICE, "Media control operation 'reverse' not supported for media type 'tone'\n");
1512 return CONTROL_TONE_RESPONSE_NORMAL;
1513 case AST_CONTROL_STREAM_FORWARD:
1514 ast_log(LOG_NOTICE, "Media control operation 'forward' not supported for media type 'tone'\n");
1515 return CONTROL_TONE_RESPONSE_NORMAL;
1516 case AST_CONTROL_HANGUP:
1517 case AST_CONTROL_BUSY:
1518 case AST_CONTROL_CONGESTION:
1519 return CONTROL_TONE_RESPONSE_FINISHED;
1520 }
1521
1522 return CONTROL_TONE_RESPONSE_NORMAL;
1523 }
1524
1525 static int parse_tone_uri(char *tone_parser,
1526 const char **tone_indication,
1527 const char **tone_zone)
1528 {
1529 *tone_indication = strsep(&tone_parser, ";");
1530
1531 if (ast_strlen_zero(tone_parser)) {
1532 /* Only the indication is included */
1533 return 0;
1534 }
1535
1536 if (!(strncmp(tone_parser, "tonezone=", 9))) {
1537 *tone_zone = tone_parser + 9;
1538 } else {
1539 ast_log(LOG_ERROR, "Unexpected Tone URI component: %s\n", tone_parser);
1540 return -1;
1541 }
1542
1543 return 0;
1544 }
1545
1546 int ast_control_tone(struct ast_channel *chan, const char *tone)
1547 {
1548 struct ast_tone_zone *zone = NULL;
1549 struct ast_tone_zone_sound *ts;
1550 int paused = 0;
1551 int res = 0;
1552
1553 const char *tone_indication = NULL;
1554 const char *tone_zone = NULL;
1555 char *tone_uri_parser;
1556
1557 if (ast_strlen_zero(tone)) {
1558 return -1;
1559 }
1560
1561 tone_uri_parser = ast_strdupa(tone);
1562
1563 if (parse_tone_uri(tone_uri_parser, &tone_indication, &tone_zone)) {
1564 return -1;
1565 }
1566
1567 if (tone_zone) {
1568 zone = ast_get_indication_zone(tone_zone);
1569 }
1570
1571 ts = ast_get_indication_tone(zone ? zone : ast_channel_zone(chan), tone_indication);
1572
1573 if (ast_playtones_start(chan, 0, ts ? ts->data : tone_indication, 0)) {
1574 res = -1;
1575 }
1576
1577 while (!res) {
1578 struct ast_frame *fr;
1579
1580 if (ast_waitfor(chan, -1) < 0) {
1581 res = -1;
1582 break;
1583 }
1584
1585 fr = ast_read_noaudio(chan);
1586
1587 if (!fr) {
1588 res = -1;
1589 break;
1590 }
1591
1592 if (fr->frametype != AST_FRAME_CONTROL) {
1593 continue;
1594 }
1595
1596 res = control_tone_frame_response(chan, fr, ts, tone_indication, &paused);
1597 if (res == CONTROL_TONE_RESPONSE_FINISHED) {
1598 res = 0;
1599 break;
1600 } else if (res == CONTROL_TONE_RESPONSE_FAILED) {
1601 res = -1;
1602 break;
1603 }
1604 }
1605
1606 if (ts) {
1607 ast_tone_zone_sound_unref(ts);
1608 }
1609
1610 if (zone) {
1611 ast_tone_zone_unref(zone);
1612 }
1613
1614 return res;
1615 }
1616
1617 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
1618 {
1619 int d = 0;
1620
1621 if ((d = ast_streamfile(chan, fn, ast_channel_language(chan)))) {
1622 return d;
1623 }
1624
1625 d = ast_waitstream(chan, AST_DIGIT_ANY);
1626
1627 ast_stopstream(chan);
1628
1629 return d;
1630 }
1631
1632 /*!
1633 * \brief Construct a silence frame of the same duration as \a orig.
1634 *
1635 * The \a orig frame must be \ref ast_format_slin.
1636 *
1637 * \param orig Frame as basis for silence to generate.
1638 * \return New frame of silence; free with ast_frfree().
1639 * \retval NULL on error.
1640 */
1641 static struct ast_frame *make_silence(const struct ast_frame *orig)
1642 {
1643 struct ast_frame *silence;
1644 size_t size;
1645 size_t datalen;
1646 size_t samples = 0;
1647
1648 if (!orig) {
1649 return NULL;
1650 }
1651 do {
1652 if (ast_format_cmp(orig->subclass.format, ast_format_slin) == AST_FORMAT_CMP_NOT_EQUAL) {
1653 ast_log(LOG_WARNING, "Attempting to silence non-slin frame\n");
1654 return NULL;
1655 }
1656
1657 samples += orig->samples;
1658
1659 orig = AST_LIST_NEXT(orig, frame_list);
1660 } while (orig);
1661
1662 ast_verb(4, "Silencing %zu samples\n", samples);
1663
1664
1665 datalen = sizeof(short) * samples;
1666 size = sizeof(*silence) + datalen;
1667 silence = ast_calloc(1, size);
1668 if (!silence) {
1669 return NULL;
1670 }
1671
1672 silence->mallocd = AST_MALLOCD_HDR;
1673 silence->frametype = AST_FRAME_VOICE;
1674 silence->data.ptr = (void *)(silence + 1);
1675 silence->samples = samples;
1676 silence->datalen = datalen;
1677
1678 silence->subclass.format = ao2_bump(ast_format_slin);
1679
1680 return silence;
1681 }
1682
1683 /*!
1684 * \brief Sets a channel's read format to \ref ast_format_slin, recording
1685 * its original format.
1686 *
1687 * \param chan Channel to modify.
1688 * \param[out] orig_format Output variable to store channel's original read
1689 * format.
1690 * \return 0 on success.
1691 * \return -1 on error.
1692 */
1693 static int set_read_to_slin(struct ast_channel *chan, struct ast_format **orig_format)
1694 {
1695 if (!chan || !orig_format) {
1696 return -1;
1697 }
1698 *orig_format = ao2_bump(ast_channel_readformat(chan));
1699 return ast_set_read_format(chan, ast_format_slin);
1700 }
1701
1702 static int global_silence_threshold = 128;
1703 static int global_maxsilence = 0;
1704
1705 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
1706 * \param chan Channel to playback to/record from.
1707 * \param playfile Filename of sound to play before recording begins.
1708 * \param recordfile Filename to record to.
1709 * \param maxtime Maximum length of recording (in seconds).
1710 * \param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
1711 * \param duration Where to store actual length of the recorded message (in milliseconds).
1712 * \param sound_duration Where to store the length of the recorded message (in milliseconds), minus any silence
1713 * \param beep Whether to play a beep before starting to record.
1714 * \param silencethreshold
1715 * \param maxsilence Length of silence that will end a recording (in milliseconds).
1716 * \param path Optional filesystem path to unlock.
1717 * \param prepend If true, prepend the recorded audio to an existing file and follow prepend mode recording rules
1718 * \param acceptdtmf DTMF digits that will end the recording.
1719 * \param canceldtmf DTMF digits that will cancel the recording.
1720 * \param skip_confirmation_sound If true, don't play auth-thankyou at end. Nice for custom recording prompts in apps.
1721 * \param if_exists
1722 *
1723 * \retval -1 failure or hangup
1724 * \retval 'S' Recording ended from silence timeout
1725 * \retval 't' Recording ended from the message exceeding the maximum duration, or via DTMF in prepend mode
1726 * \retval dtmfchar Recording ended via the return value's DTMF character for either cancel or accept.
1727 */
1728 static int __ast_play_and_record(struct ast_channel *chan, const char *playfile,
1729 const char *recordfile, int maxtime, const char *fmt, int *duration,
1730 int *sound_duration, int beep, int silencethreshold, int maxsilence,
1731 const char *path, int prepend, const char *acceptdtmf, const char *canceldtmf,
1732 int skip_confirmation_sound, enum ast_record_if_exists if_exists)
1733 {
1734 int d = 0;
1735 char *fmts;
1736 char comment[256];
1737 int x, fmtcnt = 1, res = -1, outmsg = 0;
1738 struct ast_filestream *others[AST_MAX_FORMATS];
1739 const char *sfmt[AST_MAX_FORMATS];
1740 char *stringp = NULL;
1741 time_t start, end;
1742 struct ast_dsp *sildet = NULL; /* silence detector dsp */
1743 int totalsilence = 0;
1744 int dspsilence = 0;
1745 int olddspsilence = 0;
1746 struct ast_format *rfmt = NULL;
1747 struct ast_silence_generator *silgen = NULL;
1748 char prependfile[PATH_MAX];
1749 int ioflags; /* IO flags for writing output file */
1750 SCOPE_ENTER(3, "%s: play: '%s' record: '%s' path: '%s' prepend: %d\n",
1751 ast_channel_name(chan), playfile, recordfile, path, prepend);
1752
1753 ioflags = O_CREAT|O_WRONLY;
1754
1755 switch (if_exists) {
1756 case AST_RECORD_IF_EXISTS_FAIL:
1757 ioflags |= O_EXCL;
1758 break;
1759 case AST_RECORD_IF_EXISTS_OVERWRITE:
1760 ioflags |= O_TRUNC;
1761 break;
1762 case AST_RECORD_IF_EXISTS_APPEND:
1763 ioflags |= O_APPEND;
1764 break;
1765 case AST_RECORD_IF_EXISTS_ERROR:
1766 ast_assert(0);
1767 break;
1768 }
1769
1770 if (silencethreshold < 0) {
1771 silencethreshold = global_silence_threshold;
1772 }
1773
1774 if (maxsilence < 0) {
1775 maxsilence = global_maxsilence;
1776 }
1777
1778 /* barf if no pointer passed to store duration in */
1779 if (!duration) {
1780 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
1781 return -1;
1782 }
1783
1784 ast_debug(1, "play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
1785 snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, ast_channel_name(chan));
1786
1787 if (playfile || beep) {
1788 if (!beep) {
1789 ast_trace(-1, "Playing '%s' to '%s'\n", playfile, ast_channel_name(chan));
1790 d = ast_play_and_wait(chan, playfile);
1791 }
1792 if (d > -1) {
1793 ast_trace(-1, "Playing 'beep' to '%s'\n", ast_channel_name(chan));
1794 d = ast_stream_and_wait(chan, "beep", "");
1795 }
1796 if (d < 0) {
1797 SCOPE_EXIT_RTN_VALUE(-1, "Failed to play. RC: %d\n", d);
1798 }
1799 }
1800
1801 if (prepend) {
1802 ast_copy_string(prependfile, recordfile, sizeof(prependfile));
1803 strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
1804 ast_trace(-1, "Prepending to '%s'\n", prependfile);
1805 }
1806
1807 fmts = ast_strdupa(fmt);
1808
1809 stringp = fmts;
1810 strsep(&stringp, "|");
1811 ast_debug(1, "Recording Formats: sfmts=%s\n", fmts);
1812 sfmt[0] = ast_strdupa(fmts);
1813
1814 while ((fmt = strsep(&stringp, "|"))) {
1815 if (fmtcnt > AST_MAX_FORMATS - 1) {
1816 ast_log(LOG_WARNING, "Please increase AST_MAX_FORMATS in file.h\n");
1817 break;
1818 }
1819 /*
1820 * Storage for 'fmt' is on the stack and held by 'fmts', which is maintained for
1821 * the rest of this function. So okay to not duplicate 'fmt' here, but only keep
1822 * a pointer to it.
1823 */
1824 sfmt[fmtcnt++] = fmt;
1825 }
1826
1827 end = start = time(NULL); /* pre-initialize end to be same as start in case we never get into loop */
1828 for (x = 0; x < fmtcnt; x++) {
1829 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, ioflags, 0, AST_FILE_MODE);
1830 ast_trace(-1, "x=%d, open writing: %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
1831
1832 if (!others[x]) {
1833 break;
1834 }
1835 }
1836
1837 if (path) {
1838 ast_unlock_path(path);
1839 }
1840
1841 if (maxsilence > 0) {
1842 sildet = ast_dsp_new(); /* Create the silence detector */
1843 if (!sildet) {
1844 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
1845 return -1;
1846 }
1847 ast_dsp_set_threshold(sildet, silencethreshold);
1848 res = set_read_to_slin(chan, &rfmt);
1849 if (res < 0) {
1850 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
1851 ast_dsp_free(sildet);
1852 ao2_cleanup(rfmt);
1853 return -1;
1854 }
1855 }
1856
1857 if (!prepend) {
1858 /* Request a video update */
1859 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
1860
1861 if (ast_opt_transmit_silence) {
1862 silgen = ast_channel_start_silence_generator(chan);
1863 }
1864 }
1865
1866 if (x == fmtcnt) {
1867 /* Loop, writing the packets we read to the writer(s), until
1868 * we have reason to stop. */
1869 struct ast_frame *f;
1870 int paused = 0;
1871 int muted = 0;
1872 time_t pause_start = 0;
1873 int paused_secs = 0;
1874 int pausedsilence = 0;
1875
1876 for (;;) {
1877 if (!(res = ast_waitfor(chan, 2000))) {
1878 ast_debug(1, "One waitfor failed, trying another\n");
1879 /* Try one more time in case of masq */
1880 if (!(res = ast_waitfor(chan, 2000))) {
1881 ast_log(LOG_WARNING, "No audio available on %s??\n", ast_channel_name(chan));
1882 res = -1;
1883 }
1884 }
1885
1886 if (res < 0) {
1887 f = NULL;
1888 break;
1889 }
1890 if (!(f = ast_read(chan))) {
1891 break;
1892 }
1893 if (f->frametype == AST_FRAME_VOICE) {
1894 /* write each format */
1895 if (paused) {
1896 /* It's all good */
1897 res = 0;
1898 } else {
1899 struct ast_frame *silence = NULL;
1900 struct ast_frame *orig = f;
1901
1902 if (muted) {
1903 silence = make_silence(orig);
1904 if (!silence) {
1905 ast_log(LOG_WARNING, "Error creating silence\n");
1906 break;
1907 }
1908 f = silence;
1909 }
1910 for (x = 0; x < fmtcnt; x++) {
1911 if (prepend && !others[x]) {
1912 break;
1913 }
1914 res = ast_writestream(others[x], f);
1915 }
1916 ast_frame_dtor(silence);
1917 f = orig;
1918 }
1919
1920 /* Silence Detection */
1921 if (maxsilence > 0) {
1922 dspsilence = 0;
1923 ast_dsp_silence(sildet, f, &dspsilence);
1924 if (olddspsilence > dspsilence) {
1925 totalsilence += olddspsilence;
1926 }
1927 olddspsilence = dspsilence;
1928
1929 if (paused) {
1930 /* record how much silence there was while we are paused */
1931 pausedsilence = dspsilence;
1932 } else if (dspsilence > pausedsilence) {
1933 /* ignore the paused silence */
1934 dspsilence -= pausedsilence;
1935 } else {
1936 /* dspsilence has reset, reset pausedsilence */
1937 pausedsilence = 0;
1938 }
1939
1940 if (dspsilence > maxsilence) {
1941 /* Ended happily with silence */
1942 ast_verb(3, "Recording automatically stopped after a silence of %d seconds\n", dspsilence/1000);
1943 res = 'S';
1944 outmsg = 2;
1945 break;
1946 }
1947 }
1948 /* Exit on any error */
1949 if (res) {
1950 ast_log(LOG_WARNING, "Error writing frame\n");
1951 break;
1952 }
1953 } else if (f->frametype == AST_FRAME_VIDEO) {
1954 /* Write only once */
1955 ast_writestream(others[0], f);
1956 } else if (f->frametype == AST_FRAME_DTMF) {
1957 if (prepend) {
1958 /* stop recording with any digit */
1959 ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
1960 res = 't';
1961 outmsg = 2;
1962 break;
1963 }
1964 if (strchr(acceptdtmf, f->subclass.integer)) {
1965 ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
1966 res = f->subclass.integer;
1967 outmsg = 2;
1968 break;
1969 }
1970 if (strchr(canceldtmf, f->subclass.integer)) {
1971 ast_verb(3, "User canceled message by pressing %c\n", f->subclass.integer);
1972 res = f->subclass.integer;
1973 outmsg = 0;
1974 break;
1975 }
1976 } else if (f->frametype == AST_FRAME_CONTROL) {
1977 if (f->subclass.integer == AST_CONTROL_RECORD_CANCEL) {
1978 ast_verb(3, "Message canceled by control\n");
1979 outmsg = 0; /* cancels the recording */
1980 res = 0;
1981 break;
1982 } else if (f->subclass.integer == AST_CONTROL_RECORD_STOP) {
1983 ast_verb(3, "Message ended by control\n");
1984 res = 0;
1985 break;
1986 } else if (f->subclass.integer == AST_CONTROL_RECORD_SUSPEND) {
1987 paused = !paused;
1988 ast_verb(3, "Message %spaused by control\n",
1989 paused ? "" : "un");
1990 if (paused) {
1991 pause_start = time(NULL);
1992 } else {
1993 paused_secs += time(NULL) - pause_start;
1994 }
1995 } else if (f->subclass.integer == AST_CONTROL_RECORD_MUTE) {
1996 muted = !muted;
1997 ast_verb(3, "Message %smuted by control\n",
1998 muted ? "" : "un");
1999 /* We can only silence slin frames, so
2000 * set the mode, if we haven't already
2001 * for sildet
2002 */
2003 if (muted && !rfmt) {
2004 ast_verb(3, "Setting read format to linear mode\n");
2005 res = set_read_to_slin(chan, &rfmt);
2006 if (res < 0) {
2007 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
2008 break;
2009 }
2010 }
2011 }
2012 }
2013 if (maxtime && !paused) {
2014 end = time(NULL);
2015 if (maxtime < (end - start - paused_secs)) {
2016 ast_verb(3, "Took too long, cutting it short...\n");
2017 res = 't';
2018 outmsg = 2;
2019 break;
2020 }
2021 }
2022 ast_frfree(f);
2023 }
2024 if (!f) {
2025 ast_verb(3, "User hung up\n");
2026 res = -1;
2027 outmsg = 1;
2028 } else {
2029 ast_frfree(f);
2030 }
2031 } else {
2032 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
2033 }
2034
2035 if (!prepend) {
2036 if (silgen) {
2037 ast_channel_stop_silence_generator(chan, silgen);
2038 }
2039 }
2040
2041 /*!\note
2042 * Instead of asking how much time passed (end - start), calculate the number
2043 * of seconds of audio which actually went into the file. This fixes a
2044 * problem where audio is stopped up on the network and never gets to us.
2045 *
2046 * Note that we still want to use the number of seconds passed for the max
2047 * message, otherwise we could get a situation where this stream is never
2048 * closed (which would create a resource leak).
2049 */
2050 *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
2051 if (sound_duration) {
2052 *sound_duration = *duration;
2053 }
2054
2055 if (!prepend) {
2056 /* Reduce duration by a total silence amount */
2057 if (olddspsilence <= dspsilence) {
2058 totalsilence += dspsilence;
2059 }
2060
2061 if (sound_duration) {
2062 if (totalsilence > 0) {
2063 *sound_duration -= (totalsilence - 200) / 1000;
2064 }
2065 if (*sound_duration < 0) {
2066 *sound_duration = 0;
2067 }
2068 }
2069
2070 if (dspsilence > 0) {
2071 *duration -= (dspsilence - 200) / 1000;
2072 }
2073
2074 if (*duration < 0) {
2075 *duration = 0;
2076 }
2077
2078 for (x = 0; x < fmtcnt; x++) {
2079 if (!others[x]) {
2080 break;
2081 }
2082 /*!\note
2083 * If we ended with silence, trim all but the first 200ms of silence
2084 * off the recording. However, if we ended with '#', we don't want
2085 * to trim ANY part of the recording.
2086 */
2087 if (res > 0 && dspsilence) {
2088 /* rewind only the trailing silence */
2089 ast_stream_rewind(others[x], dspsilence - 200);
2090 }
2091 ast_truncstream(others[x]);
2092 ast_closestream(others[x]);
2093 }
2094 } else if (prepend && outmsg) {
2095 struct ast_filestream *realfiles[AST_MAX_FORMATS];
2096 struct ast_frame *fr;
2097
2098 for (x = 0; x < fmtcnt; x++) {
2099 snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
2100 realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
2101 if (!others[x]) {
2102 break;
2103 }
2104 if (!realfiles[x]) {
2105 ast_closestream(others[x]);
2106 continue;
2107 }
2108 /*!\note Same logic as above. */
2109 if (dspsilence) {
2110 ast_stream_rewind(others[x], dspsilence - 200);
2111 }
2112 ast_truncstream(others[x]);
2113 /* add the original file too */
2114 while ((fr = ast_readframe(realfiles[x]))) {
2115 ast_writestream(others[x], fr);
2116 ast_frfree(fr);
2117 }
2118 ast_closestream(others[x]);
2119 ast_closestream(realfiles[x]);
2120 ast_filerename(prependfile, recordfile, sfmt[x]);
2121 ast_trace(-1, "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
2122 ast_trace(-1, "Deleting the prepend file %s.%s\n", recordfile, sfmt[x]);
2123 ast_filedelete(prependfile, sfmt[x]);
2124 }
2125 } else {
2126 for (x = 0; x < fmtcnt; x++) {
2127 if (!others[x]) {
2128 break;
2129 }
2130 ast_closestream(others[x]);
2131 }
2132 }
2133
2134 if (rfmt && ast_set_read_format(chan, rfmt)) {
2135 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_format_get_name(rfmt), ast_channel_name(chan));
2136 }
2137 ao2_cleanup(rfmt);
2138 if ((outmsg == 2) && (!skip_confirmation_sound)) {
2139 ast_stream_and_wait(chan, "auth-thankyou", "");
2140 }
2141 if (sildet) {
2142 ast_dsp_free(sildet);
2143 }
2144 SCOPE_EXIT_RTN_VALUE(res, "Done. RC: %d\n", res);
2145 }
2146
2147 static const char default_acceptdtmf[] = "#";
2148 static const char default_canceldtmf[] = "";
2149
2150 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)
2151 {
2152 return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, beep, silencethreshold, maxsilence, path, 0, S_OR(acceptdtmf, ""), S_OR(canceldtmf, default_canceldtmf), skip_confirmation_sound, if_exists);
2153 }
2154
2155 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)
2156 {
2157 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);
2158 }
2159
2160 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)
2161 {
2162 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);
2163 }
2164
2165 /* Channel group core functions */
2166
2167 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
2168 {
2169 int res = 0;
2170 char tmp[256];
2171 char *grp = NULL, *cat = NULL;
2172
2173 if (!ast_strlen_zero(data)) {
2174 ast_copy_string(tmp, data, sizeof(tmp));
2175 grp = tmp;
2176 if ((cat = strchr(tmp, '@'))) {
2177 *cat++ = '\0';
2178 }
2179 }
2180
2181 if (!ast_strlen_zero(grp)) {
2182 ast_copy_string(group, grp, group_max);
2183 } else {
2184 *group = '\0';
2185 }
2186
2187 if (!ast_strlen_zero(cat)) {
2188 ast_copy_string(category, cat, category_max);
2189 }
2190
2191 return res;
2192 }
2193
2194 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
2195 {
2196 int res = 0;
2197 char group[80] = "", category[80] = "";
2198 struct ast_group_info *gi = NULL;
2199 size_t len = 0;
2200
2201 if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
2202 return -1;
2203 }
2204
2205 /* Calculate memory we will need if this is new */
2206 len = sizeof(*gi) + strlen(group) + 1;
2207 if (!ast_strlen_zero(category)) {
2208 len += strlen(category) + 1;
2209 }
2210
2211 AST_RWLIST_WRLOCK(&groups);
2212 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
2213 if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
2214 AST_RWLIST_REMOVE_CURRENT(group_list);
2215 ast_free(gi);
2216 break;
2217 }
2218 }
2219 AST_RWLIST_TRAVERSE_SAFE_END;
2220
2221 if (ast_strlen_zero(group)) {
2222 /* Enable unsetting the group */
2223 } else if ((gi = ast_calloc(1, len))) {
2224 gi->chan = chan;
2225 gi->group = (char *) gi + sizeof(*gi);
2226 strcpy(gi->group, group);
2227 if (!ast_strlen_zero(category)) {
2228 gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
2229 strcpy(gi->category, category);
2230 }
2231 AST_RWLIST_INSERT_TAIL(&groups, gi, group_list);
2232 } else {
2233 res = -1;
2234 }
2235
2236 AST_RWLIST_UNLOCK(&groups);
2237
2238 return res;
2239 }
2240
2241 int ast_app_group_get_count(const char *group, const char *category)
2242 {
2243 struct ast_group_info *gi = NULL;
2244 int count = 0;
2245
2246 if (ast_strlen_zero(group)) {
2247 return 0;
2248 }
2249
2250 AST_RWLIST_RDLOCK(&groups);
2251 AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
2252 if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
2253 count++;
2254 }
2255 }
2256 AST_RWLIST_UNLOCK(&groups);
2257
2258 return count;
2259 }
2260
2261 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
2262 {
2263 struct ast_group_info *gi = NULL;
2264 regex_t regexbuf_group;
2265 regex_t regexbuf_category;
2266 int count = 0;
2267
2268 if (ast_strlen_zero(groupmatch)) {
2269 ast_log(LOG_NOTICE, "groupmatch empty\n");
2270 return 0;
2271 }
2272
2273 /* if regex compilation fails, return zero matches */
2274 if (regcomp(&regexbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) {
2275 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch);
2276 return 0;
2277 }
2278
2279 if (!ast_strlen_zero(category) && regcomp(&regexbuf_category, category, REG_EXTENDED | REG_NOSUB)) {
2280 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", category);
2281 regfree(&regexbuf_group);
2282 return 0;
2283 }
2284
2285 AST_RWLIST_RDLOCK(&groups);
2286 AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
2287 if (!regexec(&regexbuf_group, gi->group, 0, NULL, 0) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !regexec(&regexbuf_category, gi->category, 0, NULL, 0)))) {
2288 count++;
2289 }
2290 }
2291 AST_RWLIST_UNLOCK(&groups);
2292
2293 regfree(&regexbuf_group);
2294 if (!ast_strlen_zero(category)) {
2295 regfree(&regexbuf_category);
2296 }
2297
2298 return count;
2299 }
2300
2301 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
2302 {
2303 struct ast_group_info *gi = NULL;
2304
2305 AST_RWLIST_WRLOCK(&groups);
2306 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
2307 if (gi->chan == old) {
2308 gi->chan = new;
2309 } else if (gi->chan == new) {
2310 AST_RWLIST_REMOVE_CURRENT(group_list);
2311 ast_free(gi);
2312 }
2313 }
2314 AST_RWLIST_TRAVERSE_SAFE_END;
2315 AST_RWLIST_UNLOCK(&groups);
2316
2317 return 0;
2318 }
2319
2320 int ast_app_group_discard(struct ast_channel *chan)
2321 {
2322 struct ast_group_info *gi = NULL;
2323
2324 AST_RWLIST_WRLOCK(&groups);
2325 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
2326 if (gi->chan == chan) {
2327 AST_RWLIST_REMOVE_CURRENT(group_list);
2328 ast_free(gi);
2329 }
2330 }
2331 AST_RWLIST_TRAVERSE_SAFE_END;
2332 AST_RWLIST_UNLOCK(&groups);
2333
2334 return 0;
2335 }
2336
2337 int ast_app_group_list_wrlock(void)
2338 {
2339 return AST_RWLIST_WRLOCK(&groups);
2340 }
2341
2342 int ast_app_group_list_rdlock(void)
2343 {
2344 return AST_RWLIST_RDLOCK(&groups);
2345 }
2346
2347 struct ast_group_info *ast_app_group_list_head(void)
2348 {
2349 return AST_RWLIST_FIRST(&groups);
2350 }
2351
2352 int ast_app_group_list_unlock(void)
2353 {
2354 return AST_RWLIST_UNLOCK(&groups);
2355 }
2356
2357 unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen)
2358 {
2359 int argc;
2360 char *scan, *wasdelim = NULL;
2361 int paren = 0, quote = 0, bracket = 0;
2362
2363 if (!array || !arraylen) {
2364 return 0;
2365 }
2366
2367 memset(array, 0, arraylen * sizeof(*array));
2368
2369 if (!buf) {
2370 return 0;
2371 }
2372
2373 scan = buf;
2374
2375 for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
2376 array[argc] = scan;
2377 for (; *scan; scan++) {
2378 if (*scan == '(') {
2379 paren++;
2380 } else if (*scan == ')') {
2381 if (paren) {
2382 paren--;
2383 }
2384 } else if (*scan == '[') {
2385 bracket++;
2386 } else if (*scan == ']') {
2387 if (bracket) {
2388 bracket--;
2389 }
2390 } else if (*scan == '"' && delim != '"') {
2391 quote = quote ? 0 : 1;
2392 if (remove_chars) {
2393 /* Remove quote character from argument */
2394 memmove(scan, scan + 1, strlen(scan));
2395 scan--;
2396 }
2397 } else if (*scan == '\\') {
2398 if (remove_chars) {
2399 /* Literal character, don't parse */
2400 memmove(scan, scan + 1, strlen(scan));
2401 } else {
2402 scan++;
2403 }
2404 } else if ((*scan == delim) && !paren && !quote && !bracket) {
2405 wasdelim = scan;
2406 *scan++ = '\0';
2407 break;
2408 }
2409 }
2410 }
2411
2412 /* If the last character in the original string was the delimiter, then
2413 * there is one additional argument. */
2414 if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
2415 array[argc++] = scan;
2416 }
2417
2418 return argc;
2419 }
2420
2421 static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
2422 {
2423 char *s;
2424 char *fs;
2425 int res;
2426 int fd;
2427 int lp = strlen(path);
2428 time_t start;
2429
2430 s = ast_alloca(lp + 10);
2431 fs = ast_alloca(lp + 20);
2432
2433 snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, (unsigned long)ast_random());
2434 fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
2435 if (fd < 0) {
2436 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
2437 return AST_LOCK_PATH_NOT_FOUND;
2438 }
2439 close(fd);
2440
2441 snprintf(s, strlen(path) + 9, "%s/.lock", path);
2442 start = time(NULL);
2443 while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
2444 sched_yield();
2445 }
2446
2447 unlink(fs);
2448
2449 if (res) {
2450 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
2451 return AST_LOCK_TIMEOUT;
2452 } else {
2453 ast_debug(1, "Locked path '%s'\n", path);
2454 return AST_LOCK_SUCCESS;
2455 }
2456 }
2457
2458 static int ast_unlock_path_lockfile(const char *path)
2459 {
2460 char *s;
2461 int res;
2462
2463 s = ast_alloca(strlen(path) + 10);
2464
2465 snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
2466
2467 if ((res = unlink(s))) {
2468 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
2469 } else {
2470 ast_debug(1, "Unlocked path '%s'\n", path);
2471 }
2472
2473 return res;
2474 }
2475
2476 struct path_lock {
2477 AST_LIST_ENTRY(path_lock) le;
2478 int fd;
2479 char *path;
2480 };
2481
2482 static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
2483
2484 static void path_lock_destroy(struct path_lock *obj)
2485 {
2486 if (obj->fd >= 0) {
2487 close(obj->fd);
2488 }
2489 if (obj->path) {
2490 ast_free(obj->path);
2491 }
2492 ast_free(obj);
2493 }
2494
2495 static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
2496 {
2497 char *fs;
2498 int res;
2499 int fd;
2500 time_t start;
2501 struct path_lock *pl;
2502 struct stat st, ost;
2503
2504 fs = ast_alloca(strlen(path) + 20);
2505
2506 snprintf(fs, strlen(path) + 19, "%s/lock", path);
2507 if (lstat(fs, &st) == 0) {
2508 if ((st.st_mode & S_IFMT) == S_IFLNK) {
2509 ast_log(LOG_WARNING, "Unable to create lock file "
2510 "'%s': it's already a symbolic link\n",
2511 fs);
2512 return AST_LOCK_FAILURE;
2513 }
2514 if (st.st_nlink > 1) {
2515 ast_log(LOG_WARNING, "Unable to create lock file "
2516 "'%s': %u hard links exist\n",
2517 fs, (unsigned int) st.st_nlink);
2518 return AST_LOCK_FAILURE;
2519 }
2520 }
2521 if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
2522 ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
2523 fs, strerror(errno));
2524 return AST_LOCK_PATH_NOT_FOUND;
2525 }
2526 if (!(pl = ast_calloc(1, sizeof(*pl)))) {
2527 /* We don't unlink the lock file here, on the possibility that
2528 * someone else created it - better to leave a little mess
2529 * than create a big one by destroying someone else's lock
2530 * and causing something to be corrupted.
2531 */
2532 close(fd);
2533 return AST_LOCK_FAILURE;
2534 }
2535 pl->fd = fd;
2536 pl->path = ast_strdup(path);
2537
2538 time(&start);
2539 while (
2540 #ifdef SOLARIS
2541 ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
2542 #else
2543 ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
2544 #endif
2545 (errno == EWOULDBLOCK) &&
2546 (time(NULL) - start < 5))
2547 usleep(1000);
2548 if (res) {
2549 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
2550 path, strerror(errno));
2551 /* No unlinking of lock done, since we tried and failed to
2552 * flock() it.
2553 */
2554 path_lock_destroy(pl);
2555 return AST_LOCK_TIMEOUT;
2556 }
2557
2558 /* Check for the race where the file is recreated or deleted out from
2559 * underneath us.
2560 */
2561 if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
2562 st.st_dev != ost.st_dev &&
2563 st.st_ino != ost.st_ino) {
2564 ast_log(LOG_WARNING, "Unable to create lock file '%s': "
2565 "file changed underneath us\n", fs);
2566 path_lock_destroy(pl);
2567 return AST_LOCK_FAILURE;
2568 }
2569
2570 /* Success: file created, flocked, and is the one we started with */
2571 AST_LIST_LOCK(&path_lock_list);
2572 AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
2573 AST_LIST_UNLOCK(&path_lock_list);
2574
2575 ast_debug(1, "Locked path '%s'\n", path);
2576
2577 return AST_LOCK_SUCCESS;
2578 }
2579
2580 static int ast_unlock_path_flock(const char *path)
2581 {
2582 char *s;
2583 struct path_lock *p;
2584
2585 s = ast_alloca(strlen(path) + 20);
2586
2587 AST_LIST_LOCK(&path_lock_list);
2588 AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
2589 if (!strcmp(p->path, path)) {
2590 AST_LIST_REMOVE_CURRENT(le);
2591 break;
2592 }
2593 }
2594 AST_LIST_TRAVERSE_SAFE_END;
2595 AST_LIST_UNLOCK(&path_lock_list);
2596
2597 if (p) {
2598 snprintf(s, strlen(path) + 19, "%s/lock", path);
2599 unlink(s);
2600 path_lock_destroy(p);
2601 ast_debug(1, "Unlocked path '%s'\n", path);
2602 } else {
2603 ast_debug(1, "Failed to unlock path '%s': "
2604 "lock not found\n", path);
2605 }
2606
2607 return 0;
2608 }
2609
2610 void ast_set_lock_type(enum AST_LOCK_TYPE type)
2611 {
2612 ast_lock_type = type;
2613 }
2614
2615 enum AST_LOCK_RESULT ast_lock_path(const char *path)
2616 {
2617 enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
2618
2619 switch (ast_lock_type) {
2620 case AST_LOCK_TYPE_LOCKFILE:
2621 r = ast_lock_path_lockfile(path);
2622 break;
2623 case AST_LOCK_TYPE_FLOCK:
2624 r = ast_lock_path_flock(path);
2625 break;
2626 }
2627
2628 return r;
2629 }
2630
2631 int ast_unlock_path(const char *path)
2632 {
2633 int r = 0;
2634
2635 switch (ast_lock_type) {
2636 case AST_LOCK_TYPE_LOCKFILE:
2637 r = ast_unlock_path_lockfile(path);
2638 break;
2639 case AST_LOCK_TYPE_FLOCK:
2640 r = ast_unlock_path_flock(path);
2641 break;
2642 }
2643
2644 return r;
2645 }
2646
2647 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
2648 {
2649 int silencethreshold;
2650 int maxsilence = 0;
2651 int res = 0;
2652 int cmd = 0;
2653 int max_attempts = 3;
2654 int attempts = 0;
2655 int recorded = 0;
2656 int message_exists = 0;
2657 /* Note that urgent and private are for flagging messages as such in the future */
2658
2659 /* barf if no pointer passed to store duration in */
2660 if (!duration) {
2661 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
2662 return -1;
2663 }
2664
2665 cmd = '3'; /* Want to start by recording */
2666
2667 silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
2668
2669 while ((cmd >= 0) && (cmd != 't')) {
2670 switch (cmd) {
2671 case '1':
2672 if (!message_exists) {
2673 /* In this case, 1 is to record a message */
2674 cmd = '3';
2675 break;
2676 } else {
2677 ast_stream_and_wait(chan, "vm-msgsaved", "");
2678 cmd = 't';
2679 return res;
2680 }
2681 case '2':
2682 /* Review */
2683 ast_verb(3, "Reviewing the recording\n");
2684 cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
2685 break;
2686 case '3':
2687 message_exists = 0;
2688 /* Record */
2689 ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
2690 recorded = 1;
2691 if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, NULL, silencethreshold, maxsilence, path)) == -1) {
2692 /* User has hung up, no options to give */
2693 return cmd;
2694 }
2695 if (cmd == '0') {
2696 break;
2697 } else if (cmd == '*') {
2698 break;
2699 } else {
2700 /* If all is well, a message exists */
2701 message_exists = 1;
2702 cmd = 0;
2703 }
2704 break;
2705 case '4':
2706 case '5':
2707 case '6':
2708 case '7':
2709 case '8':
2710 case '9':
2711 case '*':
2712 case '#':
2713 cmd = ast_play_and_wait(chan, "vm-sorry");
2714 break;
2715 default:
2716 if (message_exists) {
2717 cmd = ast_play_and_wait(chan, "vm-review");
2718 } else {
2719 if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
2720 cmd = ast_waitfordigit(chan, 600);
2721 }
2722 }
2723
2724 if (!cmd) {
2725 cmd = ast_waitfordigit(chan, 6000);
2726 }
2727 if (!cmd) {
2728 attempts++;
2729 }
2730 if (attempts > max_attempts) {
2731 cmd = 't';
2732 }
2733 }
2734 }
2735 if (cmd == 't') {
2736 cmd = 0;
2737 }
2738 return cmd;
2739 }
2740
2741 #define RES_UPONE (1 << 16)
2742 #define RES_EXIT (1 << 17)
2743 #define RES_REPEAT (1 << 18)
2744 #define RES_RESTART ((1 << 19) | RES_REPEAT)
2745
2746 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
2747
2748 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
2749 {
2750 int res;
2751 int (*ivr_func)(struct ast_channel *, void *);
2752 char *c;
2753 char *n;
2754
2755 switch (option->action) {
2756 case AST_ACTION_UPONE:
2757 return RES_UPONE;
2758 case AST_ACTION_EXIT:
2759 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
2760 case AST_ACTION_REPEAT:
2761 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
2762 case AST_ACTION_RESTART:
2763 return RES_RESTART ;
2764 case AST_ACTION_NOOP:
2765 return 0;
2766 case AST_ACTION_BACKGROUND:
2767 res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
2768 if (res < 0) {
2769 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
2770 res = 0;
2771 }
2772 return res;
2773 case AST_ACTION_PLAYBACK:
2774 res = ast_stream_and_wait(chan, (char *)option->adata, "");
2775 if (res < 0) {
2776 ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
2777 res = 0;
2778 }
2779 return res;
2780 case AST_ACTION_MENU:
2781 if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
2782 /* Do not pass entry errors back up, treat as though it was an "UPONE" */
2783 res = 0;
2784 }
2785 return res;
2786 case AST_ACTION_WAITOPTION:
2787 if (!(res = ast_waitfordigit(chan, ast_channel_pbx(chan) ? ast_channel_pbx(chan)->rtimeoutms : 10000))) {
2788 return 't';
2789 }
2790 return res;
2791 case AST_ACTION_CALLBACK:
2792 ivr_func = option->adata;
2793 res = ivr_func(chan, cbdata);
2794 return res;
2795 case AST_ACTION_TRANSFER:
2796 res = ast_parseable_goto(chan, option->adata);
2797 return 0;
2798 case AST_ACTION_PLAYLIST:
2799 case AST_ACTION_BACKLIST:
2800 res = 0;
2801 c = ast_strdupa(option->adata);
2802 while ((n = strsep(&c, ";"))) {
2803 if ((res = ast_stream_and_wait(chan, n,
2804 (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
2805 break;
2806 }
2807 }
2808 ast_stopstream(chan);
2809 return res;
2810 default:
2811 ast_log(LOG_NOTICE, "Unknown dispatch function %u, ignoring!\n", option->action);
2812 return 0;
2813 }
2814 return -1;
2815 }
2816
2817 static int option_exists(struct ast_ivr_menu *menu, char *option)
2818 {
2819 int x;
2820 for (x = 0; menu->options[x].option; x++) {
2821 if (!strcasecmp(menu->options[x].option, option)) {
2822 return x;
2823 }
2824 }
2825 return -1;
2826 }
2827
2828 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
2829 {
2830 int x;
2831 for (x = 0; menu->options[x].option; x++) {
2832 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
2833 (menu->options[x].option[strlen(option)])) {
2834 return x;
2835 }
2836 }
2837 return -1;
2838 }
2839
2840 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
2841 {
2842 int res = 0;
2843 int ms;
2844 while (option_matchmore(menu, exten)) {
2845 ms = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->dtimeoutms : 5000;
2846 if (strlen(exten) >= maxexten - 1) {
2847 break;
2848 }
2849 if ((res = ast_waitfordigit(chan, ms)) < 1) {
2850 break;
2851 }
2852 exten[strlen(exten) + 1] = '\0';
2853 exten[strlen(exten)] = res;
2854 }
2855 return res > 0 ? 0 : res;
2856 }
2857
2858 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
2859 {
2860 /* Execute an IVR menu structure */
2861 int res = 0;
2862 int pos = 0;
2863 int retries = 0;
2864 char exten[AST_MAX_EXTENSION] = "s";
2865 if (option_exists(menu, "s") < 0) {
2866 strcpy(exten, "g");
2867 if (option_exists(menu, "g") < 0) {
2868 ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
2869 return -1;
2870 }
2871 }
2872 while (!res) {
2873 while (menu->options[pos].option) {
2874 if (!strcasecmp(menu->options[pos].option, exten)) {
2875 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
2876 ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
2877 if (res < 0) {
2878 break;
2879 } else if (res & RES_UPONE) {
2880 return 0;
2881 } else if (res & RES_EXIT) {
2882 return res;
2883 } else if (res & RES_REPEAT) {
2884 int maxretries = res & 0xffff;
2885 if ((res & RES_RESTART) == RES_RESTART) {
2886 retries = 0;
2887 } else {
2888 retries++;
2889 }
2890 if (!maxretries) {
2891 maxretries = 3;
2892 }
2893 if ((maxretries > 0) && (retries >= maxretries)) {
2894 ast_debug(1, "Max retries %d exceeded\n", maxretries);
2895 return -2;
2896 } else {
2897 if (option_exists(menu, "g") > -1) {
2898 strcpy(exten, "g");
2899 } else if (option_exists(menu, "s") > -1) {
2900 strcpy(exten, "s");
2901 }
2902 }
2903 pos = 0;
2904 continue;
2905 } else if (res && strchr(AST_DIGIT_ANY, res)) {
2906 ast_debug(1, "Got start of extension, %c\n", res);
2907 exten[1] = '\0';
2908 exten[0] = res;
2909 if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
2910 break;
2911 }
2912 if (option_exists(menu, exten) < 0) {
2913 if (option_exists(menu, "i")) {
2914 ast_debug(1, "Invalid extension entered, going to 'i'!\n");
2915 strcpy(exten, "i");
2916 pos = 0;
2917 continue;
2918 } else {
2919 ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
2920 res = -2;
2921 break;
2922 }
2923 } else {
2924 ast_debug(1, "New existing extension: %s\n", exten);
2925 pos = 0;
2926 continue;
2927 }
2928 }
2929 }
2930 pos++;
2931 }
2932 ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
2933 pos = 0;
2934 if (!strcasecmp(exten, "s")) {
2935 strcpy(exten, "g");
2936 } else {
2937 break;
2938 }
2939 }
2940 return res;
2941 }
2942
2943 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
2944 {
2945 int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
2946 /* Hide internal coding */
2947 return res > 0 ? 0 : res;
2948 }
2949
2950 char *ast_read_textfile(const char *filename)
2951 {
2952 int fd, count = 0, res;
2953 char *output = NULL;
2954 struct stat filesize;
2955
2956 if (stat(filename, &filesize) == -1) {
2957 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
2958 return NULL;
2959 }
2960
2961 count = filesize.st_size + 1;
2962
2963 if ((fd = open(filename, O_RDONLY)) < 0) {
2964 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
2965 return NULL;
2966 }
2967
2968 if ((output = ast_malloc(count))) {
2969 res = read(fd, output, count - 1);
2970 if (res == count - 1) {
2971 output[res] = '\0';
2972 } else {
2973 ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
2974 ast_free(output);
2975 output = NULL;
2976 }
2977 }
2978
2979 close(fd);
2980
2981 return output;
2982 }
2983
2984 static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
2985 {
2986 char *s, *arg;
2987 int curarg, res = 0;
2988 unsigned int argloc;
2989 struct ast_flags *flags = _flags;
2990 struct ast_flags64 *flags64 = _flags;
2991
2992 if (flaglen == 32) {
2993 ast_clear_flag(flags, AST_FLAGS_ALL);
2994 } else {
2995 flags64->flags = 0;
2996 }
2997
2998 if (!optstr) {
2999 return 0;
3000 }
3001
3002 s = optstr;
3003 while (*s) {
3004 curarg = *s++ & 0x7f; /* the array (in app.h) has 128 entries */
3005 argloc = options[curarg].arg_index;
3006 if (*s == '(') {
3007 int paren = 1, quote = 0;
3008 int parsequotes = (s[1] == '"') ? 1 : 0;
3009
3010 /* Has argument */
3011 arg = ++s;
3012 for (; *s; s++) {
3013 if (*s == '(' && !quote) {
3014 paren++;
3015 } else if (*s == ')' && !quote) {
3016 /* Count parentheses, unless they're within quotes (or backslashed, below) */
3017 paren--;
3018 } else if (*s == '"' && parsequotes) {
3019 /* Leave embedded quotes alone, unless they are the first character */
3020 quote = quote ? 0 : 1;
3021 ast_copy_string(s, s + 1, INT_MAX);
3022 s--;
3023 } else if (*s == '\\') {
3024 if (!quote) {
3025 /* If a backslash is found outside of quotes, remove it */
3026 ast_copy_string(s, s + 1, INT_MAX);
3027 } else if (quote && s[1] == '"') {
3028 /* Backslash for a quote character within quotes, remove the backslash */
3029 ast_copy_string(s, s + 1, INT_MAX);
3030 } else {
3031 /* Backslash within quotes, keep both characters */
3032 s++;
3033 }
3034 }
3035
3036 if (paren == 0) {
3037 break;
3038 }
3039 }
3040 /* This will find the closing paren we found above, or none, if the string ended before we found one. */
3041 if ((s = strchr(s, ')'))) {
3042 if (argloc) {
3043 args[argloc - 1] = arg;
3044 }
3045 *s++ = '\0';
3046 } else {
3047 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
3048 res = -1;
3049 break;
3050 }
3051 } else if (argloc) {
3052 args[argloc - 1] = "";
3053 }
3054 if (!options[curarg].flag) {
3055 ast_log(LOG_WARNING, "Unrecognized option: '%c'\n", curarg);
3056 }
3057 if (flaglen == 32) {
3058 ast_set_flag(flags, options[curarg].flag);
3059 } else {
3060 ast_set_flag64(flags64, options[curarg].flag);
3061 }
3062 }
3063
3064 return res;
3065 }
3066
3067 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
3068 {
3069 return parse_options(options, flags, args, optstr, 32);
3070 }
3071
3072 int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
3073 {
3074 return parse_options(options, flags, args, optstr, 64);
3075 }
3076
3077 void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
3078 {
3079 unsigned int i, found = 0;
3080 for (i = 32; i < 128 && found < len; i++) {
3081 if (ast_test_flag64(flags, options[i].flag)) {
3082 buf[found++] = i;
3083 }
3084 }
3085 buf[found] = '\0';
3086 }
3087
3088 int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
3089 {
3090 int i;
3091 *consumed = 1;
3092 *result = 0;
3093 if (ast_strlen_zero(stream)) {
3094 *consumed = 0;
3095 return -1;
3096 }
3097
3098 if (*stream == '\\') {
3099 *consumed = 2;
3100 switch (*(stream + 1)) {
3101 case 'n':
3102 *result = '\n';
3103 break;
3104 case 'r':
3105 *result = '\r';
3106 break;
3107 case 't':
3108 *result = '\t';
3109 break;
3110 case 'x':
3111 /* Hexadecimal */
3112 if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
3113 *consumed = 3;
3114 if (*(stream + 2) <= '9') {
3115 *result = *(stream + 2) - '0';
3116 } else if (*(stream + 2) <= 'F') {
3117 *result = *(stream + 2) - 'A' + 10;
3118 } else {
3119 *result = *(stream + 2) - 'a' + 10;
3120 }
3121 } else {
3122 ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
3123 return -1;
3124 }
3125
3126 if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
3127 *consumed = 4;
3128 *result <<= 4;
3129 if (*(stream + 3) <= '9') {
3130 *result += *(stream + 3) - '0';
3131 } else if (*(stream + 3) <= 'F') {
3132 *result += *(stream + 3) - 'A' + 10;
3133 } else {
3134 *result += *(stream + 3) - 'a' + 10;
3135 }
3136 }
3137 break;
3138 case '0':
3139 /* Octal */
3140 *consumed = 2;
3141 for (i = 2; ; i++) {
3142 if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
3143 (*consumed)++;
3144 ast_debug(5, "result was %d, ", *result);
3145 *result <<= 3;
3146 *result += *(stream + i) - '0';
3147 ast_debug(5, "is now %d\n", *result);
3148 } else {
3149 break;
3150 }
3151 }
3152 break;
3153 default:
3154 *result = *(stream + 1);
3155 }
3156 } else {
3157 *result = *stream;
3158 *consumed = 1;
3159 }
3160 return 0;
3161 }
3162
3163 char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
3164 {
3165 char *cur = result;
3166 size_t consumed;
3167
3168 while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
3169 cur++;
3170 stream += consumed;
3171 }
3172 *cur = '\0';
3173 return result;
3174 }
3175
3176 int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
3177 {
3178 char next, *buf;
3179 size_t offset = 0;
3180 size_t consumed;
3181
3182 if (strchr(stream, '\\')) {
3183 while (!ast_get_encoded_char(stream, &next, &consumed)) {
3184 if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
3185 ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
3186 }
3187 if (offset + 2 > ast_str_size(*str)) {
3188 break;
3189 }
3190 buf = ast_str_buffer(*str);
3191 buf[offset++] = next;
3192 stream += consumed;
3193 }
3194 buf = ast_str_buffer(*str);
3195 buf[offset++] = '\0';
3196 ast_str_update(*str);
3197 } else {
3198 ast_str_set(str, maxlen, "%s", stream);
3199 }
3200 return 0;
3201 }
3202
3203 void ast_close_fds_above_n(int n)
3204 {
3205 closefrom(n + 1);
3206 }
3207
3208 int ast_safe_fork(int stop_reaper)
3209 {
3210 sigset_t signal_set, old_set;
3211 int pid;
3212
3213 /* Don't let the default signal handler for children reap our status */
3214 if (stop_reaper) {
3215 ast_replace_sigchld();
3216 }
3217
3218 /* GCC 4.9 gives a bogus "right-hand operand of comma expression has
3219 * no effect" warning */
3220 (void) sigfillset(&signal_set);
3221 pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
3222
3223 pid = fork();
3224
3225 if (pid != 0) {
3226 /* Fork failed or parent */
3227 pthread_sigmask(SIG_SETMASK, &old_set, NULL);
3228 if (!stop_reaper && pid > 0) {
3229 struct zombie *cur = ast_calloc(1, sizeof(*cur));
3230 if (cur) {
3231 cur->pid = pid;
3232 AST_LIST_LOCK(&zombies);
3233 AST_LIST_INSERT_TAIL(&zombies, cur, list);
3234 AST_LIST_UNLOCK(&zombies);
3235 if (shaun_of_the_dead_thread == AST_PTHREADT_NULL) {
3236 if (ast_pthread_create_background(&shaun_of_the_dead_thread, NULL, shaun_of_the_dead, NULL)) {
3237 ast_log(LOG_ERROR, "Shaun of the Dead wants to kill zombies, but can't?!!\n");
3238 shaun_of_the_dead_thread = AST_PTHREADT_NULL;
3239 }
3240 }
3241 }
3242 }
3243 return pid;
3244 } else {
3245 /* Child */
3246 #ifdef HAVE_CAP
3247 cap_set_proc(child_cap);
3248 #endif
3249
3250 /* Before we unblock our signals, return our trapped signals back to the defaults */
3251 signal(SIGHUP, SIG_DFL);
3252 signal(SIGCHLD, SIG_DFL);
3253 signal(SIGINT, SIG_DFL);
3254 signal(SIGURG, SIG_DFL);
3255 signal(SIGTERM, SIG_DFL);
3256 signal(SIGPIPE, SIG_DFL);
3257 signal(SIGXFSZ, SIG_DFL);
3258
3259 /* unblock important signal handlers */
3260 if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
3261 ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
3262 _exit(1);
3263 }
3264
3265 return pid;
3266 }
3267 }
3268
3269 void ast_safe_fork_cleanup(void)
3270 {
3271 ast_unreplace_sigchld();
3272 }
3273
3274 int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
3275 {
3276 int res;
3277 char u[10];
3278 #ifdef HAVE_LONG_DOUBLE_WIDER
3279 long double amount;
3280 #define FMT "%30Lf%9s"
3281 #else
3282 double amount;
3283 #define FMT "%30lf%9s"
3284 #endif
3285 if (!timestr) {
3286 return -1;
3287 }
3288
3289 res = sscanf(timestr, FMT, &amount, u);
3290
3291 if (res == 0 || res == EOF) {
3292 #undef FMT
3293 return -1;
3294 } else if (res == 2) {
3295 switch (u[0]) {
3296 case 'h':
3297 case 'H':
3298 unit = TIMELEN_HOURS;
3299 if (u[1] != '\0') {
3300 return -1;
3301 }
3302 break;
3303 case 's':
3304 case 'S':
3305 unit = TIMELEN_SECONDS;
3306 if (u[1] != '\0') {
3307 return -1;
3308 }
3309 break;
3310 case 'm':
3311 case 'M':
3312 if (toupper(u[1]) == 'S') {
3313 unit = TIMELEN_MILLISECONDS;
3314 if (u[2] != '\0') {
3315 return -1;
3316 }
3317 } else if (u[1] == '\0') {
3318 unit = TIMELEN_MINUTES;
3319 } else {
3320 return -1;
3321 }
3322 break;
3323 default:
3324 return -1;
3325 }
3326 }
3327
3328 switch (unit) {
3329 case TIMELEN_HOURS:
3330 amount *= 60;
3331 /* fall-through */
3332 case TIMELEN_MINUTES:
3333 amount *= 60;
3334 /* fall-through */
3335 case TIMELEN_SECONDS:
3336 amount *= 1000;
3337 /* fall-through */
3338 case TIMELEN_MILLISECONDS:
3339 ;
3340 }
3341 *result = amount > INT_MAX ? INT_MAX : (int) amount;
3342 return 0;
3343 }
3344
3345 struct stasis_topic *ast_queue_topic_all(void)
3346 {
3347 return queue_topic_all;
3348 }
3349
3350 struct stasis_topic *ast_queue_topic(const char *queuename)
3351 {
3352 return stasis_topic_pool_get_topic(queue_topic_pool, queuename);
3353 }
3354
3355 static void app_cleanup(void)
3356 {
3357 #ifdef HAS_CAP
3358 cap_free(child_cap);
3359 #endif
3360 ao2_cleanup(queue_topic_pool);
3361 queue_topic_pool = NULL;
3362 ao2_cleanup(queue_topic_all);
3363 queue_topic_all = NULL;
3364 }
3365
3366 int app_init(void)
3367 {
3368 ast_register_cleanup(app_cleanup);
3369 #ifdef HAVE_CAP
3370 child_cap = cap_from_text("cap_net_admin-eip");
3371 #endif
3372 queue_topic_all = stasis_topic_create("queue:all");
3373 if (!queue_topic_all) {
3374 return -1;
3375 }
3376 queue_topic_pool = stasis_topic_pool_create(queue_topic_all);
3377 if (!queue_topic_pool) {
3378 return -1;
3379 }
3380 return 0;
3381 }