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