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